class Display(base_display.DisplayBase): """ Control Raspberry Pi Sense Hat LED Matrix """ def __init__(self): self.sense = SenseHat() self.defer = None def cb_show_text(self, *args, **kwargs): self.defer = None def show_text(self, text): self.show(text, None, None) def show(self, text, textcolor, bgcolor): if not textcolor: textcolor = (0xff,0xff,0xff) if not bgcolor: bgcolor = (0,0,0) if self.defer is None: self.sense.set_rotation(90, False) self.defer = threads.defer_to_thread(self.sense.show_message, text, text_colour=textcolor, back_colour=bgcolor) self.defer.addCallback(self.cb_show_text) self.defer.addErrback(self.cb_show_text) def clear(self): self.sense.clear()
def main(): # Initialization stuff sense = SenseHat() sense.low_light = True # Display a random pixel matrix pixelValues = [ [ random.randint( 0, 255 ) for j in range( 3 ) ] for i in range( 64 ) ] sense.set_pixels( pixelValues ) time.sleep( 3 ) # Create a colour 'beat' for i in range( 3 ): sense.clear( 255, 0, 0 ) time.sleep ( 0.333 ) sense.clear( 0, 255, 0 ) time.sleep ( 0.333 ) sense.clear( 0, 0, 255 ) time.sleep ( 0.333 ) # Toy around with text display message = "Einfach Mensch..." sense.show_message( message, 0.05 ) rotation = 0 for letter in message: sense.set_rotation( rotation, False ) rotation += 90 if rotation == 270: rotation = 0 sense.show_letter( letter ) time.sleep( 0.24 ) sense.clear()
def new_game(): global sense, a, b, r, t, m, w, k, y, x, h print("new_game ") #Sense hat reset sense.stick.direction_up = None sense.stick.direction_down = None sense.stick.direction_right = None sense.stick.direction_left = None sense.stick.direction_middle = None sense = SenseHat() sense.set_rotation(180) sense.clear() #Sense hat reset func sense.set_pixels(imagemenu) r = randint(0,4) t = randint(0,7) m = randint(4,7) w = randint(0,7) k = randint(2,6) y = 0 x = 0 a, b = (3, 4) sense.stick.get_events()
def menu(): global sense, time1, time2, r, t, m, w, k, a, b, elapsed sense = SenseHat() sense.set_rotation(180) sense.clear() sense.set_pixels(imagemenu) sense.stick.get_events() while True: print (" new game1",a," ",b) y1 = sense.get_accelerometer_raw()['y'] y1 = round(y1, 0) if y1 == -1: sense.show_message("Highscore '%s'"% (h)) sense.set_pixels(imagemenu) for event in sense.stick.get_events(): if event.action == "pressed" and event.direction == "middle": elapsed = timedelta(seconds=0) sense.set_rotation(180) sense.stick.direction_up = move_up sense.stick.direction_down = move_down sense.stick.direction_right = move_right sense.stick.direction_left = move_left x=0 y=0 time1 = datetime.now() print(elapsed, " elapsed and e ", e) while elapsed < e: sense.clear() draw_player() test = draw_enemy(x, y) print("menu nivel1 ",test) if test == 1: new_game() break sleep(0.25) y = y+1 if y > 7: r = randint(0,7) t = randint(0,7) m = randint(0,7) y = 0 x = x+1 if x > 7: w = randint(0,7) k = randint(0,7) x = 0 if elapsed > e: sense.show_message("Next level", scroll_speed=0.05) sense.set_pixels(imagesmile) sleep(1) level_2(x,y) new_game() break if event.action == "pressed" and (event.direction == "up" or event.direction == "down" or event.direction == "left" or event.direction == "right"): return
def sensors(): from sense_hat import SenseHat sense = SenseHat() tempC = sense.get_temperature() # obtains temperature in Celsius from sensor tempC = round(tempC, 1) tempF = c_to_f(tempC) # conversion from Celsius to Fahrenheit tempF = round(tempF, 1) print "\nThe temperature at the Sense Hat is", tempC, "C or", tempF, "F" humidity = sense.get_humidity() humidity = round(humidity, 1) print "The relative humidity at the Sense Hat is", humidity, "%" pressure = sense.get_pressure() pressure = round(pressure, 1) print "The atmospheric pressure at the Sense Hat is", pressure, "mbar\n" # outputing the temp, humidity, and pressure to the matrix sense.clear() # clear the 8x8 matrix sense.set_rotation(0) # sets orientation of Sense Hat matrix # setting colors for the scrolling text on the matrix red = (255, 0, 0) green = (0, 255, 0) blue = (0, 0, 255) speed = 0.02 # speed of text scroll (0.10 is default) sleep = 0.2 # time of pause in seconds sense.show_message("Temp:", text_colour=red, scroll_speed=speed) sense.show_message(str(tempC), text_colour=red, scroll_speed=speed) sense.show_message("C", text_colour=red, scroll_speed=speed) sense.show_message("or", text_colour=red, scroll_speed=speed) sense.show_message(str(tempF), text_colour=red, scroll_speed=speed) sense.show_message("F", text_colour=red, scroll_speed=speed) time.sleep(sleep) sense.show_message("Humidity:", text_colour=green, scroll_speed=speed) sense.show_message(str(humidity), text_colour=green, scroll_speed=speed) sense.show_message("%", text_colour=green, scroll_speed=speed) time.sleep(sleep) sense.show_message("Pressure:", text_colour=blue, scroll_speed=speed) sense.show_message(str(pressure), text_colour=blue, scroll_speed=speed) sense.show_message("mbar", text_colour=blue, scroll_speed=speed) sense.clear()
def show_tph(): sense = SenseHat() t = 0 h = 0 p = 0 while p < 1: p = sense.get_pressure() time.sleep(1) t = sense.get_temperature() h = sense.get_humidity() t = round(t, 1) p = round(p, 0) h = round(h, 0) msg = "P{0}H{1}".format(p,h) msg1 = "T{0}".format(t) sense.set_rotation(rotate_degree) sense.show_message(msg, text_colour=cadetblue) sense.show_message(msg1, text_colour=red)
class Display(base_display.DisplayBase): """ Control Raspberry Pi Sense Hat LED Matrix """ def __init__(self): self.sense = SenseHat() self.defer = None def cb_show_text(self, *args, **kwargs): self.defer = None def show_text(self, text): if self.defer is None: self.sense.set_rotation(90, False) self.defer = threads.defer_to_thread(self.sense.show_message, text) self.defer.addCallback(self.cb_show_text) self.defer.addErrback(self.cb_show_text) def clear(self): self.sense.clear()
B = 21 GPIO.setmode(GPIO.BCM) for pin in [UP, DOWN, LEFT, RIGHT, A, B]: GPIO.setup(pin, GPIO.IN, GPIO.PUD_UP) print("Press Escape to quit") time.sleep(1) pygame.init() pygame.display.set_mode((640, 480)) sense = SenseHat() sense.clear() # Blank the LED matrix sense.set_rotation(270) # Flight orientation # 0, 0 = Top left # 7, 7 = Bottom right UP_PIXELS = [[3, 0], [4, 0]] DOWN_PIXELS = [[3, 7], [4, 7]] LEFT_PIXELS = [[0, 3], [0, 4]] RIGHT_PIXELS = [[7, 3], [7, 4]] CENTRE_PIXELS = [[3, 3], [4, 3], [3, 4], [4, 4]] def set_pixels(pixels, col): for p in pixels: sense.set_pixel(p[0], p[1], col[0], col[1], col[2])
print("RasPi_cpuTempC: %s C" % cpuTempC) print("RasPi_cpuTempF: %s F" % cpuTempF) #get SenseHat CPU reading ap = SenseHat() SHtempC = ap.get_temperature() SHtempC = round(SHtempC, 3) SHtempF = ((SHtempC/5)*9)+32 SHtempF = round(SHtempF, 3) Humidity = ap.get_humidity() Humidity = round(Humidity, 3) print("SenseHat_TempC: %s C" % SHtempC) print("SenseHat_TempF: %s F" % SHtempF) # Show temp on console print("Humidity: %s" % Humidity) ap.set_rotation(180) # Set LED matrix to scroll from right to left w/power plugin up top #get serial number: serial = subprocess.check_output("sed -n 's/^Serial\s*: 0*//p' /proc/cpuinfo", shell=True) serial = serial.decode() serial.replace("\n","") print("Serial# is: %s" % serial) #get hardware number: hardware = subprocess.check_output("sed -n 's/^Hardware\s*: 0*//p' /proc/cpuinfo", shell=True) hardware = hardware.decode() hardware.replace("\n","") #get linux version linux_ver = subprocess.check_output("cat /proc/version|cut -d' ' -f 3", shell=True) linux_ver = linux_ver.decode()
e,e,y,b,b,y,e,e, e,y,y,y,y,y,y,e ] sense.set_pixels(image1) time.sleep(2) sense.set_pixels(image2) time.sleep(2) sense.set_pixels(image3) time.sleep(2) sense.set_pixels(image4) time.sleep(2) sense.set_pixels(image5) sense.set_rotation(90) time.sleep(0.5) sense.set_rotation(180) time.sleep(0.5) sense.set_rotation(270) time.sleep(0.5) sense.set_rotation(180) time.sleep(0.5) sense.set_pixels(image4) time.sleep(2) sense.set_pixels(image3) time.sleep(2) sense.set_pixels(image2) time.sleep(2) sense.set_pixels(image1)
class SenseHATPlugin(EPLPluginBase): def __init__(self, init): super(SenseHATPlugin, self).__init__(init) self.getLogger().info("SenseHATPlugin initialised with config: %s" % self.getConfig()) self.sense = SenseHat() @EPLAction("action<integer >") def setRotation(self, angle=None): """ Orientation of the message/image @param message: Orientation of the message, The supported values of orientation are 0, 90, 180, and 270.. """ if angle == None: angle = 90 self.sense.set_rotation(angle) @EPLAction("action<integer, integer, integer, integer, integer >") def setPixel(self, x, y, r, g, b): self.sense.set_pixel(x, y, r, g, b) @EPLAction("action< sequence <sequence <integer> > >") def setPixels(self, pixels): if not isinstance(pixels, list): return self.sense.set_pixels(pixels) @EPLAction("action< >") def clear(self): self.sense.clear() @EPLAction("action< integer, integer, integer >") def Clear(self, r, g, b): self.sense.clear(r, g, b) @EPLAction("action<string >") def showMessage(self, message): self.sense.show_message(message) @EPLAction("action<string, float, sequence<integer>, sequence<integer> >") def displayMessage(self, message, scrollingSpeed=None, textColor=None, backgroundColor=None): """ This method will scrolls a text message across the LED Matrix. @param message: The Scrolling message to be displayed. @param scrollingSpeed: Scrolling message speed. @param textColor: The text color of the scrolling message i.e [R G B] . @param backgroundColor: The background color of the scrolling message [R G B]. """ if scrollingSpeed == None: scrollingSpeed = 0.1 if (textColor == None) or (not isinstance(textColor, list)): textColor = [255, 255, 255] if (backgroundColor == None) or (not isinstance(backgroundColor, list)): backgroundColor = [0, 0, 0] self.sense.show_message(message, scroll_speed=scrollingSpeed, text_colour=textColor, back_colour=backgroundColor) @EPLAction("action<string >") def showLetter(self, letter): if not isinstance(letter, basestring): return self.sense.show_letter(letter) @EPLAction("action<boolean >") def lowLight(self, islowLight): self.sense.low_light = islowLight @EPLAction("action<string >") def loadImage(self, imagePath): self.sense.load_image(imagePath) ########################################################################################################## # Environmental sensors ########################################################################################################## @EPLAction("action<> returns float") def getHumidity(self): humidity = self.sense.get_humidity() return round(humidity, 2) @EPLAction("action<> returns float") def getTemperature(self): temp = self.sense.get_temperature() return round(temp, 2) @EPLAction("action<> returns float") def getTemperatureFromHumidity(self): temp = self.sense.get_temperature_from_humidity() return round(temp, 2) @EPLAction("action<> returns float") def getTemperatureFromPressure(self): temp = self.sense.get_temperature_from_pressure() return round(temp, 2) @EPLAction("action<> returns float") def getPressure(self): pressure = self.sense.get_pressure() return round(pressure, 2) ########################################################################################################## # Joystick ########################################################################################################## @EPLAction("action<boolean > returns com.apamax.sensehat.InputEvent") def waitForEvent(self, emptyBuffer=False): jevent = self.sense.stick.wait_for_event(emptybuffer=emptyBuffer) evtInstance = Event( 'com.apamax.sensehat.InputEvent', { "actionValue": jevent.action, "directionValue": jevent.direction, "timestamp": jevent.timestamp }) return evtInstance @EPLAction("action<> returns sequence<com.apamax.sensehat.InputEvent >") def getEvents(self): events = list() for event in self.sense.stick.get_events(): evtInstance = Event( 'com.apamax.sensehat.InputEvent', { "actionValue": jevent.action, "directionValue": jevent.direction, "timestamp": jevent.timestamp }) events.append(evtInstance) return events def pushed_up(event): if event.action == ACTION_RELEASED: joyevt = Event('com.apamax.sensehat.JoystickControl', {"controlType": 1}) Correlator.sendTo("sensedhat_data", joyevt) def pushed_down(event): if event.action == ACTION_RELEASED: joyevt = Event('com.apamax.sensehat.JoystickControl', {"controlType": 2}) Correlator.sendTo("sensedhat_data", joyevt) def pushed_left(event): if event.action == ACTION_RELEASED: joyevt = Event('com.apamax.sensehat.JoystickControl', {"controlType": 3}) Correlator.sendTo("sensedhat_data", joyevt) def pushed_right(event): if event.action == ACTION_RELEASED: joyevt = Event('com.apamax.sensehat.JoystickControl', {"controlType": 4}) Correlator.sendTo("sensedhat_data", joyevt) def pushed_in(event): if event.action == ACTION_RELEASED: self.sense.show_message(str(round(sense.temp, 1)), 0.05, b) ########################################################################################################## # IMU Sensor ########################################################################################################## @EPLAction("action<boolean, boolean, boolean >") def setIMUConfig(self, compassEnabled, gyroscopeEnabled, accelerometerEnabled): ''' Enables and disables the gyroscope, accelerometer and/or magnetometer contribution to the get orientation functions @param compassEnabled : enable compass @param gyroscopeEnabled : enable gyroscope @param accelerometerEnabled : enable accelerometer ''' self.sense.set_imu_config(compassEnabled, gyroscopeEnabled, accelerometerEnabled) @EPLAction("action< > returns com.apamax.sensehat.IMUData") def getOrientationRadians(self): ''' Gets the current orientation in radians using the aircraft principal axes of pitch, roll and yaw @return event with pitch, roll and yaw values. Values are floats representing the angle of the axis in radians ''' pitch, roll, yaw = self.sense.get_orientation_radians().values() evtInstance = Event('com.apamax.sensehat.IMUData', { "pitch": pitch, "roll": roll, "yaw": yaw }) return evtInstance @EPLAction("action< > returns com.apamax.sensehat.IMUData") def getOrientationDegrees(self): ''' Gets the current orientation in degrees using the aircraft principal axes of pitch, roll and yaw @return event with pitch, roll and yaw values. Values are Floats representing the angle of the axis in degrees ''' pitch, roll, yaw = self.sense.get_orientation_degrees().values() evtInstance = Event('com.apamax.sensehat.IMUData', { "pitch": pitch, "roll": roll, "yaw": yaw }) return evtInstance @EPLAction("action< > returns com.apamax.sensehat.IMUData") def getOrientation(self): ''' @return event with pitch, roll and yaw representing the angle of the axis in degrees ''' pitch, roll, yaw = self.sense.get_orientation().values() evtInstance = Event('com.apamax.sensehat.IMUData', { "pitch": pitch, "roll": roll, "yaw": yaw }) return evtInstance @EPLAction("action< > returns float") def getCompass(self): ''' Calls set_imu_config internally in Python core to disable the gyroscope and accelerometer then gets the direction of North from the magnetometer in degrees @return The direction of North ''' return self.sense.get_compass() @EPLAction("action< > returns com.apamax.sensehat.IMUDataRaw") def getCompassRaw(self): ''' Gets the raw x, y and z axis magnetometer data @return event representing the magnetic intensity of the axis in microteslas (uT) ''' x, y, z = self.sense.get_compass_raw().values() evtInstance = Event('com.apamax.sensehat.IMUDataRaw', { "x": x, "y": y, "z": z }) return evtInstance @EPLAction("action< > returns com.apamax.sensehat.IMUData") def getGyroscope(self): ''' Calls set_imu_config internally in Python core to disable the magnetometer and accelerometer then gets the current orientation from the gyroscope only @return event with pitch, roll and yaw representing the angle of the axis in degrees ''' pitch, roll, yaw = self.sense.get_gyroscope().values() evtInstance = Event('com.apamax.sensehat.IMUData', { "pitch": pitch, "roll": roll, "yaw": yaw }) return evtInstance @EPLAction("action< > returns com.apamax.sensehat.IMUDataRaw") def getGyroscopeRaw(self): ''' Gets the raw x, y and z axis gyroscope data @return event representing the rotational intensity of the axis in radians per second ''' x, y, z = sense.get_gyroscope_raw().values() evtInstance = Event('com.apamax.sensehat.IMUDataRaw', { "x": x, "y": y, "z": z }) return evtInstance @EPLAction("action< > returns com.apamax.sensehat.IMUData") def getAccelerometer(self): ''' Calls set_imu_config in Python core to disable the magnetometer and gyroscope then gets the current orientation from the accelerometer only @return Object representing the angle of the axis in degrees ''' pitch, roll, yaw = self.sense.get_accelerometer().values() evtInstance = Event('com.apamax.sensehat.IMUData', { "pitch": pitch, "roll": roll, "yaw": yaw }) return evtInstance @EPLAction("action< > returns com.apamax.sensehat.IMUDataRaw") def getAccelerometerRaw(self): ''' Gets the raw x, y and z axis accelerometer data @return event representing the acceleration intensity of the axis in Gs ''' x, y, z = sense.get_accelerometer_raw().values() evtInstance = Event('com.apamax.sensehat.IMUDataRaw', { "x": x, "y": y, "z": z }) return evtInstance
pixelOffset = 0 index = 0 for indexLoop in range(0, 4): for counterLoop in range(0, 4): if (hour >= 10): clockImage[index] = number[int(hour/10)*16+pixelOffset] clockImage[index+4] = number[int(hour%10)*16+pixelOffset] clockImage[index+32] = number[int(minute/10)*16+pixelOffset] clockImage[index+36] = number[int(minute%10)*16+pixelOffset] pixelOffset = pixelOffset + 1 index = index + 1 index = index + 4 # Colour the hours and minutes for index in range(0, 64): if (clockImage[index]): if index < 32: clockImage[index] = hourColour else: clockImage[index] = minuteColour else: clockImage[index] = empty # Display the time sense.set_rotation(90) # Optional sense.low_light = True # Optional sense.set_pixels(clockImage)
forecast_bom_today = "" forecast_bom_tomorrow = "" forecast_file_today = "" forecast_toggle = 0 global_init=True readings = {} # pywws data if config.getboolean('Output','PYWWS_PUBLISH'): ds = DataStore.data_store(config.get('PYWWS','STORAGE')) dstatus = DataStore.status(config.get('PYWWS','STORAGE')) if config.getboolean('Output','ADA_LCD'): AdaLcd.clear() if config.getboolean('Output','SENSEHAT_DISPLAY'): # Set up display PiSenseHat.clear() PiSenseHat.set_rotation(config.get('SenseHat','ROTATION')) if config.getboolean('Sensors','ENOCEAN'): eoCommunicator = eoSerialCommunicator(port=config.get('EnOcean','PORT')) eoCommunicator.start() # Warm up sensors print "Waiting for sensors to settle" for i in range(1,6): Sample() time.sleep(1) global_init=False if config.getboolean('Sensors','FORECAST_BOM'): ForecastBoM() if config.getboolean('Sensors','FORECAST_FILE'): ForecastFile() Sample() print "Scheduling events..."
from sense_hat import SenseHat import time sense = SenseHat() sense.show_letter("J") for r in (0, 90, 180, 270, 0, 90, 180, 270): sense.set_rotation(r) time.sleep(0.5) # From here: https://github.com/raspberrypilearning/getting-started-with-the-sense-hat/blob/master/code/spinning_j.py
# Connect to the influx db client = InfluxDBClient(host=IP_RP4, port=PORT, username=USER_NAME, password=PWD, database=DB_NAME, timeout=10) # Sends the data to the influxdb server success = client.write_points(points, time_precision='ms') client.close() sensor = SenseHat() sensor.set_rotation(270) if success: # The transfer succeeded, remove the data samples from RP3 volume directory, # have to walk through the directories in volume, because rmtree also deletes # the root, i.e. the volume directory, but don't want that... for roots, dirs, file in os.walk('volume'): for d in dirs: shutil.rmtree(join('volume', d)) # Also clear the LEDs on the senseHat, if there were a signal sensor.clear() else: # Transfer crashed, display a red '!' on the x = [255, 0, 0] o = [0, 0, 0]
from sense_hat import SenseHat from time import sleep sense = SenseHat() sense.set_rotation(r=90) red = (255, 0, 0) blue = (0, 0, 255) green = (0, 255, 0) black = (0, 0, 0) white = (255, 255, 255) sense.show_letter("O", red) sleep(1) sense.show_letter("M", blue) sleep(1) sense.show_letter("G", green) sleep(1) sense.show_letter("!", white) sleep(1) sense.clear()
if ('y' in choice): random_colour = True #Runs for 10 wins while (True): image_pixels = [ b, b, b, b, b, b, b, b, b, b, b, y, b, b, b, b, b, b, y, y, y, b, b, b, b, y, b, y, b, y, b, b, b, b, b, y, b, b, b, b, b, b, b, y, b, b, b, b, b, b, b, y, b, b, b, b, b, b, b, y, b, b, b, b ] #Set new pixel and rotation values sense.set_pixels(image_pixels) rotation = rand.randint(1, 4) sense.set_rotation(rotation * 90 % 360) #Pause for 1 second to admire the effect time.sleep(delay) #Increase player's reaction time delay *= 0.95 #Refresh screen sense.clear() #Collect IMU values acceleration = sense.get_accelerometer_raw() x_ = acceleration['x'] y_ = acceleration['y'] z_ = acceleration['z']
if sense.humidity > 80 and sense.temp > 20: #Test if rainbow comes #if 1: # Send push notification conn = httplib.HTTPSConnection("api.pushover.net:443") conn.request("POST", "/1/messages.json", urllib.urlencode({ "token": "axpw6yrhai5pcnoyhasfuzvjdiox8e", "user": "******", "message": "Wow, there is rainbow today, have fun", }), { "Content-type": "application/x-www-form-urlencoded" }) conn.getresponse() sense.set_pixels(rainbow) time.sleep(5) ap.set_rotation(180) # Set LED matrix to scroll from right to left ap.show_message("Temperature: %.1f C" % temp, scroll_speed=0.10, text_colour=[0, 255, 0]) time.sleep(2) # Wait 1 second ap.show_message("Humidity: %.1f H" % humidity, scroll_speed=0.10, text_colour=[255, 0, 0]) time.sleep(2) # Wait 1 second ap.show_message("Pressure: %.1f Millibars" % pressure, scroll_speed=0.10, text_colour=[0, 0, 255]) ap.clear() # Clear LED matrix elif sense.humidity > 80 and sense.temp < 0 : # Send push notification conn = httplib.HTTPSConnection("api.pushover.net:443") conn.request("POST", "/1/messages.json", urllib.urlencode({ "token": "axpw6yrhai5pcnoyhasfuzvjdiox8e", "user": "******", "message": "It's snowing today",
class Host(object): def __init__(self, rotation = 0, low_light = False, calibration = {}, smoothing = 0, register_services = True, environmental_publishing = False, environmental_publishing_rate = 1, imu_publishing = True, #imu_publishing_mode = "get_gyroscope_rpy", imu_publishing_mode = "get_sensor_msg", imu_publishing_config = "1|1|1", imu_publishing_rate = 0.01, stick_publishing = False, stick_sampling = 0.2): """Constructor method""" #IMU_FRAME = rospy.get_param('~imu_frame', 'imu_link') IMU_FRAME="imu_frame" # Init sensor self.sense = SenseHat() self.sense.clear(0,0,0) self.sense.set_rotation(rotation) self.sense.low_light = low_light self.measures = { 'humidity': self.sense.get_humidity, 'temperature_from_humidity': self.sense.get_temperature_from_humidity, 'temperature_from_pressure': self.sense.get_temperature_from_pressure, 'pressure': self.sense.get_pressure, 'compass': self.sense.get_compass, } # Init parameters self.imu_publishing = imu_publishing self.imu_publishing_mode = imu_publishing_mode self.imu_publishing_rate = imu_publishing_rate self.history = {} for measure in self.measures: self.history[measure] = collections.deque([], maxlen = smoothing if smoothing > 0 else None) if smoothing >= 0 else None # Init Lock to serialize access to the LED Matrix self.display_lock = Lock() # Register publishers if self.imu_publishing: self.sense.set_imu_config(*[i=="1" for i in imu_publishing_config.split("|")]) self.imu_pub = rospy.Publisher("imu", Imu, queue_size=10) rospy.loginfo("sensehat_ros initialized") def __del__(self): if self.sense: self.sense.clear(0,0,0) rospy.loginfo("sensehat_ros destroyed") ############################################################################## # Private methods ############################################################################## def _get_sensor_msg_imu(self, timestamp): # 1 g-unit is equal to 9.80665 meter/square second. # Linear Acceleration # 1° × pi/180 = 0.01745rad # Angular velocity # Gyro gunit_to_mps_squ = 9.80665 msg = Imu() msg.header.stamp = timestamp msg.header.frame_id = IMU_FRAME gyr = self.sense.get_gyroscope_raw() acc = self.sense.get_accelerometer_raw() msg.orientation.x = 0.0 msg.orientation.y = 0.0 msg.orientation.z = 0.0 msg.orientation.w = 0.0 msg.orientation_covariance = [-1, 0.0, 0.0, 0.0, 0, 0.0, 0.0, 0.0, 0] #msg.angular_velocity.x = gyr['x'] * np.pi msg.angular_velocity.x = round( gyr['x'] * ( np.pi / 180 ), 8 ) * (-1) # Inverted x axis msg.angular_velocity.y = round( gyr['y'] * ( np.pi / 180 ), 8 ) msg.angular_velocity.z = round( gyr['z'] * ( np.pi / 180 ), 8 ) msg.angular_velocity_covariance = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0] msg.linear_acceleration.x = round((acc['x'] * gunit_to_mps_squ), 8 ) * (-1) # Inverted x axis msg.linear_acceleration.y = round((acc['y'] * gunit_to_mps_squ), 8 ) msg.linear_acceleration.z = round((acc['z'] * gunit_to_mps_squ), 8 ) #msg.linear_acceleration.x = np.radians( acc['x'] ) #msg.linear_acceleration.y = np.radians( acc['y'] ) #msg.linear_acceleration.z = np.radians( acc['z'] ) msg.linear_acceleration_covariance = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0] return msg def _publish_sensor_msg_imu(self, event): imu = self._get_sensor_msg_imu(rospy.Time.now()) rospy.logdebug( "Publishing IMU" ) br = tf2_ros.TransformBroadcaster() self.imu_pub.publish(imu) ############################################################################## # Run ############################################################################## def run(self): if self.imu_publishing: # Start publishing events rospy.Timer(rospy.Duration(self.imu_publishing_rate), self._publish_sensor_msg_imu) rospy.loginfo("sensehat_ros publishing Imu") rospy.spin()
class Host(object): """Main class used by the ROS node supporting dialogue between the ROS framework and the Sense HAT hardware. :param rotation: control Sense HAT LED matrix orientation. Defaults to 0. :type rotation: int, optional :param low_light: enable Sense HAT low-light mode. Defaults to False. :type low_light: bool, optional :param calibration: linear fixing for environmental readings (ex. {"humidity": -20.0} ). Defaults to {}. :type calibration: dict, optional :param smoothing: number of observations to be used for median smoothing (0 = smoothing disabled). Smoothing is applied only to environmental data (humidity, temperature and pressure). Defaults to 0. :type smoothing: int, optional :param register_services: control ROS services registration. Defaults to True. :type register_services: bool, optional :param environmental_publishing: enable automatic publishing of environmental data (rate controlled by environmental_publishing_rate). Defaults to True. :type environmental_publishing: bool, optional :param environmental_publishing_rate: environmental data publication frequency in seconds. Defaults to 12 (5 times a minute). :type environmental_publishing_rate: float, optional :param imu_publishing: enable automatic publishing of IMU data (rate controlled by imu_publishing_rate). Defaults to False. :type imu_publishing: bool, optional :param imu_publishing_mode: specify the Sense HAT API function to be used to get x,y,z/roll,pitch,yaw. Valid values are: get_orientation_radians_rpy, get_orientation_degrees_rpy, get_compass_raw_xyz, get_gyroscope_rpy, get_gyroscope_raw_xyz, get_accelerometer_rpy, get_compass_raw_xyz. Defaults to get_orientation_degrees_rpy. :type imu_publishing_mode: string, optional :param imu_publishing_rate: IMU data publication frequency in seconds. Defaults to 1 (once a second). :type imu_publishing_rate: float, optional :param stick_publishing: enable automatic publishing of stick events. Defaults to True. :type stick_publishing: bool, optional :param stick_sampling: indicates how frequently the Stick is checked for new events. Defaults to 0.2 (5 times a second). :type stick_sampling: float, optional """ def __init__(self, rotation=0, low_light=False, calibration={}, smoothing=0, register_services=True, environmental_publishing=True, environmental_publishing_rate=12, imu_publishing=False, imu_publishing_mode="get_orientation_degrees_rpy", imu_publishing_config="1|1|1", imu_publishing_rate=1, stick_publishing=True, stick_sampling=0.2): """Constructor method""" # Init sensor self.sense = SenseHat() self.sense.clear(0, 0, 0) self.sense.set_rotation(rotation) self.sense.low_light = low_light self.measures = { 'humidity': self.sense.get_humidity, 'temperature_from_humidity': self.sense.get_temperature_from_humidity, 'temperature_from_pressure': self.sense.get_temperature_from_pressure, 'pressure': self.sense.get_pressure, 'compass': self.sense.get_compass, } self.imu_modes = { 'get_orientation_radians_rpy': self.sense.get_orientation_radians, 'get_orientation_degrees_rpy': self.sense.get_orientation_degrees, 'get_compass_raw_xyz': self.sense.get_compass_raw, 'get_gyroscope_rpy': self.sense.get_gyroscope, 'get_gyroscope_raw_xyz': self.sense.get_gyroscope_raw, 'get_accelerometer_rpy': self.sense.get_accelerometer, 'get_accelerometer_raw_xyz': self.sense.get_accelerometer_raw, } # Init parameters self.stick_publishing = stick_publishing self.environmental_publishing = environmental_publishing self.imu_publishing = imu_publishing self.imu_publishing_mode = imu_publishing_mode self.stick_sampling = stick_sampling self.environmental_publishing_rate = environmental_publishing_rate self.imu_publishing_rate = imu_publishing_rate self.calibration = calibration self.register_services = register_services self.smoothing = smoothing self.history = {} for measure in self.measures: self.history[measure] = collections.deque( [], maxlen=smoothing if smoothing > 0 else None) if smoothing >= 0 else None # Init Lock to serialize access to the LED Matrix self.display_lock = Lock() # Register publishers if self.stick_publishing: self.stick_pub = rospy.Publisher("Stick", Stick, queue_size=10) if self.environmental_publishing: self.environmental_pub = rospy.Publisher("Environmental", Environmental, queue_size=10) if self.imu_publishing: self.sense.set_imu_config( *[i == "1" for i in imu_publishing_config.split("|")]) self.imu_pub = rospy.Publisher("IMU", IMU, queue_size=10) # Register services if self.register_services: self.getEnvironmentalService = rospy.Service( "GetEnvironmental", GetEnvironmental, self.getEnvironmental) self.getHumidityService = rospy.Service("GetHumidity", GetHumidity, self.getHumidity) self.getTemperatureService = rospy.Service("GetTemperature", GetTemperature, self.getTemperature) self.getPressureService = rospy.Service("GetPressure", GetPressure, self.getPressure) self.getIMUService = rospy.Service("GetIMU", GetIMU, self.getIMU) self.getCompassService = rospy.Service("GetCompass", GetCompass, self.getCompass) self.emulateStick = rospy.Service("EmulateStick", EmulateStick, self.emulateStick) self.clearService = rospy.Service("Clear", Clear, self.clear) self.setPixelsService = rospy.Service("SetPixels", SetPixels, self.setPixels) self.switchLowLightService = rospy.Service("SwitchLowLight", SwitchLowLight, self.switchLowLight) self.showLetterService = rospy.Service("ShowLetter", ShowLetter, self.showLetter) self.showMessageService = rospy.Service("ShowMessage", ShowMessage, self.showMessage) rospy.loginfo("sensehat_ros initialized") def __del__(self): if self.sense: self.sense.clear(0, 0, 0) rospy.loginfo("sensehat_ros destroyed") ############################################################################## # Private methods ############################################################################## def _get_environmental(self, timestamp): msg = Environmental() msg.header.stamp = timestamp msg.humidity = self._get_measure('humidity') msg.temperature_from_humidity = self._get_measure( 'temperature_from_humidity') msg.temperature_from_pressure = self._get_measure( 'temperature_from_pressure') msg.pressure = self._get_measure('pressure') return msg def _get_imu(self, mode, timestamp): msg = IMU() msg.header.stamp = timestamp msg.mode = mode imu = self.imu_modes[mode]() if mode[-3:] == 'xyz': msg.x, msg.y, msg.z = imu['x'], imu['y'], imu['z'] elif mode[-3:] == 'rpy': msg.x, msg.y, msg.z = imu['roll'], imu['pitch'], imu['yaw'] return msg def _get_measure(self, measure, disableSmooting=False): def _get_measure_median(smoothing): """Return median value from the last <smoothing> elements in the history Args: smoothing (int): values to be extracted from the history Returns: double: median value """ lst = [ history[-i] for i in range(1, 1 + min(smoothing, len(history))) ] n = len(lst) s = sorted(lst) return (sum(s[n // 2 - 1:n // 2 + 1]) / 2.0, s[n // 2])[n % 2] if n else None if not measure in self.measures: raise ValueError('Invalid measure %s' % measure) val = self.measures[measure]() + self.calibration.get(measure, 0.0) history = self.history[measure] if history is not None: history.append(val) if self.smoothing > 0 and not disableSmooting: val = _get_measure_median(self.smoothing) return val def _publish_stick(self, event): for stick_event in self.sense.stick.get_events(): stick = Stick(direction=stick_event.direction, action=stick_event.action) rospy.logdebug("Publishing Stick (D: %s, A: %s)", stick.direction, stick.action) self.stick_pub.publish(stick) def _publish_environmental(self, event): environmental = self._get_environmental(rospy.Time.now()) rospy.logdebug( "Publishing Environmental (H: %s, TH: %s, TP: %s, P: %s)", environmental.humidity, environmental.temperature_from_humidity, environmental.temperature_from_pressure, environmental.pressure) self.environmental_pub.publish(environmental) def _publish_imu(self, event): imu = self._get_imu(self.imu_publishing_mode, rospy.Time.now()) rospy.logdebug( "Publishing IMU (Mode: %s, X: %s, Y: %s, Z: %s)", imu.mode, imu.x, imu.y, imu.z, ) self.imu_pub.publish(imu) ############################################################################## # ROS service methods ############################################################################## def clear(self, req): """ROS service: sets all of the 64 LED matrix pixels to the specified RGB color and waits for the specified amount of seconds""" self.display_lock.acquire() try: self.sense.clear(req.colour) rospy.sleep(req.duration) finally: self.display_lock.release() return ClearResponse() def switchLowLight(self, req): """ROS service: switches on/off the LED matrix \"low light\" mode and returns the current state.""" self.sense.low_light = not self.sense.low_light return SwitchLowLightResponse(low_light=self.sense.low_light) def setPixels(self, req): """ROS service: sets each of the 64 LED matrix pixels to a specific RGB color and waits for the specified amount of seconds.""" self.display_lock.acquire() try: self.sense.set_pixels( list(zip(req.pixels_red, req.pixels_green, req.pixels_blue))) rospy.sleep(req.duration) finally: self.display_lock.release() return SetPixelsResponse() def showLetter(self, req): """ROS service: shows a letter on the LED matrix and waits for the specified amount of seconds.""" self.display_lock.acquire() try: self.sense.show_letter(req.text, req.text_colour, req.back_colour) rospy.sleep(req.duration) finally: self.display_lock.release() return ShowLetterResponse() def showMessage(self, req): """ROS service: scrolls a text message from right to left across the LED matrix and at the specified speed, in the specified colour and background colour.""" self.display_lock.acquire() try: self.sense.show_message(req.text, req.scroll_speed, req.text_colour, req.back_colour) finally: self.display_lock.release() return ShowMessageResponse() def getIMU(self, req): """ROS service: queries Sense HAT IMU sensor. Warning: not allowed when imu_publishing=True due to potential set_imu_config interference.""" if self.imu_publishing: raise RuntimeError( "Method getIMU not allowed when imu_publishing=True (due to potential set_imu_config interference)" ) imu = self._get_imu(req.mode, rospy.Time.now()) rospy.logdebug( "Sending IMU (Mode: %s, X: %s, Y: %s, Z: %s)", imu.mode, imu.x, imu.y, imu.z, ) return imu def getCompass(self, req): """ROS service: gets the direction of North from the magnetometer in degrees. Warning: not allowed when imu_publishing=True due to potential set_imu_config interference.""" if self.imu_publishing: raise RuntimeError( "Method getCompass not allowed when imu_publishing=True due to potential set_imu_config interference" ) compass = self._get_measure('compass', disableSmooting=True) rospy.logdebug("Sending Compass (Compass: %s)", compass) return compass def getHumidity(self, req): """ROS service: gets the percentage of relative humidity from the humidity sensor.""" humidity = self._get_measure('humidity') rospy.logdebug("Sending Humidity (H: %s)", humidity) return humidity def getTemperature(self, req): """ROS service: gets the current temperature in degrees Celsius from the humidity sensor.""" temperature = self._get_measure('temperature_from_humidity') rospy.logdebug("Sending Temperature (TH: %s)", temperature) return temperature def getPressure(self, req): """ROS service: gets the current pressure in Millibars from the pressure sensor.""" pressure = self._get_measure('pressure') rospy.logdebug("Sending Pressure (P: %s)", pressure) return pressure def getEnvironmental(self, req): """ROS service: gets the current humidity and temperature from the humidity sensor and temperature and pressure from the pressure sensor.""" environmental = self._get_environmental(rospy.Time.now()) rospy.logdebug("Sending Environmental (H: %s, TH: %s, TP: %s, P: %s)", environmental.humidity, environmental.temperature_from_humidity, environmental.temperature_from_pressure, environmental.pressure) return environmental def emulateStick(self, req): """ROS service: remotely triggers a stick event without interacting with the Stick device.""" if self.stick_publishing: rospy.loginfo("Emulating Stick (D: %s, A: %s)", req.direction, req.action) stick = Stick(direction=req.direction, action=req.action) self.stick_pub.publish(stick) return EmulateStickResponse() ############################################################################## # Run ############################################################################## def run(self): """Starts configured data publishing (stick, environmental, IMU) and spins waiting for service calls. Triggered by the ROS node after initialization.""" if self.stick_publishing: # Clear buffer self.sense.stick.get_events() # Start publishing events rospy.Timer(rospy.Duration(self.stick_sampling), self._publish_stick) rospy.loginfo("sensehat_ros publishing stick") if self.environmental_publishing: # Start publishing events rospy.Timer(rospy.Duration(self.environmental_publishing_rate), self._publish_environmental) rospy.loginfo("sensehat_ros publishing environmental") if self.imu_publishing: # Start publishing events rospy.Timer(rospy.Duration(self.imu_publishing_rate), self._publish_imu) rospy.loginfo("sensehat_ros publishing IMU") rospy.spin()
import pygame import picamera from pygame.locals import * import sweaty_astronaut_framed as saf import RPi.GPIO as GPIO UP=26 DOWN=13 RIGHT=19 LEFT=20 A=16 B=21 GPIO.setmode(GPIO.BCM) ap = SenseHat() ap.set_rotation(270) def button_pressed(button): #written by Richard global ap global pressed #print(button) pressed = 1 for pin in [UP, DOWN, LEFT, RIGHT, A, B]: GPIO.setup(pin, GPIO.IN, GPIO.PUD_UP) GPIO.add_event_detect(pin, GPIO.FALLING, callback=button_pressed, bouncetime=100) # Logging code by Alfie tmstmp = time.strftime("%Y%m%d-%H%M%S")
from sense_hat import SenseHat hat = SenseHat() hat.set_rotation(180) temp = hat.get_temperature() text = str(round(temp,2)) hat.show_message("Temperature = ", scroll_speed=0.05) hat.show_message(text) temp = hat.get_temperature_from_humidity() text = str(round(temp,2)) hat.show_message(text, text_colour=[127, 0,127])
area = math.pi * (radius_int**2) print ("The circumference is:", circumference, \ ", and the area is:", area) #2: Basic sensehat from sense_hat import SenseHat sense = SenseHat() color_txt = input("Input the text color value") color_bg = input("Input the background color value") speed = input("Input the speed") sense.show_message("This is fun!", text_colour = color_txt, back_colour = color_bg, scroll_speed = speed) sense.set_rotation(180) #3: What if user chooses same colour for both? #4: Program should take Message, Rotation, Colour, Background, Speed # Program should reject rotations above 270 and colours above 255 from sense_hat import SenseHat sense = SenseHat() display_message = input("Enter your message to display:") while True: rotate_int = int(input("Enter your rotation angle.")) if 0 <= rotate_int <= 270 and rotate_int%90 == 0: break
class Sensors(): """Obtain data from the Atmospheric sensors.""" def __init__(self, MQ7_Ro, MQ2_Ro): # Gas sensor ajustments self.MQ7_Ro = MQ7_Ro # Sensor resistance at 100 ppm of CO self.MQ2_Ro = MQ2_Ro # Sensor resistance at 1000 ppm of H2 # Initializing self.spi_comm = spiCommunicator(SPICLK, SPIMOSI, SPIMISO, SPICS) self.sense = SenseHat() print("* Initializing sensors. Please wait 20 seconds...") sys.stdout.flush() self.sense.set_rotation(ROTATION) self.sense.show_message("INITIALIZING...", text_colour=TEXT_COLOUR, scroll_speed=TEXT_SPEED) self.sense.show_letter("-", [255, 0, 0]) time.sleep(20) # Execute a first measurement in order to avoid error data from sensors self.getSensorData() def calibration(self, mq_channel): """ Assuming that the sensor is in clean air, this function calculates the sensor resistance in clean air, and divide it by RO_CLEAN_AIR_FACTOR. Input: mq_channel -> Analog channel where the MQ sensor is connected Output: Ro of the sensor """ ro = 0.0 for i in range(CALIBRATION_SAMPLE_TIMES): ro += self.getResistance(self.spi_comm.read(mq_channel), mq_channel) time.sleep(CALIBRATION_SAMPLE_INTERVAL/1000.0) ro = ro/CALIBRATION_SAMPLE_TIMES if(mq_channel == MQ7_CHANNEL): ro = ro/MQ7_RO_CLEAN_AIR_FACTOR elif(mq_channel == MQ2_CHANNEL): ro = ro/MQ2_RO_CLEAN_AIR_FACTOR return ro def getSensorData(self): """ Obtain the data from the different sensors and return it. Output: Current sensor data """ data = {} mq7_Rs = self.read(MQ7_CHANNEL) mq2_Rs = self.read(MQ2_CHANNEL) # Avoid Rs to be 0 if mq7_Rs == 0: mq7_Rs = 0.001 if mq2_Rs == 0: mq2_Rs = 0.001 # Gas sensors data["CO"] = self.getGasPPM(float(mq7_Rs)/self.MQ7_Ro, MQ7_CHANNEL) data["LPG"] = self.getGasPPM(float(mq2_Rs)/self.MQ2_Ro, MQ7_CHANNEL) # Calculate the real temperature compensating the CPU heating temp1 = self.sense.get_temperature_from_humidity() temp2 = self.sense.get_temperature_from_pressure() temp_cpu = self.getCPUTemperature() temp = (temp1+temp2)/2 real_temp = temp - ((temp_cpu-temp)/CPU_TEMP_FACTOR) # Environment sensors data["Temperature"] = real_temp data["Humidity"] = self.sense.get_humidity() data["Pressure"] = self.sense.get_pressure() # Set screen colors: self.setScreen(data["CO"], data["LPG"]) return data def setScreen(self, CO, LPG): """ Set SenseHat screen depending on the CO and LPG levels. Input: CO -> CO gas level. LPG -> LPG level. """ O = [0, 0, 0] X = COLOURS_LEVELS[4] Y = COLOURS_LEVELS[4] for i in reversed(range(0,4)): if CO < LIMITS['CO'][i]: X = COLOURS_LEVELS[i] if LPG < LIMITS['LPG'][i]: Y = COLOURS_LEVELS[i] screen = [ O, O, X, X, X, O, O, O, O, O, X, X, X, O, O, O, O, O, X, X, X, O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, Y, Y, Y, O, O, O, O, O, Y, Y, Y, O, O, O, O, O, Y, Y, Y, O, O, O ] self.sense.set_pixels(screen) def getCPUTemperature(self): """ Calculate CPU temperature. Output: Current CPU temperature """ command_res = os.popen("vcgencmd measure_temp").readline() t = float(command_res.replace("temp=","").replace("'C\n","")) return(t) def read(self, mq_channel): """ Calculate the current sensor resistance which depens on the different concentration of the target gas. Input: mq_channel -> Analog channel where the MQ sensor is connected Output: Rs of the sensor """ Rs = 0.0 for i in range(READ_SAMPLE_TIMES): adc_value = self.spi_comm.read(mq_channel) Rs += self.getResistance(adc_value, mq_channel) time.sleep(READ_SAMPLE_INTERVAL/1000.0) Rs = Rs/READ_SAMPLE_TIMES return Rs def getResistance(self, adc_value, mq_channel): """ Calculate the current resistance of the sensor given its current voltage. Input: adc_value -> Raw value form the ADC. Voltage = adc*Vref/1024 mq_channel -> Analog channel where the MQ sensor is connected Output: Current resistance of the sensor """ resistance = 0.0 if adc_value == 0: # Avoid division by 0 adc_value = 1 if(mq_channel == MQ7_CHANNEL): resistance = float(MQ7_RL*(1024.0-adc_value)/float(adc_value)) elif(mq_channel == MQ2_CHANNEL): resistance = float(MQ2_RL*(1024.0-adc_value)/float(adc_value)) return resistance def getGasPPM(self, rs_ro_ratio, mq_channel): """ Calculate the ppm of the target gases. Input: rs_ro_ratio -> Value obtained of the division Rs/Ro mq_channel -> Analog channel where the MQ sensor is connected Output: Current gas percentage in the environment """ percentage = 0 if(mq_channel == MQ7_CHANNEL): percentage = self.getMQPPM(rs_ro_ratio, CO_Curve) elif(mq_channel == MQ2_CHANNEL): percentage = self.getMQPPM(rs_ro_ratio, LPG_Curve) return percentage def getMQPPM(self, rs_ro_ratio, mq_curve): """ Calculate the ppm of the target gas using the slope and a point form the line obtained aproximating the sensitivity characteristic curve. x = (y-n)/m Input: rs_ro_ratio -> Value obtained of the division Rs/Ro mq_curve -> Line obtained using two points form the sensitivity characteristic curve Output: Current gas percentage in the environment """ return (math.pow(10, (math.log10(rs_ro_ratio)-mq_curve[1]) / mq_curve[0]))
def get_stick(): for evdev in glob.glob('/sys/class/input/event*'): try: with io.open(os.path.join(evdev, 'device', 'name'), 'r') as f: if f.read().strip() == 'Raspberry Pi Sense HAT Joystick': return os.path.join('/dev', 'input', os.path.basename(evdev)) except IOError as e: sys.exit(1) sys.exit(1) stick_file = io.open(get_stick(),'rb') SH = SenseHat() SH.set_rotation(0) SH.clear() files = [sys.stdin,stick_file] last_hf_time = time.time() last_lf_time = time.time() hf_interval = 0.09 # Approx 10/s lf_interval = 1 hf_enabled = False lf_enabled = False scroll = None class ScrollThread(threading.Thread):
from sense_hat import SenseHat sense = SenseHat() sense.clear() sense.show_letter("M") while True: a = sense.get_accelerometer_raw() x = a["x"] y = a["y"] z = a["z"] x = int(round(x, 0)) y = int(round(y, 0)) z = int(round(z, 0)) print(f"X: {x} Y:{y} Z:{z}") if x == 1: sense.set_rotation(270) elif x == -1: sense.set_rotation(90) elif y == -1: sense.set_rotation(180) else: sense.set_rotation(0)
from sense_hat import SenseHat import time sense = SenseHat() ang = [0,90,180,270,0,90,180,270] i=0 while True: sense.show_message("Hello") time.sleep(0.5) sense.set_rotation(ang[i]) if i <8: i+=1
'If you are using the Pi upside down or sideways you can use this function to correct the orientation of the image being shown.' ) parser.add_argument( 'r', type=int, choices={0, 90, 180, 270}, help= 'The angle to rotate the LED matrix though. 0 is with the Raspberry Pi HDMI port facing downwards.' ) parser.add_argument( 'redraw', type=str2bool, nargs='?', default=True, help= 'Whether or not to redraw what is already being displayed on the LED matrix. Defaults to True' ) args = parser.parse_args() try: from sense_hat import SenseHat sense = SenseHat() sense.set_rotation(args.r, args.redraw) finish({"result": True}) except Exception, e: finish(e, 1)
from sense_hat import SenseHat import os import time import pygame # See http://www.pygame.org/docs from pygame.locals import * print("Press Escape to quit") time.sleep(1) pygame.init() pygame.display.set_mode((640, 480)) sense = SenseHat() sense.clear() # Blank the LED matrix sense.set_rotation(270) # Flight orientation # 0, 0 = Top left # 7, 7 = Bottom right UP_PIXELS = [[3, 0], [4, 0]] DOWN_PIXELS = [[3, 7], [4, 7]] LEFT_PIXELS = [[0, 3], [0, 4]] RIGHT_PIXELS = [[7, 3], [7, 4]] CENTRE_PIXELS = [[3, 3], [4, 3], [3, 4], [4, 4]] def set_pixels(pixels, col): for p in pixels: sense.set_pixel(p[0], p[1], col[0], col[1], col[2])
def weather(): sense = SenseHat() sense.clear() # Get temperature, humidity, pressure, and calculate dewpoint celcius = round(sense.get_temperature(), 1) fahrenheit = round(1.8 * celcius + 32, 1) humidity = round(sense.get_humidity(), 1) pressure = round(sense.get_pressure(), 1) dewpoint = round( 243.04 * (log(humidity / 100) + ((17.625 * celcius) / (243.04 + celcius))) / (17.625 - log(humidity / 100) - (17.625 * celcius) / (243.04 + celcius)), 1) # Get orientation data acceleration = sense.get_accelerometer_raw() x = round(acceleration['x'], 2) y = round(acceleration['y'], 2) z = round(acceleration['z'], 2) # Set screen color based on temperature if fahrenheit > 20 and fahrenheit < 80: bg_color = [0, 0, 155] # blue elif fahrenheit > 81 and fahrenheit < 90: bg_color = [0, 155, 0] # Green elif fahrenheit > 91 and fahrenheit < 100: bg_color = [155, 155, 0] # Yellow elif fahrenheit > 101 and fahrenheit < 102: bg_color = [255, 127, 0] # Orange elif fahrenheit > 103 and fahrenheit < 104: bg_color = [155, 0, 0] # Red elif fahrenheit > 105 and fahrenheit < 109: bg_color = [255, 0, 0] # Bright Red elif fahrenheit > 110 and fahrenheit < 120: bg_color = [155, 155, 155] # White else: bg_color = [0, 155, 0] # Green result = ' Temp. F ' + str(fahrenheit) + ' Temp. C ' + str( celcius) + ' Hum. ' + str(humidity) + ' Press. ' + str( pressure) + ' DewPoint ' + str(dewpoint) print(result) result_list = [(datetime.datetime.now(), celcius, fahrenheit, humidity, pressure, dewpoint, x, y, z)] # Log input with open('weather_logs.csv', 'a', newline='') as csv_file: writer = csv.writer(csv_file) writer.writerows(result_list) # Print the data logged 5 times for x in range(5): # set orientation acceleration = sense.get_accelerometer_raw() x = round(acceleration['x'], 0) y = round(acceleration['y'], 0) if x == -1: sense.set_rotation(90) elif y == 1: sense.set_rotation(0) elif y == -1: sense.set_rotation(180) else: sense.set_rotation(180) # print result variable to the PiHAT screen sense.show_message(result, scroll_speed=0.10, back_colour=bg_color, text_colour=[155, 155, 155])
from sense_hat import SenseHat import time s = SenseHat() s.low_light = True s.set_rotation(180) r = (255, 0, 0) g = (0, 255, 0) b = (0, 0, 255) k = (255, 255, 255) w = (255, 255, 255) c = (0, 255, 255) y = (255, 255, 0) o = (255, 128, 0) n = (255, 128, 128) p = (128, 0, 128) d = (255, 0, 128) l = (128, 255, 128) def fish00(): img = [ b, b, b, b, b, b, b, b, b, b, b, b, b, b, b, b, b, b, b, b, b, b, b, k, b, b, b, b, b, b, b, k, b, b, b, b, b, b, b, k, b, b, b, b, b, b, b, b, b, b, b, b, b, b, b, b, b, b, b, b, b, b, b, b ] return img
#!/usr/bin/python from sense_hat import SenseHat import sys import os rotate_degree = 180 sense = SenseHat() sense.set_rotation(rotate_degree) red = (255, 0, 0) blue = (0, 0, 255) yellow = (255,255,0) cadetblue = (95,158,160) if len(sys.argv) == 1: sense.show_message("Hello Melody!", text_colour=red) quit() for i in sys.argv[1:]: sense.show_message(i, text_colour=blue)
#!/usr/bin/env python from sense_hat import SenseHat import time, datetime hat = SenseHat() hat.set_rotation(180) year_color = (0, 255, 0) month_color = (0, 0, 255) day_color = (255, 0, 0) hour_color = (0, 255, 0) minute_color = (0, 0, 255) second_color = (255, 0, 0) hundrefths_color = (127, 127, 0) off = (0, 0, 0) hat.clear() def display_binary(value, row, color): binary_str = "{0:8b}".format(value) for x in range(0, 8): if binary_str[x] == '1': hat.set_pixel(x, row, color) else: hat.set_pixel(x, row, off) try: while True: t = datetime.datetime.now() display_binary(t.year % 100, 0, year_color) display_binary(t.month, 1, month_color)
def hello_world(): GPIO.setmode(GPIO.BOARD) GPIO.setup(7, GPIO.IN) B = [0,0,0] #negre X = [100,100,100] #blanc gris V = [255,150,0] #tronja K = [0, 150, 150] cares = [ [B,B,B,B,B,B,B,B, X,X,X,B,B,X,X,X, X,B,X,B,B,X,B,X, B,B,B,B,B,B,B,B, B,V,V,V,V,V,V,B, B,B,V,V,V,V,B,B, B,B,B,V,V,B,B,B, B,B,B,B,B,B,B,B] , [B,B,B,B,B,B,B,B, X,X,B,B,B,B,X,X, B,B,X,B,B,X,B,B, B,B,B,B,B,B,B,B, B,V,V,V,V,V,V,B, B,B,V,V,V,V,B,B, B,B,B,V,V,B,B,B, B,B,B,B,B,B,B,B] , [B,B,B,B,B,B,B,B, B,B,B,B,B,B,B,B, X,X,X,B,B,X,X,X, B,B,B,B,B,B,B,B, B,V,V,V,V,V,V,B, B,B,V,V,V,V,B,B, B,B,B,V,V,B,B,B, B,B,B,B,B,B,B,B] , [B,B,B,B,B,B,B,B, B,B,X,B,B,X,B,B, X,X,B,B,B,B,X,X, B,B,B,B,B,B,B,B, B,V,V,V,V,V,V,B, B,B,V,V,V,V,B,B, B,B,B,V,V,B,B,B, B,B,B,B,B,B,B,B] , [B,B,B,B,B,B,B,B, X,B,X,B,B,X,B,X, X,X,X,B,B,X,X,X, B,B,B,B,B,B,B,B, B,V,V,V,V,V,V,B, B,B,V,V,V,V,B,B, B,B,B,V,V,B,B,B, B,B,B,B,B,B,B,B] , [B,B,B,B,B,B,B,B, X,X,X,B,B,X,X,X, X,K,X,B,B,X,K,X, B,B,B,B,B,B,B,B, B,V,V,V,V,V,V,B, B,B,V,V,V,V,B,B, B,B,B,V,V,B,B,B, B,B,B,B,B,B,B,B] ] caraActual = 2 sense = SenseHat() sense.set_rotation(270) start = time.time() elapsedTime = 0 elapsedTime_sett = 0 # Initialize config with open('../config.json', 'r') as content_file: content = content_file.read() config = json.loads(content) sense.set_pixels(cares[caraActual]) conn = sqlite3.connect('database.db') cursor = conn.cursor() deltat = 604800 while True: if elapsedTime > 3 and elapsedTime < 5: sense.set_pixels(cares[5]) else: sense.set_pixels(cares[caraActual]) if elapsedTime_sett > 5: with open('../config.json', 'r') as content_file: content = content_file.read() config = json.loads(content) elapsedTime_sett = 0 if elapsedTime > 1 and GPIO.input(7) == 1: print(elapsedTime) elapsedTime = 0 if config['action'] == "negative": caraActual += 1 else: caraActual -= 1 cursor.execute("INSERT INTO entries (date, amount, delayed_until, reason) VALUES (?,?,?,?)", [int(time.time()), config['quantity'], int(time.time() + deltat), config['reason']]) conn.commit() end = time.time() dif = end - start elapsedTime += dif elapsedTime_sett += dif start = time.time() if elapsedTime > 20: if config['action'] == "negative": caraActual -= 1 else: caraActual += 1 elapsedTime = 0 if caraActual > 4: caraActual = 4 if caraActual < 0: caraActual = 0
start_time = 0.0 sense.show_message("Hi Tim! Let's play some tunes!") while True: pygame.mixer.music.load(music_files[current_track]) pygame.mixer.music.set_volume(volume) pygame.mixer.music.play() start_time = 0.0 sense.set_pixels(image) while pygame.mixer.music.get_busy(): for event in pygame.event.get(): if event.type == pygame.KEYDOWN: if event.key == pygame.K_u: if paused == False: pygame.mixer.music.pause() sense.set_rotation(0) sense.set_pixels(pause_image) else: pygame.mixer.music.unpause() sense.set_rotation(0) sense.set_pixels(play_image) time.sleep(2) sense.set_pixels(image) paused = not paused if event.key == pygame.K_r: current_track = current_track + 1 if current_track >= n_tracks: current_track = 0 sense.set_rotation(0) sense.set_pixels(next_image) pygame.mixer.music.stop()
# cursor navigation if event.key == K_DOWN and y < 7: new_y = y + 1 elif event.key == K_UP and y > 0: new_y = y - 1 elif event.key == K_RIGHT and x < 6: new_x = x + 2 new_x1 = x1 +2 elif event.key == K_LEFT and x > 0: new_x = x - 2 new_x1 = x1 -2 elif event.key == K_RETURN: print('press') # display a png or animation if pos in pngs: sh.set_rotation(90) sh.load_image("pngs/dec"+str(int(pos))+".png") time.sleep(5) sh.set_rotation(0) sh.set_pixels(cal) elif pos in anis: # days with animations if int(pos) == 5: ani.play5() elif int(pos) == 10: ani.play10() elif int(pos) == 15: ani.play15() elif int(pos) == 1: ani.play1() elif int(pos) == 20: ani.play20()
orient_message("Shake Me") while shake_check() == False: time.sleep(0.1) play = True score = 0 lives = 3 pause = 2.5 while play == True: last_arrow = arrow while arrow == last_arrow: arrow = random.choice([0,90,180,270]) sense.set_rotation(arrow) num = random.random() print("humidity = " +str(sense.get_humidity())) if num < 0.1: plot_image(shake_img,w,bl) time.sleep(pause) if shake_check(): plot_image(shake_img,g,bl) score = score + 1 else: plot_image(shake_img,r,bl) lives = lives -1 elif num > 0.9 and sense.get_humidity()<60: hum = sense.get_humidity() print(hum)
def message(): sense = SenseHat() sense.set_rotation(180) color = tuple(map(ord, request.form['color'].decode('hex'))) sense.show_message(request.form['message'], text_colour=color) return redirect(url_for('root'))
# Setup Pygame (for display) pygame.init() screen = pygame.display.set_mode([800, 480]) # Setup the Pi Camera camera = PiCamera() camera.resolution = (800, 480) camera.hflip = True # Setup the SenseHAT sense = SenseHat() sense.set_rotation(0) # Function to display an image def displayImage(file): image = pygame.image.load(file) imagerect = image.get_rect() screen.fill([0, 0, 0]) screen.blit(image, imagerect) pygame.display.flip() # Function to take a selfie
# sens_samples.py # # sudo apt-get install sense-hat # https://trinket.io/sense-hat from sense_hat import SenseHat import sens_defn import time # definitions sensehat = SenseHat( ) #### header msg = "JESUS!" sensehat.low_light = True sensehat.set_rotation( 180 ) sensehat.show_message ( msg , text_colour = sens_defn.G ) sensehat.show_letter( "M" , sens_defn.R ) time.sleep( 1 ) sensehat.show_letter( "G" , sens_defn.G ) time.sleep( 1 ) #### pix varIMGs = [ sens_defn.MLG , sens_defn.SPRG , sens_defn.SMMR , sens_defn.ATMN , sens_defn.WNTR , sens_defn.FLAG , sens_defn.TREE ] ictr = 0 while ictr < len( varIMGs ): sensehat.set_pixels( varIMGs[ ictr % len( varIMGs ) ]( ) ) time.sleep( 1 ) ictr += 1
#!/usr/bin/python import sys import time import datetime import clock_digits from sense_hat import SenseHat sense = SenseHat() # create sense object sense.set_rotation(180) # better when USB cable sticks out the top sense.low_light = True # don't hurt my eyes sense.clear() # always start with a clean slate charWidth = 4 charHeight = 4 # returns the specified row of the digit def digitrow(digit, row): return digit[row * charWidth : (row * charWidth) + charWidth] # main display routine # takes a list of 4 digits and displays them on the LED-matrix def display(digits): if len(digits) > 4: return x = [0, 0, 0] # off screen = [ x, x, x, x, x, x, x, x, x, x, x, x, x, x, x, x, x, x, x, x, x, x, x, x,
pause = 3 score = 0 angle = 0 play = True sense.show_message("Trouvez comment jouer.", scroll_speed=0.05, text_colour=[0, 255, 0]) # WHILE play == True while play: # CHOOSE a new random angle last_angle = angle while angle == last_angle: angle = choice([0, 90, 180, 270]) sense.set_rotation(angle) # DISPLAY the white arrow sense.set_pixels(arrow) # SLEEP for current pause length sleep(pause) acceleration = sense.get_accelerometer_raw() x = acceleration['x'] y = acceleration['y'] z = acceleration['z'] x = round(x, 0) y = round(y, 0)
from sense_hat import SenseHat import time hat = SenseHat() red = (255, 0, 0) hat.load_image('small_image.png') time.sleep(1) hat.set_rotation(90) time.sleep(1) hat.set_rotation(180) time.sleep(1) hat.set_rotation(270) time.sleep(1) hat.clear() hat.set_rotation(0) for xy in range(0, 8): hat.set_pixel(xy, xy, red) hat.set_pixel(xy, 7-xy, red)
from sense_hat import SenseHat sense = SenseHat() sense.set_rotation(270) while True: #temp = sense.temperature temp = round(sense.temperature, 1) sense.show_message(str(temp)) #sense.show_message("It is " + str(temp) + " degrees" )
e,e,e,w,w,e,e,e ] # Print it once sh.set_pixels(arrow) while True: x_full, y_full, z_full = sh.get_accelerometer_raw().values() x=round(x_full, 0) y=round(y_full, 0) z=round(z_full, 0) print ("x=%s, y=%s, z=%s" % (x_full,y_full,z_full)) if x == -1: # works sh.set_pixels(arrow) sh.set_rotation(180) elif x == 1: # works sh.set_pixels(arrow) sh.set_rotation(0) elif y == 1: sh.set_pixels(arrow) sh.set_rotation(270) elif y == -1: sh.set_pixels(arrow) sh.set_rotation(90) else: sh.show_letter("*")
import sys from sense_hat import SenseHat sense = SenseHat() if len(sys.argv) > 1: sense.set_rotation(int(sys.argv[1])) else: print(sense.rotation)
humidity = sense.get_humidity() humidity = round(humidity, 1) print "The relative humidity at the Sense Hat is", humidity, "%" sense.clear() pressure = sense.get_pressure() pressure = round(pressure, 1) print "The atmospheric pressure at the Sense Hat is", pressure, "mbar" # outputing the temp, humidity, and pressure to the matrix sense.clear() sense.set_rotation(0) # sets orientation of Sense Hat matrix # setting colors for the scrolling text on the matrix red = (255, 0, 0) green = (0, 255, 0) blue = (0, 0, 255) speed = (0.06) # speed of text scroll (0.10 is default) sleep = (0.6) # time of break in seconds sense.show_message("Temp:", text_colour=red, scroll_speed=speed) sense.show_message(str(tempC), text_colour=red, scroll_speed=speed) sense.show_message("C", text_colour=red, scroll_speed=speed) sense.show_message("or", text_colour=red, scroll_speed=speed) sense.show_message(str(tempF), text_colour=red, scroll_speed=speed) sense.show_message("F", text_colour=red, scroll_speed=speed)
for item in grid for value in item ] sample_pixels = [ range(value, value + icon_size, pixel_width) for item in image_rows for value in item ] characters = [image_pixels[value] for item in sample_pixels for value in item] # Break list into chunks def chunks(list_data, chunk_size): return [ list_data[item:item + chunk_size] for item in range(0, len(list_data), chunk_size) ] chunk_list = chunks(characters, 64) # select chunk size # Display characters using LED matrix display on Sense HAT sense = SenseHat() sense.set_rotation(r=180) for chunk in chunk_list: sense.set_pixels(chunk) time.sleep(1) sense.clear()
#!/usr/bin/python import sys # arg1 is the script name # arg2 is what we want if len(sys.argv) != 2: raise ValueError('Argument missing or too many'); from sense_hat import SenseHat sense = SenseHat() sense.set_rotation(int(sys.argv[1]))
last_rotation = 180 SenseHat.set_rotation(180) elif y == 1: if last_rotation != 0: last_rotation = 0 SenseHat.set_rotation(0) else: if last_rotation != default: last_rotation = default SenseHat.set_rotation(default) sleep(0.5) SenseHat = SenseHat() SenseHat.set_rotation(rotation) #=============================================================================== # Run updateDisplayRotation() in the background #=============================================================================== BackgroundThread = threading.Thread(target=updateDisplayRotation, args=(SenseHat, rotation)) BackgroundThread.daemon = True BackgroundThread.start() #=============================================================================== # Change the smileys face after a random period of time #=============================================================================== while True: SenseHat.set_pixels(image_a) sleep(choice([2, 4, 6, 8]))
shake = 0 pause = 3 score = 0 angle = 0 play = True sense.show_message("Keep the arrow pointing up", scroll_speed=0.05, text_colour=[100,100,100]) while play: last_angle = angle while angle == last_angle: angle = random.choice([0, 90, 180, 270]) shake = random.choice([1,2,3,4,5,6,7,8,9,10]) if shake >7 sense.set_pixels(shake_symbole) sense.set_rotation(angle) sense.set_pixels(arrow) time.sleep(pause) x, y, z = sense.get_accelerometer_raw().values() x = round(x, 0) y = round(y, 0) print(angle) print(x) print(y) if x == -1 and angle == 180: sense.set_pixels(arrow_green) score += 1 elif x == 1 and angle == 0:
import sys sys.path.append("/home/pi/Desktop/NAVI/WANDER_LUST") import random from random import randint import time from sense_hat import SenseHat sense = SenseHat() sense.set_rotation(90) sense.clear() blue = (0, 0, 255) yellow = (255, 255, 0) red = (255, 0, 0) white = (255, 255, 255) black = (0, 0, 0) green = (0, 255, 0) def fortune(): sense.show_message("Ask a question", scroll_speed=0.06) time.sleep(3) replies = [ 'Signs point to yes', 'Without a doubt', 'You may rely on it', 'Do not count on it', 'Looking good', 'Cannot predict now', 'It is decidedly so', 'Outlook not so good' ] while True:
#!/usr/bin/python # Import modules from sense_hat import SenseHat import random # Instantiate SenseHat sense = SenseHat() sense.set_rotation(270) # Define colour palette r = [255, 0, 0] o = [255, 127, 0] y = [255, 255, 0] g = [0, 255, 0] b = [0, 0, 255] i = [75, 0, 130] v = [159, 0, 255] e = [0, 0, 0] # e stands for empty/black # Main loop while True: # Initialise random colors r = random.randint(0,255) g = random.randint(0,255) b = random.randint(0,255) # Display welcome message sense.show_message("Hello World!", scroll_speed=0.05, text_colour=[r,g,b],back_colour=[0,0,0])
from sense_hat import SenseHat import time import datetime sense = SenseHat() sense.set_rotation(180) inky = [] for nbr in range(1, 15): inky.append( sense.load_image("sprites/inky" + str(nbr) + ".png", redraw=False)) def Move(sprites, direction): if direction: animation = sprites else: animation = reversed(sprites) for sprite in animation: sense.set_pixels(sprite) time.sleep(0.1) # delays for 100 miliseconds Move(inky, 1) sense.clear() # no arguments defaults to off time.sleep(1) Move(inky, 0) sense.clear() # no arguments defaults to off time.sleep(1)
r, b, r, g, r, r, g, g, r, r, g, g, r, ] sense.set_pixels(image) sense.set_rotation(90) time.sleep(1) sense.show_letter("Z") angles = [0, 90, 180, 270, 0, 90, 180, 270] for r in angles: sense.set_rotation(r) time.sleep(1) r = [255, 0, 0] g = [0, 255, 0] b = [0, 0, 255] image = [ r, g,
from time import sleep from picamera import PiCamera import numpy as np import cv2 from tensorflow import keras from sense_hat import SenseHat # Set up Camera cam = PiCamera() cam.resolution = (100, 100) # Set up LED panel s = SenseHat() s.clear() s.set_pixel(0, 0, (0, 0, 255)) s.set_rotation(r=90) #0 (hdmi side), 90, 180, 270 red = (255, 0, 0) # Load model model = keras.models.load_model(r"/home/pi/CPE4903/digit_recog.h5") output = np.empty((112*128*3,), dtype=np.uint8) for i in range(4): # Start camera cam.start_preview() sleep(1) # Save picture to array cam.capture(output, 'rgb') img = output.reshape((112, 128, 3))
#!/usr/bin/python import sys from sense_hat import SenseHat # To get good results with the magnetometer you must first calibrate it using # the program in RTIMULib/Linux/RTIMULibCal # The calibration program will produce the file RTIMULib.ini # Copy it into the same folder as your Python code led_loop = [4, 5, 6, 7, 15, 23, 31, 39, 47, 55, 63, 62, 61, 60, 59, 58, 57, 56, 48, 40, 32, 24, 16, 8, 0, 1, 2, 3] sense = SenseHat() sense.set_rotation(0) sense.clear() prev_x = 0 prev_y = 0 led_degree_ratio = len(led_loop) / 360.0 while True: dir = sense.get_compass() dir_inverted = 360 - dir # So LED appears to follow North led_index = int(led_degree_ratio * dir_inverted) offset = led_loop[led_index] y = offset // 8 # row x = offset % 8 # column if x != prev_x or y != prev_y: sense.set_pixel(prev_x, prev_y, 0, 0, 0)
fileName= '/home/pi/weatherPi/weather_data/'+str(cTime[0])+'_weatherData.csv' if os.path.exists(fileName): with open(fileName,'a',newline='') as f: writ = csv.writer(f) writ.writerow([cDatetime,cTemp,cPres,cHumi,cConditions]) else: with open(fileName,'w',newline='') as f: writ = csv.writer(f) writ.writerow(['Datetime','Temperature','Pressure','Humidity','Conditions']) writ.writerow([cDatetime,cTemp,cPres,cHumi,cConditions]) #------------------------------------------------------------- #Display on Matrix-------------------------------------------- sense.set_rotation(90,redraw=False) #If it is the first of the month, reset all pixels if cTime[2]==1 and cTime[3]==0 and cTime[4]==0: #first minute of new month sense.clear() #rotating the matrix properly sense.low_light = False #12:00 pm - display temperature if (cTime[3]==12 and cTime[4]==0): rgbVal = [0,0,0] if cTemp <=BLUE_TEMP: rgbVal = [int(255*BRIGHTNESS),int(255*BRIGHTNESS),int(255*BRIGHTNESS)] elif cTemp>=RED_TEMP:
from sense_hat import SenseHat sense = SenseHat() r = [255, 0, 0] o = [255, 127, 0] y = [255, 255, 0] g = [0, 255, 0] b = [0, 0, 255] i = [75, 0, 130] v = [159, 0, 255] e = [0, 0, 0] image = [ e,e,e,e,e,e,e,e, e,e,e,r,r,e,e,e, e,r,r,o,o,r,r,e, r,o,o,y,y,o,o,r, o,y,y,g,g,y,y,o, y,g,g,b,b,g,g,y, b,b,b,i,i,b,b,b, b,i,i,v,v,i,i,b ] sense.set_pixels(image) sense.set_rotation(180)
# Get microphone data data = stream.read(chunk) matrix = calculate_levels(data, chunk, sample_rate) figure = empty[:] for y in range(0, 8): if matrix[y] <= 8: for x in range(0, matrix[y]): figure[y * 8 + x] = green elif matrix[y] <= 16: for x in range(4 - (matrix[y] - 8) / 2, 4 + (matrix[y] - 8) / 2): figure[y * 8 + (x - 8)] = blue else: for x in range(matrix[y], 24): figure[y * 8 + (x - 16)] = red time.sleep(chunk / sample_rate) # is this needed? sense.set_rotation(rotation) sense.set_pixels(figure) except KeyboardInterrupt: print("Ctrl-C Terminating...") stream.stop_stream() stream.close() p.terminate() sys.exit(1) except Exception, e: print(e) print("ERROR Terminating...") stream.stop_stream() stream.close() p.terminate() sys.exit(1)