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 gyroGame(maxDegs): sense = SenseHat() while 1: orientation = sense.get_orientation_degrees() if orientation['pitch'] < maxDegs: realpitch=orientation['pitch'] else: realpitch=-1*(360-orientation['pitch']) if orientation['roll'] < maxDegs: realroll=orientation['roll'] else: realroll=-1*(360-orientation['roll']) x_pos=7-int(round(((maxDegs+realpitch)/(2.0*maxDegs))*8.0,0)) y_pos=int(round(((maxDegs+realroll)/(2.0*maxDegs))*8.0,0)) if x_pos > 7: x_pos = 7 if x_pos < 0: x_pos = 0 if y_pos > 7: y_pos = 7 if y_pos < 0: y_pos = 0 sense.clear() if (1 <= x_pos <=6) and (1 <= y_pos <=6): sense.set_pixel(x_pos,y_pos,0,0,255) else: sense.set_pixel(x_pos,y_pos,255,0,0)
def tv(): sense = SenseHat() sense.clear() pygame.init() pygame.display.set_mode((640, 480)) state = "Off" done=True while done: for event in pygame.event.get(): if event.type == KEYDOWN: if event.key == K_RETURN and state == "On": sense.clear() state = "Off" done=False elif event.key == K_RETURN and state == "Off": sense.set_pixels(channel4) state = "On" elif event.key == K_DOWN: sense.set_pixels(volumedown) elif event.key == K_UP: sense.set_pixels(volumeup) elif event.key == K_LEFT: sense.set_pixels(bw) elif event.key == K_RIGHT: sense.set_pixels(fw) pygame.quit()
def music(): root = tkinter.Tk() root.geometry("150x150") root.wm_title("Music") b1 = ttk.Button(root, text = 'V+', command = vdown) b2 = ttk.Button(root, text = 'V-', command = vup) b3 = ttk.Button(root, text = 'Next', command = nextm) b4 = ttk.Button(root, text = 'Previous', command = previousm) b5 = ttk.Button(root, text = 'On/Off', command = moff) b1.pack() b2.pack() b3.pack() b4.pack() b5.pack() sense = SenseHat() sense.clear() pygame.init() pygame.display.set_mode((15, 15)) mixer.init() #music global path path = "/home/pi/Desktop/Smart House/Music" global mfiles mfiles = [f for f in os.listdir(path) if f.endswith('.mp3')] global abc abc = 2 global state state = "Off"
def interp(doc): ''' boilermake devices.setup() devices.set_in('Button',devices.Button(16, GPIO.PUD_DOWN)) devices.set_in('TempSensor',devices.TemperatureHumiditySensor(7)) devices.set_out('Servo', devices.Servo(12)) devices.set_out('RgbLed', devices.RgbLed(11, 13, 15, 100)) devices.set_out('BlueLed', devices.Led(19,120)) devices.set_out('GreenLed', devices.Led(18,120)) devices.set_out('RedLed', devices.Led(22, 120)) ''' try: global page_decls page_decls = {} global sense sense = SenseHat() if 'Pages' not in doc: raise Exception("Malformed doc {}".format(json.dumps(doc))) for page_doc in doc['Pages']: page_decl = translate_page_decl(page_doc) page_decls[page_decl.name] = page_decl if 'Main' not in page_decls: raise Exception('Malformed doc - no main {}'.format(json.dumps(doc))) page_decls['Main'].interp() sense.clear() #devices.cleanup() except Exception as e: if sense: sense.clear() #devices.cleanup() raise e
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 SH_show_colour(): # Thread to update colour on LED matrix sh = SenseHat() global running while running: red_val =red_var.get() green_val =green_var.get() blue_val =blue_var.get() time.sleep(0.05) sh.clear(red_val,green_val,blue_val) sh.clear([0,0,0])
class _SenseHat: def __init__(self, board_object, colour=""): self.board = board_object self.colour = colour self.sense = SenseHat() def magnetometer_on(self): self.sense.set_imu_config(True, False, False) # gyroscope only @property def temp_c(self): return (self.sense.get_temperature_from_humidity() + self.sense.get_temperature_from_pressure())/2 @property def pressure(self): return self.sense.pressure @property def humidity(self): return self.sense.humidity def led_all(self, colour): lcd = [] for i in range(0, 64): lcd.append(colour) self.sense.set_pixels(lcd) def led_1(self, colour): self.sense.set_pixel(0, 0, colour) self.sense.set_pixel(0, 1, colour) self.sense.set_pixel(1, 0, colour) self.sense.set_pixel(1, 1, colour) def led_2(self, colour): self.sense.set_pixel(2, 2, colour) self.sense.set_pixel(2, 3, colour) self.sense.set_pixel(3, 2, colour) self.sense.set_pixel(3, 3, colour) def led_3(self, colour): self.sense.set_pixel(4, 4, colour) self.sense.set_pixel(4, 5, colour) self.sense.set_pixel(5, 4, colour) self.sense.set_pixel(5, 5, colour) def led_4(self, colour): self.sense.set_pixel(6, 6, colour) self.sense.set_pixel(6, 7, colour) self.sense.set_pixel(7, 6, colour) self.sense.set_pixel(7, 7, colour) def clear(self): self.sense.clear()
def monitor_pass(pass_details): sense = SenseHat() sense.clear() p = pass_details t0 = p.StartTime t1 = p.HighTime t2 = p.EndTime pixels = [C.K] * 64 nx, ny = 0, 0 while True: time.sleep(0.1) t = datetime.utcnow() if t >= t0: break pixels[8 * ny + nx] = C.K nx, ny = border(Azimuth.from_string('N')) pixels[8 * ny + nx] = C.B sense.set_pixels(pixels) while True: time.sleep(0.1) t = datetime.utcnow() if t > t2: break if t < t1: x = (t - t0).total_seconds() / (t1 - t0).total_seconds() a = x * p.HighAzimuth + (1 - x) * p.StartAzimuth if a > 180: a = a - 360 else: x = (t2 - t).total_seconds() / (t2 - t1).total_seconds() a = x * p.HighAzimuth + (1 - x) * p.EndAzimuth if a > 180: a = a - 360 #print('{0:0.3f} {1:0.3f}'.format(x, distinv(x))) #pixels = spot(x, distinv) #pixels = spiral(x, ramp) pixels = spot(x, Tween.distinv) nx, ny = border(Azimuth.from_string('N')) pixels[8 * ny + nx] = C.B px, py = border(a) pixels[8 * py + px] = C.R sense.set_pixels(pixels) sense.clear()
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 music(): sense = SenseHat() sense.clear() pygame.init() pygame.display.set_mode((640, 480)) mixer.init() #music path = "/home/pi/Desktop/Smart House/Music" mfiles = [f for f in os.listdir(path) if f.endswith('.mp3')] abc = 2 state = "Off" running = True while running: for event in pygame.event.get(): if event.type == KEYDOWN: if event.key == K_RETURN and state == "On": sense.clear() state = "Off" mixer.music.stop() running = False elif event.key == K_RETURN and state == "Off": sense.set_pixels(song2) state = "On" mixer.music.load(path + '/' + mfiles[abc]) mixer.music.play() elif event.key == K_DOWN: sense.set_pixels(volumedown) elif event.key == K_UP: sense.set_pixels(volumeup) elif event.key == K_LEFT: sense.set_pixels(song2) if abc>0: abc = abc-1 else: abc= len(mfiles)-1 mixer.music.load(path + '/' + mfiles[abc]) mixer.music.play() elif event.key == K_RIGHT: sense.set_pixels(song2) if abc<(len(mfiles)-1): abc = abc+1 else: abc = 0 mixer.music.load(path + '/' + mfiles[abc]) mixer.music.play() pygame.quit()
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 main(): sense = SenseHat() color = (255, 0, 0) prev_x = -1 prev_y = -1 while True: acc = sense.get_accelerometer_raw() x = round(limit(-10 * acc['x'] + 3)) y = round(limit(-10 * acc['y'] + 3)) if x != prev_x or y != prev_y: sense.clear() sense.set_pixel(x, y, *color) prev_x = x prev_y = y time.sleep(0.08)
def main(): sense = SenseHat() sense.low_light = True print( "<---- ImageDisplay ---->\n" ) if len( sys.argv ) != 2: print( "There must be exactly one argument, the path of the to be displayed image" ) return 0 else: print( "Displaying \'{0}\'".format( sys.argv[ 1 ] ) ) onOffMatrix = senseSuppLib.LoadPixelStatusFromBIDF( sys.argv[ 1 ] ) senseSuppLib.UpdateScreen( [ 255, 255, 255 ], onOffMatrix, sense ) time.sleep( 3 ) sense.clear() return 0
def main(): sense = SenseHat() sense.low_light = True print( "<---- SinusGraph ---->\n" ) pixelStatuses = [ [ 0, 0, 0 ] for i in range( 64 ) ] for i in range( 150 ): assert len( pixelStatuses ) == 64 del pixelStatuses[ : 8 ] pixelStatuses.extend( [ [ 0, 0, 0 ] for i in range( 8 ) ] ) pixelStatuses[ 60 + round( cos( i / 1.5 ) * 3 ) ] = [ 0, 255, 0 ] pixelStatuses[ 60 + round( sin( i / 2 ) * 3 ) ] = [ 255, 255, 255 ] sense.set_pixels( pixelStatuses ) pixelStatuses = sense.get_pixels() print( pixelStatuses ) sleep( 0.096 ) sense.clear()
def search_device(user_name, device_name, max_address_file): print("Searching for your device ({})".format(device_name)) sense = SenseHat() sense.clear() device_address=None nearby_devices = bluetooth.discover_devices() for mac_address in nearby_devices: if device_name == bluetooth.lookup_name(mac_address): device_address = mac_address break if device_address is not None: MAC_ADDRESS_FILE.write("{}, {}\r\n".format(user_name, mac_address)) print("{}, your device '{}' has been registered!".format(user_name, device_name)) elif device_address is None: print("Could not find {}". format(device_name))
def main(): sense = SenseHat() """ sense.show_message("Hello World!!"); sense.set_rotation(180) sense.show_message("Hello World!!"); """ sense.flip_v() list = sense.get_pixels() #print list sense.set_pixel(0,0,255,0,0) sense.clear() for i in range(0, 5): sense.show_letter(str(i)) time.sleep(1) sense.clear()
def senseDisplayService(): print 'Starting SenseHat Display Service' # create an object with display functions show = { 'server': senseDisplayServer, 'temperature': senseDisplayTemperature, 'humidity': senseDisplayHumidity, 'pressure': senseDisplayPressure } # Initialise the sense hat sense = SenseHat() sense.clear(0,0,0) # display a message according to the currentDisplayMode on a loop while True: show[currentDisplayMode.value](sense)
def main(): global sense global serverip sense = SenseHat() sense.clear() s_stick = SenseStick() # start two threads that actually update the display and listen to the joystick thread.start_new_thread(keepUpdatingDisplay, ("keepUpdatingDisplayThread", sense)) #thread.start_new_thread(keepSensingJoyStick, ("keepSensingJoyStickThread", s_stick)) if( len(sys.argv) == 1 ): # listen for server ip inbound on port 4000 print("start looking up serverip \n") # assumes that avahi-publish has been started already s = socket.socket() # Create a socket object host = "127.0.0.1" # Get local machine name port = 4000 # Reserve a port for your service. s.bind((host, port)) s.listen(5) b = True while( b ): (c,addr) = s.accept() data = c.recv(1024) if data != None: serverip = str( data ) # contains server ip b = False c.close() s.close() else: serverip = sys.argv[1] print("serverip=" + sys.argv[1]) f = open(config.HOME_DIR + "serverip.txt", 'w') f.write(serverip) f.close() keepSensingJoyStick("keepSensingJoyStickThread", s_stick) # might as well run this in the main thread
def tv(): root = tkinter.Tk() root.geometry("150x150") root.wm_title("Tv") b1 = ttk.Button(root, text = 'V+', command = vdown) b2 = ttk.Button(root, text = 'V-', command = vup) b3 = ttk.Button(root, text = 'P+', command = nexttv) b4 = ttk.Button(root, text = 'P-', command = prevtv) b5 = ttk.Button(root, text = 'On/Off', command = tvoff) b1.pack() b2.pack() b3.pack() b4.pack() b5.pack() sense = SenseHat() sense.clear() pygame.init() pygame.display.set_mode((15,15)) global state2 state2 = "Off"
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()
class Controller(object): def __init__(self): self.sense = SenseHat() self.sense.clear() self.found = False self.dev = None self.running = False devices = [InputDevice(fn) for fn in list_devices()] for dev in devices: if dev.name == 'Raspberry Pi Sense HAT Joystick': self.dev = dev self.found = True self.running = True break def on_button_pressed(self, event): raise NotImplementedError("Please Implement Button Pressed Method") def on_button_released(self, event): raise NotImplementedError("Please implement BUtton Released Method") def pre_input_event(self): pass def run(self): while self.running: self.pre_input_event() event = self.dev.read_one() if event: if event.value == 1: self.on_button_pressed(event) if event.value == 0: self.on_button_released(event) def reset(self): raise NotImplementedError("Please implement reset method")
def get_current_data(): if(enable_sense_hat): sense = SenseHat() sense.clear() t = sense.get_temperature() p = sense.get_pressure() h = sense.get_humidity() tp = sense.get_temperature_from_pressure() data = { 'temperature':str(round(t, 1)), 'pressure':str(round(p,1)), 'humidity':str(round(h,1)), 'temperatureP':str(round(tp,1)), 'datetime' : datetime.now() } else: data = { 'temperature': 0, 'pressure':0, 'humidity':0, 'temperatureP':0, 'datetime' : datetime.now() } return data
def main(): menu = Menu(SenseHat(), SenseStick()) menu.run() return sense_stick = SenseStick() sense_hat = SenseHat() sense_hat.clear() while True: event = sense_stick.read() if event.state == SenseStick.STATE_PRESS: message = '' if event.key == SenseStick.KEY_UP: message = 'poo' elif event.key == SenseStick.KEY_LEFT: message = 'bum' elif event.key == SenseStick.KEY_RIGHT: message = 'dick' elif event.key == SenseStick.KEY_DOWN: message = 'balls' elif event.key == SenseStick.KEY_ENTER: message = 'rofl' red = (255, 0, 0) sense_hat.show_message(message, text_colour=red, scroll_speed=0.05) print 'hello'
if door_state_code == '0': door_state_desc = "Open" else: door_state_desc = "Closed" except: door_state_desc = "Error" pass f = open("/home/pi/proj/weather.txt","r") weather=eval(f.read()) #from the sensehat #temp = round(s.get_temperature()*1.8 +32,1) humidityhome = int(s.get_humidity()) #pressure = round(s.get_pressure(),1) temp = round(weather['temperature'],1) humidity = weather['humidity'] windspeed = round(weather['windspeed'],1) winddirection = weather['winddirection'] maxtemp = int(weather['maxtemperature']) mintemp = int(weather['mintemperature']) message= 'temp out {0}F hum out {1}% / hum in {2}% low {3}F high {4}F wind {5} @ {6} {7}'.format(temp,humidity,humidityhome,mintemp,maxtemp,windspeed,winddirection,door_state_desc) s.show_message(message, scroll_speed=(0.05),text_colour=[0,102,255], back_colour= [0,0,0]) s.set_pixels(heart()) time.sleep(1.0) s.set_pixels(ben()) time.sleep(2.0) s.clear() except: s.clear() pass
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()
y = (170, 176, 0) # yellow g = (0, 255, 0) # green c = (0, 255, 255) # cyan b = (0, 0, 255) # blue p = (255, 0, 255) # purple n = (255, 128, 128) # pink w = (255, 255, 255) # white k = (0, 0, 0) # blank rainbow = [r, o, y, g, c, b, p, n] try: os.chdir('/home/pi/myNAS/env/') except: for cycle in range(10): sense.clear(b) time.sleep(.25) sense.clear(r) time.sleep(.25) sense.show_letter("F", b, r) sys.exit() while True: sense.clear() hour = time.strftime('%H') nap = hour >= '08' and hour < '20' if nap: for i in range(8): colour = rainbow[i] for x in range(8):
class TemperatureMonitor: sense = None def __init__(self): self.sense = SenseHat() def monitor_and_display(self): # colors red = (255, 0, 0) blue = (0, 0, 255) green = (0, 255, 0) # Fetching data from config.json file temp_thresholds = self.get_data_from_json() # Checking if the boundary values in JSON are correct if (not self.verify_temperature_boundary_values(temp_thresholds)): print("--------------- USER WARNING ---------------") print("") print( " The JSON in config.json file have invalid boundary values.") print("") print("--------------------------------------------") exit() try: while (True): temp = self.sense.get_temperature() if (temp < temp_thresholds['cold_max']): color = blue elif (temp >= temp_thresholds['comfortable_min'] and temp <= temp_thresholds['comfortable_max']): color = green else: color = red self.sense.show_message(str(round(temp, 2)), text_colour=color) time.sleep(10) # Clearing sense hat display on keyboard interrupt finally: self.sense.clear() # Returns the JSON object from config.json def get_data_from_json(self): with open('config.json') as json_file: try: data = json.load(json_file) except: print("--------------- USER WARNING ---------------") print("") print(" The JSON in config.json file is invalid.") print("") print("--------------------------------------------") exit() return data # Checks if the boundaries of temperature in json is incorrect def verify_temperature_boundary_values(self, temp_thresholds): if (temp_thresholds['cold_max'] == temp_thresholds['comfortable_min'] and temp_thresholds['comfortable_max'] == temp_thresholds['hot_min'] and temp_thresholds['comfortable_min'] < temp_thresholds['comfortable_max']): return True else: return False
def sse_left(): sense = SenseHat() sense.clear() return Response(arduino_slave.move_left(sense), mimetype='text/event-stream')
from sense_hat import SenseHat sensehat = SenseHat() sensehat.clear() color_list = [(4,104,255),(16,187,251),(28,248,237),(39,245,167),(51,242,107) ,(67,239,62),(131,237,72),(187,235,83)] # generate via colour library marker = (255,0,0) # create the matrix imageLists = [[] for i in range(8)] for i in range(8): imageLists[i] = [(0,0,0) for j in range(8)] # set the background for i in range(8): for j in range(8): imageLists[i][j] = color_list[i] # integrate the matrix image_pixels = [] for (i,j) in [(1,0),(1,1),(2,1),(3,1),(5,1),(4,1),(6,2), (5,3),(4,4),(3,4),(2,4),(1,4),(5,5),(6,6),(5,7),(4,7),(3,7),(2,7),(1,7)]: imageLists[i][j] = marker for i in range(8): image_pixels.extend(imageLists[i]) # image_pixels = [b, b, b, b, b, b, b, b, # w, w, b, b, w, b, b, w, # b, w, b, b, w, b, b, w, # b, w, b, b, w, b, b, w, # b, w, b, b, w, b, b, w, # b, w, b, w, b, w, b, w, # b, b, w, b, b, b, w, b,
b = (0,0,255) w = (255,255,255) cell = [ 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,w,w,b,b,B, B,b,b,w,w,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 ] sense.clear() sense.set_pixels(cell) #Wait until the enter button is pressed on the Sense HAT wait = input("Press<enter> to continue") sense.clear(0,0,255) #Blow now time.sleep(10) sense.clear(255,0,0) #Collect data for the first experiment humidity_start = round(sense.get_humidity(),2) temp_start = round(sense.get_temperature(),2)
### librarys ### from sense_hat import SenseHat from time import sleep ### varibles ### sh = SenseHat() running = True last_value = 0 current_value = 0 hard_stops = 0 hard_accels = 0 ### main program ### while running: sh.clear(0, 255, 0) last_value = current_value current_value = sh.accel_raw['y'] if current_value <= last_value / 2: sh.clear(255, 0, 0) hard_stops = hard_stops + 1 sleep(1)
def __init__(self): sense = SenseHat() sense.clear() self.temp = round(sense.get_temperature(), 1) self.temp_humid = round(sense.get_humidity(), 1)
class Morse(object): # Read character-to-morse-character definitions from a text file. def __init__(self, infile='morse.txt', rotation=180, wpm=50, flash_letter=True): # Morse Encoding stuff self.dit="." self.dah="-" re_morse=re.compile( "^(\\"+self.dit+"|\\"+self.dah+")+$" ) self.spacer=re.compile( "\s+" ) self.pause=re.compile( "\.|,|\?|!" ) self.single_space=" " self.characters={} print "Reading morse definition file %s:"%(infile) for linecount, line in enumerate(open(infile), start=1): if not(re.match("^#", line) ): fields=line.split() if not(len(fields)==2): print "Error at line %d, does not contain two space-separated values"%(linecount, line) raise character, morse_character=fields[0], fields[1] if not(re.match(re_morse, morse_character) ): print "Error at line %d, I don't understand the morse character :%s"%(linecount, morse_character) raise self.characters[ character ]= morse_character print "Read %d characters definitions."%len(self.characters) allowable_chars="".join( sorted( self.characters.keys() ) ).upper() print "Allowable Characters:%s"%(allowable_chars) self.allowable_chars=re.compile("[^%s%s]"%(self.single_space, allowable_chars ) ) self.current_character="" # sort of cheating, using this to communicate to other methods in the same class.... # Morse Timing stuff self.dit_ms= 1200/wpm self.dah_ms= 3 * self.dit_ms self.inter_element_ms= self.dit_ms self.inter_letter_ms= 3 * self.dit_ms self.inter_word_ms= 7 * self.dit_ms # SenseHat stuff self.blank_pattern=[ [0,0,0] ] *64 self.flash_pattern=[ [255,255,255] ] *64 self.flash_letter=flash_letter # Changes behaviour to flash the actual letter rather than a full-screen flash. self.sense=SenseHat() self.sense.rotation=rotation self.sense.clear() print "Created Morse Object, wpm=%d, rotation=%d, flash_letter=%s"%( wpm, rotation, self.flash_letter ) def blank(self, millis): self.sense.set_pixels( self.blank_pattern ) time.sleep( millis/1000.0 ) def flash(self, on_millis, off_millis): self.sense.set_pixels( self.flash_pattern ) time.sleep( on_millis/1000.0 ) self.blank( off_millis ) def flash_char(self, on_millis, off_millis ): self.sense.show_letter( self.current_character ) time.sleep( on_millis/1000.0 ) self.blank( off_millis ) def do_flash(self, on_millis, off_millis ): if self.flash_letter: self.flash_char(on_millis, off_millis) else: self.flash(on_millis, off_millis) def do_dit(self): self.do_flash( self.dit_ms, self.inter_element_ms ) # The Camptown ladies sing this song... def do_dah(self): self.do_flash( self.dah_ms, self.inter_element_ms ) def do_pause(self): self.blank( self.inter_word_ms ) def blink_char(self, character): dits_and_dahs=self.characters[character] for dit_dah in dits_and_dahs: if dit_dah==self.dit: self.do_dit() elif dit_dah==self.dah: self.do_dah() self.blank(self.inter_letter_ms) def blink_message(self, message, repeat=1): normalized_message=re.sub(self.spacer, self.single_space, re.sub(self.pause, self.single_space, message) ) cleaned_message=re.sub(self.allowable_chars, '', normalized_message.upper() ).strip() for i in range(1,repeat+1): print "Sending Message: %s. (%d of %d)"%(cleaned_message, i, repeat) for self.current_character in cleaned_message: sys.stdout.write( self.current_character ) sys.stdout.flush() if self.current_character==self.single_space: self.do_pause() else: self.blink_char(self.current_character) print "\ndone." self.do_pause()
import signal import sys sense = SenseHat() sense.set_rotation(180) # sense.show_message("IoT Sensor Pack") # sense.show_message(str(datetime.datetime.now())) def signal_handler(signal, frame): print("Shutting down.") sense.clear() sys.exit(0) signal.signal(signal.SIGINT, signal_handler) sense.clear() try: while True: t = sense.get_temperature() p = sense.get_pressure() h = sense.get_humidity() t = round(t, 1) p = round(p, 1) h = round(h, 1) print("T: %d P: %d H: %d" % (t, p, h)) sense.show_message("T: %d P: %d H: %d" % (t, p, h)) time.sleep(5)
#!/usr/bin/python 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])
#!/bin/python2 # -*- coding: utf-8 -*- from sense_hat import SenseHat import time import datetime #add push over library import httplib, urllib from firebase import firebase sense = SenseHat() sense.clear() R = [255, 0, 0] # red O = [255, 165, 0] # orange Y = [255, 255, 0] # yellow G = [0, 255, 0] # green B = [0, 55, 155] # blue I = [25, 0, 255] # indigo V = [255, 0, 255] # violet X = [0, 0, 0] # off rainbow = [ R, R, R, R, R, R, R, R, R, O, O, O, O, O, O, O, R, O, Y, Y, Y, Y, Y, Y, R, O, Y, G, G, G, G, G, R, O, Y, G, B, B, B, B, R, O, Y, G, B, I, I, I,
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()
#!/usr/bin/python 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 # 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 handle_event(event, colour):
counter += 1 return counter sense.stick.direction_up = move_up sense.stick.direction_down = move_down colorList = [(255, 0, 0), (255, 165, 0), (255, 255, 0), (0, 255, 0), (0, 0, 255), (238, 130, 238)] #from red to violet (low level to high level) colorIndex = 0 speedIndex = 0.5 count = 0 #to state how many succesful draw between the bat and the ball batCounter = 0 activate = 0 while True: sense.clear(0, 0, 0) color = colorList[colorIndex % len(colorList)] draw_bat(color, activate) draw_ball(count) sleep(speedIndex) if counter == 1: count += 1 if count == 7 and colorIndex < len(colorList) - 1: colorIndex += 1 speedIndex -= 0.075 count = 0 batCounter += 1 if batCounter >= 3: activate += 1 if ball_position[0] == 0: batCounter = 0
from sense_hat import SenseHat from time import sleep sense = SenseHat() red = (255,0,0) sense.clear(red) sleep(1) sense.clear() sense.show_message('hello')
#!/usr/bin/env python from sense_hat import SenseHat sense = SenseHat() r = 255 g = 255 b = 255 sense.clear((r, g, b))
from sense_hat import SenseHat from random import randint from time import sleep sense = SenseHat() num1 = randint(0, 255) num2 = randint(0, 255) num3 = randint(0, 255) sense.clear(num1, num2, num3) sleep(1) sense.clear()
] six = [ X, X, O, O, O, O, X, X, X, X, O, O, O, O, X, X, O, O, O, O, O, O, O, O, X, X, O, O, O, O, X, X, X, X, O, O, O, O, X, X, O, O, O, O, O, O, O, O, X, X, O, O, O, O, X, X, X, X, O, O, O, O, X, X ] # creates the roll dice functions and iterates 500 random numbers before stopping giving the visualization it's 'rolling' def roll_dice(): i = 0 while (i < 500): sense.clear() num_img = [one, two, thr, fou, fiv, six] #set the images in a list dice_num = random.randint(0, 5) #generates random number between 0-5 sense.set_pixels( num_img[dice_num]) #uses random number to pull from image list i += 1 #interates i #uses the accelerometer sensors to intiated the roll dice function while True: x, y, z, = list(sense.get_accelerometer_raw().values()) x, y, z = abs(x), abs(y), abs(z) #set x y and z values to absolute values if x > 1.4 or y > 1.4 or z > 1.4: roll_dice() sleep(3) #shows the dice/dots for 3 seconds before clearing the screen sense.clear() #rests the leds
from sense_hat import SenseHat from time import sleep from random import randint sense = SenseHat() sense.set_pixel(0, 2, [0, 0, 255]) sense.set_pixel(7, 4, [255, 0, 0]) sleep(1) r = randint(0, 255) sense.show_letter("T", text_colour=[0, r, 0]) sleep(2) sense.show_message("Hello Dad, I'm tallulah", scroll_speed=0.12, text_colour=[0, 251, 0], back_colour=[0, 0, 0]) sense.clear()
class ElectronicDice: x = (255, 255, 255) o = (0, 0, 0) # Different sides of a dice sides = [ [ o, o, o, o, o, o, o, o, o, o, o, o, o, o, o, o, o, o, o, o, o, o, o, o, o, o, o, x, x, o, o, o, o, o, o, x, x, o, o, o, o, o, o, o, o, o, o, o, o, o, o, o, o, o, o, o, o, o, o, o, o, o, o, o, ], [ o, o, o, o, o, o, o, o, o, o, o, x, x, o, o, o, o, o, o, x, x, o, o, o, o, o, o, o, o, o, o, o, o, o, o, o, o, o, o, o, o, o, o, x, x, o, o, o, o, o, o, x, x, o, o, o, o, o, o, o, o, o, o, o, ], [ x, x, o, o, o, o, o, o, x, x, o, o, o, o, o, o, o, o, o, o, o, o, o, o, o, o, o, x, x, o, o, o, o, o, o, x, x, o, o, o, o, o, o, o, o, o, o, o, o, o, o, o, o, o, x, x, o, o, o, o, o, o, x, x, ], [ o, o, o, o, o, o, o, o, o, x, x, o, o, x, x, o, o, x, x, o, o, x, x, o, o, o, o, o, o, o, o, o, o, o, o, o, o, o, o, o, o, x, x, o, o, x, x, o, o, x, x, o, o, x, x, o, o, o, o, o, o, o, o, o, ], [ o, o, o, o, o, o, o, o, o, x, x, o, o, x, x, o, o, x, x, o, o, x, x, o, o, o, o, x, x, o, o, o, o, o, o, x, x, o, o, o, o, x, x, o, o, x, x, o, o, x, x, o, o, x, x, o, o, o, o, o, o, o, o, o, ], [ o, x, x, o, o, x, x, o, o, x, x, o, o, x, x, o, o, o, o, o, o, o, o, o, o, x, x, o, o, x, x, o, o, x, x, o, o, x, x, o, o, o, o, o, o, o, o, o, o, x, x, o, o, x, x, o, o, x, x, o, o, x, x, o, ], ] def __init__(self): self.__sense = SenseHat() # Call the dice to roll def roll(self): while True: acceleration = self.__sense.get_accelerometer_raw() x = acceleration['x'] y = acceleration['y'] z = acceleration['z'] x = abs(x) y = abs(y) z = abs(z) # Check if the sense_hat is being shaked if x > 2 or y > 2 or z > 2: for i in range(3): self.__sense.set_pixels(random.choice(self.sides)) sleep(0.5) self.__sense.clear() result = random.choice(self.sides) print(self.sides.index(result) + 1) self.__sense.set_pixels(result) sleep(2) return self.sides.index(result) + 1 else: self.__sense.clear()
sense.set_pixels(xplod2) time.sleep(0.15) sense.set_pixels(xplod3) time.sleep(0.15) sense.set_pixels(xplod4) time.sleep(0.15) sense.set_pixels(xplod5) time.sleep(0.4) sense.clear(255,255,255) time.sleep(0.05) sense.set_pixels(xplod6) time.sleep(0.75) # Warning flash for i in range(50): sense.clear(255,255,255) time.sleep(0.05) sense.clear() time.sleep(0.05) # Message sense.show_message("10..9..8..7..6..5..4..3..2..1..", scroll_speed=0.08, text_colour=[204,0,0]) sense.show_message("HAPPY NEW YEAR!", scroll_speed=0.04, text_colour=[204,0,204]) sense.show_letter("2") time.sleep(0.25) sense.show_letter("0") time.sleep(0.25) sense.show_letter("1") time.sleep(0.25) sense.show_letter("6") time.sleep(0.25)
def sse_backwards(): sense = SenseHat() sense.clear() backwardsarrow.backwards() return Response(arduino_slave.move_backwards(sense), mimetype='text/event-stream')
send("Move") elif direction == "up": sense.show_message("Contacting Voltar") song = input("What sont do you want voltar to \"play\"?\n") send("Play " + song) elif direction == "down": sense.show_message("Glub") sleep(5) sense.clear((0, 0, 0)) sense.clear((0, 0, 0)) while True: for event in sense.stick.get_events(): if event.action == "released": dir = event.direction contact(dir)
if b >= STEP: b -= STEP colour = (r, g, b) set_centre_square(colour) sense = SenseHat() pygame.init() pygame.display.set_mode((640, 480)) target_colour = random_colour() initial_colour = random_colour() sense.clear(target_colour) set_centre_square(initial_colour) colour = initial_colour running = True while running: for event in pygame.event.get(): if event.type == pygame.QUIT: running = False elif event.type == pgl.KEYDOWN: if event.key == pgl.K_ESCAPE: running = False else: handle_event(event)
from sense_hat import SenseHat import time hat = SenseHat() fill = (255, 0, 0) while True: reading = int(hat.get_compass_raw()['z']) if reading > 200: hat.clear(fill) time.sleep(0.2) else: hat.clear()
from sense_hat import SenseHat sense = SenseHat() import time sense.clear() while True: for x in range(0, 255): sense.clear(255, x, 0) #red to yellow for x in range(0, 255): sense.clear(255-x, 255, 0) #yellow to green for x in range(0, 255): sense.clear(0, 255, x) #green to sky-blue for x in range(0, 255): sense.clear(0, 255-x, 255) #sky-blue to blue for x in range(0, 255): sense.clear(x, 0, 255) #blue to purple for x in range(0, 255): sense.clear(255, 0, 255-x) #purple to red
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 #### sensehat.clear( ) for loop in range( 0 , 2 ): for clr in range( 0 , 255 , 1 ): sensehat.set_pixel( 4 , 4 , clr , 0 , 0 ) time.sleep( 0.001 ) for clr in range( 255 , 0 , -1 ): sensehat.set_pixel( 4 , 4 , clr , 0 , 0 ) time.sleep( 0.001 ) sensehat.clear( ) time.sleep( .1 ) sensehat.clear( sens_defn.V ) time.sleep( .1 ) sensehat.clear( )
sense_hat = SenseHat() sense_hat.set_imu_config(False, False, False) except: print('Unable to initialize the Sense Hat library: {}'.format(sys.exc_info()[0])) sys.exit(1) # callback when change is detected in database def cb(self): current_matrix = firebase_ref_current_character.get() current_matrix_tuple = [] # convert array of strings to array of tuple if current_matrix and len(current_matrix) == 64: for color in current_matrix: current_matrix_tuple.append(tuple(map(int, color[1:-1].split(',')))) sense_hat.set_pixels(current_matrix_tuple) else: sense_hat.clear() def main(): firebase_ref_current_character.listen(cb) while True: sleep(100) if __name__ == "__main__": try: main() except (KeyboardInterrupt, SystemExit): print('Interrupt received! Stopping the application...') finally: print('Cleaning up the mess...') sense_hat.clear() sys.exit(0)
class pollingThread(QThread): def __init__(self): super().__init__() def run(self): self.db = QtSql.QSqlDatabase.addDatabase('QMYSQL') self.db.setHostName("3.34.124.67") self.db.setDatabaseName("16_3") self.db.setUserName("16_3") self.db.setPassword("1234") ok = self.db.open() print(ok) if ok == False : return self.mh = Raspi_MotorHAT(addr=0x6f) self.myMotor = self.mh.getMotor(1) self.pwm = PWM(0x6F) self.pwm.setPWMFreq(60) self.sense = SenseHat(1) while True: time.sleep(0.1) self.getQuery() self.setQuery() def setQuery(self): pressure = self.sense.get_pressure() temp = self.sense.get_temperature() humidity = self.sense.get_humidity() p = round((pressure - 1000) / 100, 3) t = round(temp / 100, 3) h = round(humidity / 100, 3) self.query = QtSql.QSqlQuery(); self.query.prepare("insert into sensing2 (time, num1, num2, num3, meta_string, is_finish) values (:time, :num1, :num2, :num3, :meta, :finish)"); time = QDateTime().currentDateTime() self.query.bindValue(":time", time) self.query.bindValue(":num1", p) self.query.bindValue(":num2", t) self.query.bindValue(":num3", h) self.query.bindValue(":meta", "") self.query.bindValue(":finish", 0) self.query.exec() a = int((p * 1271) % 256) b = int((t * 1271) % 256) c = int((h * 1271) % 256) self.sense.clear(a, b, c) def getQuery(self): query = QtSql.QSqlQuery("select * from command2 order by time desc limit 1"); query.next() cmdTime = query.record().value(0) cmdType = query.record().value(1) cmdArg = query.record().value(2) is_finish = query.record().value(3) if is_finish == 0 : print(cmdTime.toString(), cmdType, cmdArg) query = QtSql.QSqlQuery("update command2 set is_finish=1 where is_finish=0"); if cmdType == "go": self.go() if cmdType == "back": self.back() if cmdType == "left": self.left() if cmdType == "right": self.right() if cmdType == "mid": self.middle() #add if cmdType == "front" and cmdArg == "press" : self.go() self.middle() if cmdType == "leftside" and cmdArg == "press" : self.go() self.left() if cmdType == "rightside" and cmdArg == "press" : self.go() self.right() if cmdType == "front" and cmdArg == "release" : self.stop() if cmdType == "leftside" and cmdArg == "release" : self.stop() if cmdType == "rightside" and cmdArg == "release" : self.stop() def stop(self): print("MOTOR STOP") self.myMotor.run(Raspi_MotorHAT.RELEASE) def go(self): print("MOTOR GO") self.myMotor.setSpeed(50) self.myMotor.run(Raspi_MotorHAT.FORWARD) def back(self): print("MOTOR BACK") self.myMotor.setSpeed(50) self.myMotor.run(Raspi_MotorHAT.BACKWARD) def left(self): print("MOTOR LEFT") self.pwm.setPWM(0, 0, 150); def right(self): print("MOTOR RIGHT") self.pwm.setPWM(0, 0, 430); def middle(self): print("MOTOR MIDDLE") self.pwm.setPWM(0, 0, 350);
#!/usr/bin/python # Uses the user inputted message as a # command line argument. Argument is then # concatenated as a string, and sent to SenseHat. import sys from sense_hat import SenseHat sense = SenseHat() sense.clear(0, 0, 0) message = "" for index in range(len(sys.argv) - 1): if index == (len(sys.argv) - 1): message += sys.argv[index + 1] else: message += sys.argv[index + 1] + " " sense.show_message(message, text_colour=(0, 255, 0))
def readTemp(): sense = SenseHat() sense.clear() temp = sense.get_temperature() return temp
sh = SenseHat() # File to store high score highscorefile = open('/home/pi/.2048score','r') global highscore highscore = int(highscorefile.readline()) highscorefile.close() # Check that we can see the SenseHat Joystick devices = [InputDevice(fn) for fn in list_devices()] for dev in devices: print(dev.name) if dev.name == "Raspberry Pi Sense HAT Joystick": js=dev print('found') sh.clear() # Clear LEDs #Define the colours for each 'number' square global colour2 colour2 = [255,0,0] global colour4 colour4 = [255,128,0] global colour8 colour8 = [0,255,0] global colour16 colour16 = [255,255,0] global colour32 colour32 = [0,255,128] global colour64 colour64 = [255,0,128] global colour128 colour128 = [128,0,255]
#! /usr/bin/python3 #Wasmachine Testing from sense_hat import SenseHat from time import sleep import telebot from telebot import types bot = telebot.TeleBot("1300564024:AAGfIIywVz0d06CxCLvJ6ABP7xKhI7Rt7ek", parse_mode=None) sense = SenseHat() sense.low_light = True sense.clear(0, 0, 255) #CONFIG timelimit = 300 #3 minuten telegramid = 447307637 #Global Vars sw_status = False timelimit = timelimit * 10 def startWas(): #Default Values global sw_status gp = 0 gr = 0 gy = 0 timer = 0 if sw_status is False: sw_status = True bot.send_message(telegramid, "Wasmachine staat aan")