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 main(frames=FRAMES): """Show the frames on the sense hat.""" sense = SenseHat() for frame in frames: sense.set_pixels(frame) time.sleep(0.25)
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()
class RunTime: def __init__(self): self.apps = [] self.apps.append(Clock()) self.sense = SenseHat() def start(self): pygame.init() pygame.display.set_mode((640, 480)) running = True icon = self.apps[0].get_icon() self.display_icon(icon) """ while running: for event in pygame.event.get(): if event.type == QUIT: running = False else: if event.key == K_RIGHT: self.sense.clear() elif event.key == K_LEFT: self.display_icon(icon) else: running = False """ def display_icon(self, icon): e = [0, 0, 0] padded_icon = [] for i in range(0, len(icon)): padded_icon.append(e) padded_icon.extend(icon[i]) padded_icon.append(e) padded_icon.extend([e, e, e, e, e, e, e, e, e, e, e, e, e, e, e, e]) self.sense.set_pixels(padded_icon)
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()
class Screen: def __init__(self): self.sense = SenseHat() self.general_level = 0 self.wait_time = 4 self.cur_time = 0 self.clear() self.balance = 0 def clear(self): for i in range(SIZE): for j in range(SIZE): self.sense.set_pixel(i, j, BLACK) def clear_col(self, x): for i in range(0, 7): self.sense.set_pixel(x, i, BLACK) def plot_bar(self, x, height, colors=None): if colors is None: colors = BAR_COLORS self.clear_col(x) for i in range(height): self.sense.set_pixel(x, 7 - i, colors[7 - i]) def plot_balance(self): for i in range(SIZE): self.plot_bar(i, max(1, self.general_level), BAR_COLORS) def show_amount(self): self.show_message(str(self.balance), color=list(BAR_COLORS[min(7, 8 - self.general_level)])) def show_message(self, message, speed=0.1, color=[255, 255, 255]): self.sense.show_message(message, speed, color) self.plot_balance() """ Parses an input in the form: balance percentage """ def parse_input(self, line): self.cur_time = 0 # Split balance and percentage. [self.balance, percent] = [float(x) for x in line.split()] self.general_level = int(round(min(max(0, percent), 100) / 100.0 * SIZE)) self.draw_check() def draw_check(self): types = [BLACK, GREEN] pixels = [types[CHECK[i / SIZE][i % SIZE]] for i in range(SIZE * SIZE)] self.sense.set_pixels(pixels) def no_text(self): self.cur_time += SLEEP_TIME if self.cur_time > self.wait_time: self.cur_time = 0 self.show_amount()
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 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 draw_bluetooth(): B = [0, 0, 255] # Blue O = [255, 255, 255] # White sense = SenseHat() bluetooth_logo = [ O, O, O, O, O, O, O, O, O, O, O, B, O, O, O, O, O, O, O, B, B, O, O, O, O, B, O, B, O, B, O, O, O, O, B, B, B, O, O, O, O, B, O, B, O, B, O, O, O, O, O, B, B, O, O, O, O, O, O, B, O, O, O, O ] sense.set_pixels(bluetooth_logo)
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 hello_world(): sense = SenseHat() X = [255, 0, 0] # Red O = [255, 255, 255] # White question_mark = [ O, O, O, X, X, O, O, O, O, O, X, O, O, X, O, O, O, O, O, O, O, X, O, O, O, O, O, O, X, O, O, O, O, O, O, X, O, O, O, O, O, O, O, X, O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, X, O, O, O, O ] sense.set_pixels(question_mark) return 'Hello World!'
def Main(): '''Wrapper.''' # # Collect data. # data = FetchCitiBikeData() station = ExtractStationData(data=data,id=445) # # Generate pixels. # pixels = GeneratePixels(station['data']['availableBikes']) # # Send to SenseHAT. # sense = SenseHat() sense.set_pixels(pixels)
def display2(self): # Levels of dist d1 = self.int2rgb(self.siglevel_dt(-20,0)) d2 = self.int2rgb(self.siglevel_dt(-40,-21)) d3 = self.int2rgb(self.siglevel_dt(-60,-41)) d4 = self.int2rgb(self.siglevel_dt(-100,-61)) #print self.siglevel_dt(-50,0) sense = SenseHat() pixels = [ d4,d4,d4,d4,d4,d4,d4,d4, d4,d3,d3,d3,d3,d3,d3,d4, d4,d3,d2,d2,d2,d2,d3,d4, d4,d3,d2,d1,d1,d2,d3,d4, d4,d3,d2,d1,d1,d2,d3,d4, d4,d3,d2,d2,d2,d2,d3,d4, d4,d3,d3,d3,d3,d3,d3,d4, d4,d4,d4,d4,d4,d4,d4,d4] sense.set_pixels(pixels)
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 senseHatDisplay(self): # Display in round formation ish # Signal level is pixels # Counts of macs to color # Levels of dist d0 = [0,0,0] d1 = self.int2rgb(self.siglevel_dt(-30,0)) d2 = self.int2rgb(self.siglevel_dt(-50,-31)) d3 = self.int2rgb(self.siglevel_dt(-70,-51)) d4 = self.int2rgb(self.siglevel_dt(-100,-71)) sense = SenseHat() pixels = [ d0,d0,d0,d4,d4,d0,d0,d0, d0,d0,d4,d3,d3,d4,d0,d0, d0,d4,d3,d2,d2,d3,d4,d0, d4,d3,d2,d1,d1,d2,d3,d4, d4,d3,d2,d1,d1,d2,d3,d4, d0,d4,d3,d2,d2,d3,d4,d0, d0,d0,d4,d3,d3,d4,d0,d0, d0,d0,d0,d4,d4,d0,d0,d0] sense.set_pixels(pixels)
e, y, y, r, r, y, e, e, e, e, y, y, y, y ] emoji16 = [ e, e, e, y, y, y, y, e, e, e, y, y, y, y, y, y, e, y, y, b, y, y, b, y, e, y, y, y, y, y, y, y, e, y, r, y, y, y, y, r, e, y, y, r, r, r, r, y, e, e, y, y, r, r, y, y, e, e, e, y, y, y, y, e ] # Configure Sense Hat LED Matrix sense.low_light = True sense.set_rotation(180) sense.clear() # Flash Emoji sense.set_pixels(emoji2) time.sleep(.5) sense.set_pixels(emoji1) time.sleep(.5) sense.set_pixels(emoji2) time.sleep(.5) sense.set_pixels(emoji1) time.sleep(.5) sense.set_pixels(emoji2) time.sleep(.5) sense.set_pixels(emoji1) time.sleep(.5) sense.set_pixels(emoji2) time.sleep(1) #Animated scroll out to left
class WeatherStation(CarouselContainer): """Weather Station controlling class, setups and manages station run time.""" # Constants SMOOTH_READINGS_NUMBER = 3 READINGS_PRINT_TEMPLATE = 'Temp: %sC (%sF), Humidity: %s%%, Pressure: %s inHg' def __init__(self): super(WeatherStation, self).__init__() self._sense_hat = None self._log_timer = None self._upload_timer = None self._update_timer = None self._last_readings = None @property def carousel_items(self): return DEFAULT_WEATHER_ENTITIES @property def current_style(self): return self.current_item.current_style def activate_sensors(self): """Activates sensors by requesting first values and assigning handlers.""" self._sense_hat = SenseHat() # Scroll Init message over HAT screen self._show_message('Init Sensors', (255, 255, 0), (0, 0, 255)) # Init sensors, to be sure first effective run uses correct sensors values self._sense_hat.get_humidity() self._sense_hat.get_pressure() # Setup Sense Hat stick self._sense_hat.stick.direction_up = self._change_weather_entity self._sense_hat.stick.direction_down = self._change_weather_entity self._sense_hat.stick.direction_left = self._change_weather_entity self._sense_hat.stick.direction_right = self._change_weather_entity def start_station(self): """Launches multiple threads to handle configured behavior.""" if Config.LOG_TO_CONSOLE and Config.LOG_INTERVAL: self._log_results(first_time=True) if Config.WEATHER_UPLOAD and Config.UPLOAD_INTERVAL: self._upload_results(first_time=True) if Config.UPDATE_DISPLAY and Config.UPDATE_INTERVAL: self._update_display() def stop_station(self): """Tries to stop active threads and clean up screen.""" if self._sense_hat: self._sense_hat.clear() if self._log_timer: self._log_timer.cancel() if self._upload_timer: self._upload_timer.cancel() if self._update_timer: self._update_timer.cancel() @staticmethod def to_fahrenheit(value): """Converts celsius temperature to fahrenheit.""" return (value * 1.8) + 32 @staticmethod def calculate_dew_point(temp, hum): """ Calculates dewpoint in celsius, uses simplified formula less accurate but obvious. https://en.wikipedia.org/wiki/Dew_point#Calculating_the_dew_point """ return temp - (100 - hum) / 5 def get_temperature(self): """ Gets temperature and adjusts it with environmental impacts (like cpu temperature). There are some issues, getting an accurate temperature reading from the Sense HAT is improbable, see here: https://www.raspberrypi.org/forums/viewtopic.php?f=104&t=111457 We need to take CPU temp into account. The Pi foundation recommendeds using the following: http://yaab-arduino.blogspot.co.uk/2016/08/accurate-temperature-reading-sensehat.html """ # Get temp readings from both sensors humidity_temp = self._sense_hat.get_temperature_from_humidity() pressure_temp = self._sense_hat.get_temperature_from_pressure() # avg_temp becomes the average of the temperatures from both sensors # We need to check for pressure_temp value is not 0, to not ruin avg_temp calculation avg_temp = (humidity_temp + pressure_temp) / 2 if pressure_temp else humidity_temp # Get the CPU temperature cpu_temp = self._get_cpu_temp() # Calculate temperature compensation for CPU heating # Depending on Raspberry Pi model (2, 3 etc.) and case you may try different formulas # The commented option below is recommended for Raspberry Pi 3 by: # http://yaab-arduino.blogspot.co.uk/2016/08/accurate-temperature-reading-sensehat.html # adj_temp = avg_temp - (cpu_temp - avg_temp) / 1.5 # Adjustment for pi zero install, 2-17-2019 (cpu 20.2, sense 10.2, actual 33F(0.55C)) # 2-19-2019 (cpu 20.2, sense 13, actual 33F(0.55C)) adj_temp = avg_temp - (cpu_temp - avg_temp) / 1.05 print('\033[92mCPU temp: %s, Avg temp: %s, Adj temp: %s\033[0m' % (cpu_temp, avg_temp, adj_temp)) # Average out value across the last three readings return self._get_smooth(adj_temp) def get_humidity(self): """Gets humidity sensor value.""" return self._sense_hat.get_humidity() def get_pressure(self): """Gets humidity sensor value and converts pressure from millibars to inHg before posting.""" return self._sense_hat.get_pressure() * 0.0295300 def get_sensors_data(self): """Returns sensors data tuple.""" temp_in_celsius = self.get_temperature() return ( round(temp_in_celsius, 1), round(self.to_fahrenheit(temp_in_celsius), 1), round(self.get_humidity(), 0), round(self.get_pressure(), 1) ) def _change_weather_entity(self, event): """Internal. Switches to next/previous weather entity or next/previous visual style.""" # We need to handle release event state if event.action == ACTION_RELEASED: self._sense_hat.clear() if event.direction == DIRECTION_UP: next_entity = self.next_item self._show_message(next_entity.entity_messsage, next_entity.positive_color) elif event.direction == DIRECTION_DOWN: previous_entity = self.previous_item self._show_message(previous_entity.entity_messsage, previous_entity.positive_color) elif event.direction == DIRECTION_LEFT: self.current_item.previous_item else: self.current_item.next_item self._update_display(loop=False) def _show_message(self, message, message_color, background_color=(0, 0, 0)): """Internal. Shows message by scrolling it over HAT screen.""" # Need to be sure we revert any changes to rotation self._sense_hat.rotation = 0 self._sense_hat.show_message(message, Config.SCROLL_TEXT_SPEED, message_color, background_color) def _log_results(self, first_time=False): """Internal. Continuously logs sensors values.""" if not first_time: print(self.READINGS_PRINT_TEMPLATE % self.get_sensors_data()) self._log_timer = self._start_timer(Config.LOG_INTERVAL, self._log_results) def _update_display(self, loop=True): """Internal. Continuously updates screen with new sensors values.""" sensors_data = self.get_sensors_data() if self.current_item.entity_type is WeatherEntityType.TEMPERATURE: pixels = self.current_item.show_pixels(sensors_data[1]) elif self.current_item.entity_type is WeatherEntityType.HUMIDITY: pixels = self.current_item.show_pixels(sensors_data[2]) else: pixels = self.current_item.show_pixels(sensors_data[3]) self._sense_hat.set_rotation(self.current_style.rotation) self._sense_hat.set_pixels(pixels) if loop: self._update_timer = self._start_timer(Config.UPDATE_INTERVAL, self._update_display) def _upload_results(self, first_time=False): """Internal. Continuously uploads new sensors values to Weather Underground.""" if not first_time: print('Uploading data to Weather Underground') sensors_data = self.get_sensors_data() # Build a weather data object http://wiki.wunderground.com/index.php/PWS_-_Upload_Protocol weather_data = { 'action': 'updateraw', 'ID': Config.STATION_ID, 'PASSWORD': Config.STATION_KEY, 'dateutc': 'now', 'tempf': sensors_data[1], 'humidity': sensors_data[2], 'baromin': sensors_data[3], 'dewptf': self.to_fahrenheit(self.calculate_dew_point(sensors_data[0], sensors_data[2])) } for plugin in Config.PLUGINS: try: data = plugin.get_data() for error in plugin.errors: logging.warning('%s got an error: %s', plugin.plugin_name, error.message) if data: print('\033[94m%s got data: %s\033[0m' % (plugin.plugin_name, data)) weather_data.update(data) else: print('\033[94m%s has no data\033[0m' % plugin.plugin_name) logging.warning('%s has no data', plugin.plugin_name) except: logging.warning('Unexpected error occured in %s', plugin.plugin_name, exc_info=True) try: upload_url = Config.WU_URL + '?' + urlencode(weather_data) response = urllib2.urlopen(upload_url) html = response.read() print('Server response: ', html) # Close response object response.close() except: print('Could not upload to Weather Underground') logging.warning('Could not upload to Weather Underground\r\nWeather Data: %s\r\nUpload URL: %s', weather_data, upload_url, exc_info=True) self._upload_timer = self._start_timer(Config.UPLOAD_INTERVAL, self._upload_results) def _start_timer(self, interval, callback): """Internal. Starts timer with given interval and callback function.""" timer = Timer(interval, callback) timer.daemon = True timer.start() return timer def _get_cpu_temp(self): """" Internal. Executes a command at the OS to pull in the CPU temperature. Thanks to https://www.raspberrypi.org/forums/viewtopic.php?f=104&t=111457 """ res = os.popen('vcgencmd measure_temp').readline() return float(res.replace('temp=', '').replace("'C\n", '')) def _get_smooth(self, value): """Moving average to smooth reading.""" # We use deque here as it is more efficient for in/out behaviour than regular list/tuple if not self._last_readings: self._last_readings = deque((value, ) * self.SMOOTH_READINGS_NUMBER, self.SMOOTH_READINGS_NUMBER) else: self._last_readings.appendleft(value) # Average last temperature readings return sum(self._last_readings) / self.SMOOTH_READINGS_NUMBER
n, n, p, p, p, p, n, n, n, n, n, p, p, n, n, n, n, n, n, n, n, n, n, n, ] s.set_pixels(heart) time.sleep(6) s.show_message("I LOVE SAMOS")
b, a, b, b, b, b, a, b, b, a, b, b, ] #Turn on the TicTacToe board and cursor sense.set_pixels(board) sense.set_pixel(x, y, team1, selectcolor, team2) #Run this function any time the joystick is pushed in def select(event): global team1, team2 global x, y global board #If the joystick is pressed and this spot on the board has not already been selected: if event.action == ACTION_PRESSED and board[(col * y) + x] == b: if team1 == 255: #If it is the red player's turn: #Set the four LEDs to red board[(col * y) + x] = rd
import time from sense_hat import SenseHat X = (255, 0, 0) O = (255, 255, 255) question_mark = [ O, O, O, X, X, O, O, O, O, O, X, O, O, X, O, O, O, O, O, O, O, X, O, O, O, O, O, O, X, O, O, O, O, O, O, X, O, O, O, O, O, O, O, X, O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, X, O, O, O, O ] sense = SenseHat() sense.set_pixels(question_mark) sense.set_pixel(0, 0, 255, 0, 0) sense.set_pixel(0, 7, 0, 255, 0) sense.set_pixel(7, 0, 0, 0, 255) sense.set_pixel(7, 7, 255, 0, 255) while True: for r in [0, 90, 180, 270]: sense.set_rotation(r) time.sleep(0.3)
r, w, w, w, w, w, w, w, w, r, r, r, r, r, r, r, r, w, w, w, w, w, w, w, w, ] sense.set_pixels(pixels) time.sleep(5) sense.clear()
from sense_hat import SenseHat import digit, time sense = SenseHat() sense.clear() sense.set_rotation(180) while True: temp = int(round(sense.get_temperature(), 0)) # "Calibrate" temp -= 10 print(temp) sense.set_pixels(digit.makedigit(temp)) # Check every minute time.sleep(60)
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)
X, Y, Y, Y, Y, Y, Y, X, X, Y, Y, Y, Y, Y, Y, X ] number_zero = [ X, Y, Y, Y, Y, Y, Y, X, X, Y, Y, Y, Y, Y, Y, X, X, Y, Y, X, X, Y, Y, X, X, Y, Y, X, X, Y, Y, X, X, Y, Y, X, X, Y, Y, X, X, Y, Y, X, X, Y, Y, X, X, Y, Y, Y, Y, Y, Y, X, X, Y, Y, Y, Y, Y, Y, X ] sense.set_pixels(number_one) ###CODE TO GET TWITTER TO LISTEN FOR KEYWORD### class My_Tweets(tweepy.StreamListener): def on_status(self, tweet): ###ASCII Dictionary### try: print tweet.user.screen_name print tweet.text Tweet = str(tweet.text.lower()) print type(Tweet) print "" time.sleep(1) """Converts the letter to a Binary Value"""
w, w, w, w, b, w, w, w, w, b, w, w, w, b, b, b, b, w, w, w, w, w, w, w, w, w, w, ] sense.set_pixels(smiley_pixels)
g, bl, p, p, p, g, g, g, g, g, r, b, r, g, g, g, g, r, b, b, b, r, g, g, g, g, b, b, b, g, g, g, g, bl, bl, g, bl, bl, g, g, ] marioUp = [ g, g, r, r, r, r, g, g, g, bl, p, p, p, g, g, g, g, bl, p, p, p, r, g, g, g, g, r, b, r, g, g, g, g, r, b, b, b, g, g, g, g, g, b, b, b, g, g, g, g, bl, bl, g, bl, bl, g, g, g, g, g, g, g, g, g, g, ] sense.clear() sense.set_pixels(marioDown) def jump(): event = sense.stick.wait_for_event() if (event): sense.set_pixels(marioUp) time.sleep(0.2) sense.set_pixels(marioDown) jump() jump()
O, O, O, O, R, R, R, R, O, O, O, O ], [ R, O, O, R, R, R, R, O, R, O, O, R, O, O, R, O, R, O, O, R, O, O, R, O, R, R, R, R, O, O, R, O ], [ R, O, O, R, R, R, R, O, R, O, O, R, O, O, R, O, R, O, O, R, O, O, R, O, R, R, R, R, R, R, R, O ], [ R, R, R, R, R, R, R, 0, R, O, O, O, O, O, O, O, R, O, O, O, O, O, O, O, R, O, O, O, O, O, O, O ], [ R, R, R, R, R, R, R, 0, R, O, O, R, O, O, R, O, R, O, O, R, O, O, R, O, R, R, R, R, R, R, R, O ], [ R, R, R, R, R, R, R, 0, R, O, O, R, O, O, O, O, R, O, O, R, O, O, O, O, R, R, R, R, O, O, O, O ]] tempInt = int(temp) tempTens = int(tempInt / 10) tempOnes = tempInt - (10 * tempTens) FinalArray = displayValue[tempOnes] + displayValue[tempTens] print(FinalArray) sense.set_pixels(FinalArray) #sense.show_message(str(int(temp)))
B, B, B, B, B, B, B, B, W, W, W, W, W, W, W, W, B, B, B, B, B, B, B, B, W, W, W, W, W, W, W, W, ] return logo def getCPUtemperature(): res = os.popen('vcgencmd measure_temp').readline() return(res.replace("temp=","").replace("'C\n","")) # Clear SenseHat LEDs sense.clear() # Output our Logo, the Greek Flag followed by our School's name sense.set_pixels(greek_flag()) time.sleep(3) sense.show_message("2o Gymnasio Samou", scroll_speed=0.07, text_colour=blue) # Open a file for writing (creates file if not exists), to collect program's data # In Excel Spreadsheet use Menu Data > Get External From Text , use comma delimiter file = open("SamiansLogMission2.csv", "a") # Add in the file, the columns labels (\n for new line) file.write("Date, Time, Temperature, Humidity, Pressure, Gyro_x, Gyro_y, Gyro_z \n") print("Data Log File to be used: SamiansLogMission2.csv for Date, Time, Temperature, Humidity, Gyro_x, Gyro_y, Gyro_z") # Variable "seconds" measures the total execution time of this program # It is used to stop the program after 1,5 hrs of running time, as suggested by the Contest Instructions seconds = 0 # initialise
w = (255, 255, 255) b = (0, 0, 0) picture = [ b, b, w, w, w, w, b, b, b, w, b, b, b, b, w, b, b, w, b, w, w, b, w, b, b, w, b, b, b, b, w, b, b, b, w, w, w, w, b, b, b, b, w, w, w, w, b, b, b, w, w, w, w, w, w, b, b, w, w, w, w, w, w, b ] sense.set_rotation(0) sense.set_pixels(picture) time.sleep(2) sense.show_message("Temp: ", text_colour=(255, 0, 0), back_colour=(0,0,0), scroll_speed=0.1) sense.show_message(str(round(temp,1)), text_colour=(255, 0, 0), back_colour=(0,0,0), scroll_speed=0.1) sense.show_message(str(round(pressure,0))[:-2], text_colour=(255, 0, 0), back_colour=(0,0,0), scroll_speed=0.1) sense.show_message(str(round(humidity,0))[:-2], text_colour=(255, 0, 0),
if 1 < pitch < 179 and x != 0: new_x -= 1 elif 181 < pitch < 359 and x != 7: new_x += 1 if 1 < roll < 179 and y != 7: new_y += 1 elif 359 > roll > 179 and y != 0: new_y -= 1 new_x, new_y = check_wall(x, y, new_x, new_y) new_x, new_y = check_gate(x, y, new_x, new_y) return new_x, new_y most_recent_maze = maze while game_over == False: o = sense.get_orientation() pitch = o["pitch"] roll = o["roll"] x, y = move_marble(pitch, roll, x, y) if maze[y][x] == g: sense.show_message("YOU GOT THIS VICTORY ROYALE") game_over = True maze[y][x] = w if maze[y][x] == T: most_recent_maze = maze_non sense.set_pixels(sum(most_recent, [])) sense.set_pixels(sum(most_recent_maze, [])) sleep(0.05) maze[y][x] = b
from sense_hat import SenseHat sense = SenseHat() B = (102, 51, 0) b = (0, 0, 255) S = (205, 133, 63) W = (255, 255, 255) steve_pixels = [ B, B, B, B, B, B, B, B, B, B, B, B, B, B, B, B, B, S, S, S, S, S, S, B, S, S, S, S, S, S, S, S, S, W, b, S, S, b, W, S, S, S, S, B, B, S, S, S, S, S, B, S, S, B, S, S, S, S, B, B, B, B, S, S ] sense.set_pixels(steve_pixels)
data.append( { "temp": sense.get_temperature(), "pressure": sense.get_pressure(), "humidity": sense.get_humidity(), "time": today.strftime("%Y-%m-%d %H:%M:%S") } ) # Write new data to file with open("/home/james/weather/get_weather/data/data.json", "w") as new_file: json.dump(data, new_file) orange = [255,69,0] yellow = [255,255,0] blue = [0,0,255] dark_blue = [0,0,139] if outdoor_temp <= 2: color_array = [dark_blue] * 64 elif outdoor_temp >= 3 and outdoor_temp <= 8: color_array = [blue] * 64 elif outdoor_temp >= 9 and outdoor_temp <= 15: color_array = [yellow] * 64 else: color_array = [orange] * 64 sense.set_pixels(color_array)
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 == True: last_angle = angle while angle == last_angle: angle = random.choice([0, 90, 180, 270]) 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 = score + 1 elif x == 1 and angle == 0: sense.set_pixels(arrow_green)
class GameOfLife: def __init__(self, N=8): self.red = [255, 0, 0] self.green = [0, 255, 0] self.C = [0, 0, 255] self.O = [0, 0, 0] self.sense = SenseHat() self.playing = False self.N = N self.matrix = [self.O] * 64 self.old_grid = np.zeros(N * N) self.new_grid = np.zeros(N * N) self.currX = 3 self.currY = 3 def draw(self): """ Convert the numpy array into a 64 matrix with colors then displays it on the monitor. Parameters ---------- / Returns ------- / """ for i in range(self.N): for j in range(self.N): if self.old_grid[j * 8 + i] == 1: self.matrix[j * 8 + i] = self.C else: self.matrix[j * 8 + i] = self.O self.sense.set_pixels(self.matrix) def neighbours(self, x, y): """ Return the number of living cells adjacent to the cell in pos (x,y). Parameters ---------- x: int X-axis position y: int Y-axis position Returns ------- count: int Number of living cells adjacent """ count = 0 for i in range(3): for j in range(3): new_x = (x + i + 7) % 8 new_y = (y + j + 7) % 8 if self.old_grid[new_y * 8 + new_x] == 1: count += 1 if self.old_grid[y * 8 + x] == 1: count -= 1 return count def next_gen(self): """ Compute the next generation of living cells and update the matrix. For each index of the matrix, get the number of living neighbour cells and check if there should be a cell in the index or not according to the rules of Conway's Game of Life. Finally copy the new matrix into the old one. Parameters ---------- / Returns ------- / """ for i in range(self.N): for j in range(self.N): index = j * 8 + i neighs = self.neighbours(i, j) curr_state = self.old_grid[index] if (curr_state == 1 and neighs < 2): self.new_grid[index] = 0 elif (curr_state == 1 and (neighs == 2 or neighs == 3)): self.new_grid[index] = 1 elif (curr_state == 1 and neighs > 3): self.new_grid[index] = 0 elif (curr_state == 0 and neighs == 3): self.new_grid[index] = 1 else: self.new_grid[index] = 0 if np.array_equal(self.old_grid, self.new_grid): self.C = self.red self.old_grid = self.new_grid.copy() def foo(self): """ Used to dismount the stick. Parameters ---------- / Returns ------- """ return def dismount(self): """ Dismount the stick directions so it doesn't interfere. Parameters ---------- / Returns ------- / """ self.sense.stick.direction_up = self.foo self.sense.stick.direction_down = self.foo self.sense.stick.direction_right = self.foo self.sense.stick.direction_left = self.foo def pushed_up(self, event): """ Upon getting pressed, move the current cell 1 pixel up Parameters ---------- event: Event Either ACTION_PRESSED, ACTION_HELD, ACTION_RELEASED Returns ------- / """ if event.action != ACTION_RELEASED: self.currY = (self.currY - 1) % 8 def pushed_down(self, event): """ Upon getting pressed, move the current cell 1 pixel down Parameters ---------- event: Event Either ACTION_PRESSED, ACTION_HELD, ACTION_RELEASED Returns ------- / """ if event.action != ACTION_RELEASED: self.currY = (self.currY + 1) % 8 def pushed_right(self, event): """ Upon getting pressed, move the current cell 1 pixel right Parameters ---------- event: Event Either ACTION_PRESSED, ACTION_HELD, ACTION_RELEASED Returns ------- / """ if event.action != ACTION_RELEASED: self.currX = (self.currX + 1) % 8 def pushed_left(self, event): """ Upon getting pressed, move the current cell 1 pixel left Parameters ---------- event: Event Either ACTION_PRESSED, ACTION_HELD, ACTION_RELEASED Returns ------- / """ if event.action != ACTION_RELEASED: self.currX = (self.currX - 1) % 8 def pushed_middle(self, event): """ Perform several actions depending on the game playing state and the event If the state is playing, pressing or holding the middle button will display the next generation If the state is not playing, pressing the button will change the state of the current cell. If the state is not playing, holding the button will change the playing state and launch the first generation Parameters ---------- event: Event Either ACTION_PRESSED, ACTION_HELD, ACTION_RELEASED Returns ------- / """ if not self.playing: if event.action != ACTION_RELEASED: self.old_grid[self.currY * 8 + self.currX] = 1 if self.old_grid[ self.currY * 8 + self.currX] == 0 else 0 if event.action == ACTION_HELD: self.playing = True self.dismount() self.next_gen() else: if (event.action == ACTION_PRESSED or event.action == ACTION_HELD): self.next_gen() def refresh(self): """ Clear the monitor and draw the current matrix. Parameters ---------- / Returns ------- / """ self.sense.clear() self.draw() if not self.playing: is_cell = self.green if self.old_grid[ self.currY * 8 + self.currX] == 1 else self.red self.sense.set_pixel(self.currX, self.currY, is_cell) def mount(self): """ Bind each stick direction to its corresponding function Parameters ---------- / Returns ------- / """ self.sense.stick.direction_up = self.pushed_up self.sense.stick.direction_down = self.pushed_down self.sense.stick.direction_right = self.pushed_right self.sense.stick.direction_left = self.pushed_left self.sense.stick.direction_middle = self.pushed_middle self.sense.stick.direction_any = self.refresh
[n,b,n,n,], [n,b,n,n,], [n,b,n,n,], [n,b,n,n,], [b,b,b,n,], ], [ [n,b,n,n,], [b,n,b,n,], [n,n,b,n,], [n,b,n,n,], ] ] load0 = [ b,g,y,o,r,m,p,b, sense.set_pixels(play) sleep(1) sense.set_pixels(pause) sleep(1) sense.set_pixels(stop) sleep(1) sense.set_pixels(off) sleep(1) while True: sense.set_pixels(load0) sleep(0.2) sense.set_pixels(load1) sleep(0.2) sense.set_pixels(load2)
fahrenheit = abs(fahrenheit) fahrenheit_color = negative_fahrenheit_color # Map digits to the display array pixel_offset = 0 index = 0 for index_loop in range(0, 4): for counter_loop in range(0, 4): display[index] = number[int(celcius/10)*16+pixel_offset] display[index+4] = number[int(celcius%10)*16+pixel_offset] display[index+32] = number[int(fahrenheit/10)*16+pixel_offset] display[index+36] = number[int(fahrenheit%10)*16+pixel_offset] pixel_offset = pixel_offset + 1 index = index + 1 index = index + 4 # Color the temperatures for index in range(0, 64): if display[index]: if index < 32: display[index] = celcius_color else: display[index] = fahrenheit_color else: display[index] = empty # Display the temperatures sense.low_light = True # Optional sense.set_pixels(display) time.sleep(1)
X = [0, 0, 0] # Black W = [255, 255, 255] # White def question_mark(): emoji = [ W, W, W, R, R, W, W, W, W, W, R, W, W, R, W, W, W, W, W, W, W, R, W, W, W, W, W, W, R, W, W, W, W, W, W, R, W, W, W, W, W, W, W, R, W, W, W, W, W, W, W, W, W, W, W, W, R, W, W, R, W, W, W, W ] return emoji def face(): emoji = [ X, X, X, Y, Y, X, X, X, X, X, Y, Y, Y, Y, X, X, X, Y, Y, Y, Y, Y, Y, X, Y, Y, Y, Y, Y, Y, Y, Y, Y, Y, Y, Y, Y, Y, Y, Y, X, Y, Y, Y, Y, Y, Y, X, X, X, Y, Y, Y, Y, X, X, X, X, X, Y, Y, X, X, X ] return emoji display = [question_mark, face] count = 0 while True: sense.set_pixels(display[count % len(display)]()) time.sleep(3) count += 1 ##https://pythonhosted.org/sense-hat/api/
r = (255, 0, 0) g = (0, 255, 0) w = (255, 255, 255) e = (0, 0, 0) locked = [ e, e, e, e, e, e, e, e, e, e, e, w, w, e, e, e, e, e, w, e, e, w, e, e, e, e, w, e, e, w, e, e, e, e, r, r, r, r, e, e, e, e, r, r, r, r, e, e, e, e, r, r, r, r, e, e, e, e, e, e, e, e, e, e ] unlocked = [ e, e, e, e, e, e, e, e, e, e, e, e, e, w, w, e, e, e, e, e, w, e, e, w, e, e, e, e, w, e, e, w, e, e, g, g, g, g, e, e, e, e, g, g, g, g, e, e, e, e, g, g, g, g, e, e, e, e, e, e, e, e, e, e ] ##### Main Program ##### sense = SenseHat() sense.set_pixels(locked) sleep(2) ##### Locks ##### ##### Unlocked ##### sense.set_pixels(unlocked) sleep(2) sense.show_message("This is a secret message", scroll_speed=0.05, text_colour=(255, 0, 0))
by=4 diffV=1 X=[255,100,0] S=[0,0,0] field=[S]*64 while(True): orien = sense.get_orientation_degrees() pdiff=orien['pitch']-base_pitch rdiff=orien['roll']-base_roll print '{} {} {}'.format(orien['pitch'],base_pitch,pdiff) print '{} {} {}'.format(orien['roll'],base_roll,rdiff) #print '{} {}'.format(orien['yaw'],base_yaw) print'######################################' if(pdiff> diffV): if(bx>0): bx-=1 elif(pdiff < -diffV): if(bx<7): bx+=1 if(rdiff >diffV): if(by<7): by+=1 elif(rdiff < -diffV): if(by >0): by-=1 for i in range(0,63): field[i]=S sense.set_pixels(field) sense.set_pixel(bx,by,X) sleep(1)
e,y,y,y,y,y,y,e ] image5 = [ e,e,e,e,e,e,e,e, e,y,y,y,y,y,y,e, e,e,y,e,e,y,e,e, e,e,y,e,e,y,e,e, e,e,e,y,y,e,e,e, e,e,y,b,b,y,e,e, 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)
#Get everything imported. from sense_hat import SenseHat from time import sleep from datetime import datetime import time #Standard definitions sense = SenseHat() # Define some colours g = (0, 255, 0) # Green b = (0, 0, 0) # Black #Define Finished Image exclaimation_mark = [ g, g, g, b, b, g, g, g, g, g, g, b, b, g, g, g, g, g, g, b, b, g, g, g, g, g, g, b, b, g, b, g, g, g, g, b, b, g, g, g, g, g, g, b, b, g, g, g, g, g, g, g, b, g, g, g, g, g, g, b, b, g, g, g ] #Start the loop 48 times, as the process waits 5 minutes, times 48 equals four hours. for i in range(48): humidity = sense.get_humidity() temp = sense.get_temperature() sense.show_message("Testing!") print(time.ctime()) print("Humidity: %s %%rH" % humidity) print("Temperature: %s C" % temp) sleep(300) #Show message when done! else: sense.set_pixels(exclaimation_mark)
elif opt == "-g": isMatch = isGreen elif opt == "-b": isMatch = isBlue elif opt == "-l": sense.low_light = True elif opt == "--rgb": rgb = arg.split(',') print "arg {}, rgb {}".format(arg, rgb) red = int(rgb[0]) green = int(rgb[1]) blue = int(rgb[2]) #Initialize the pixels with random colors sense.set_pixels([[randint(0, 255), randint(0, 255), randint(0, 255)] for x in xrange(0, 64)]) print "rgb={},{},{}, isMatch={}".format(red, green, blue, inspect.getsourcelines(isMatch)) iteration = 0 try: matches = 0 while True: grid = sense.get_pixels() for i in xrange(0, len(grid)): if not isMatch(grid[i]): grid[i] = [randint(0, 255), randint(0, 255), randint(0, 255)] else: print "Pixel {} matches [{},{},{}]".format(i, red, green, blue)
def fade( pixel ): new_pixel=[] for comp in pixel: if comp>0: new_pixel.append( comp-1) else: new_pixel.append( 0 ) return new_pixel while True: rx=random.randint(0,3) ry=random.randint(0,3) if random.randint(0,100) < 25: col=[ random.randint(0,255), random.randint(0,255), random.randint(0,255) ] if sense.get_pixel(rx,ry)==[0,0,0]: sense.set_pixel(rx, ry, col) sense.set_pixel(7-rx, ry, col) sense.set_pixel(7-rx, 7-ry, col) sense.set_pixel(rx, 7-ry, col) pixels=sense.get_pixels() new_pixels=[] for p in pixels: new_pixels.append( fade( p ) ) sense.set_pixels( new_pixels ) #sleep(0.1)
mc.postToChat("Gold") P = [255, 0, 255] R = [255, 0, 0] B = [0, 0, 255] O = [255, 165, 0] G = [0, 255, 0] goldDesign =[P, O, O, O, O, O, O, P, O, B, R, R, R, R, B, O, O, G, B, R, R, B, G, O, O, G, G, B, B, G, G, O, O, G, G, B, B, G, G, O, O, G, B, R, R, B, G, O, O, B, R, R, R, R, B, O, P, O, O, O, O, O, O, P ] sense.set_pixels(goldDesign) if block == diamond: mc.postToChat("Diamond") R = [255, 0, 0] G = [0, 255, 0] B = [0, 0, 255] O = [255,165, 0] P = [255, 0, 255] diamondDesign = [G, G, G, G, G, G, G, G, G, R, R, R, R, R, R, G, G, R, B, B, B, B, R, G, G, R, B, O, P, B, R, G, G, R, B, P, O, B, R, G, G, R, B, B, B, B, R, G,
happy = [ y, y, y, y, y, y, y, y, y, y, e, y, y, e, y, y, y, e, y, e, e, y, e, y, y, y, y, y, y, y, y, y, y, w, w, w, w, w, w, y, y, e, e, e, e, e, e, y, y, y, e, v, v, e, y, y, y, y, y, y, y, y, y, y ] oh = [ y, y, y, y, y, y, y, y, y, w, w, y, y, w, w, y, y, w, e, y, y, e, w, y, y, w, w, y, y, w, w, y, y, y, y, y, y, y, y, y, y, y, y, e, e, y, y, y, y, y, y, e, e, y, y, y, y, y, y, y, y, y, y, y ] x, y, z = sense.get_accelerometer_raw().values() sense.set_pixels(happy) time.sleep(1) sense.set_pixels(wink) time.sleep(0.5) sense.set_pixels(smile) while True: shake = 1 x, y, z = sense.get_accelerometer_raw().values() if x > shake or y > shake or z > shake: sense.set_pixels(oh) time.sleep(3) print str(x) + " X " print str(y) + " Y " print str(z) + " Z "
day = dt.date.today().day O = (0,0,0) cal = [ 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, 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 ] def day2led(day): if day % 2 == 1: ledPair = (day, day -1) else: ledPair = (day, day + 1) return ledPair for d in range(2*day): p = day2led(d) print(p) r = random.randint(50,255) g = random.randint(50,255) b = random.randint(50,255) cal[p[0]] = (r,g,b) cal[p[1]] = (r,g,b) sh.set_pixels(cal)
a, a, a, a, w, w, w, w, w, w, w, w, w, ] sense.set_pixels(MAPA) x = [1, 2, 3, 4, 5, 6] y = [1, 2, 3, 4, 5, 6] r = random.choice(x[0:6]) z = random.choice(y[0:6]) co = [ 9, 10, 11, 12, 13, 14, 17, 18, 19, 20, 21, 22, 25, 26, 27, 28, 29, 30, 33, 34, 35, 36, 37, 38, 41, 42, 43, 44, 45, 46, 49, 50, 51, 52, 53, 54 ] def sujar(): while True: ca = random.choice(co)
from sense_hat import SenseHat import random import time s = SenseHat() i = 0 while True: n = i % 255 print(n) screen = [(n,n,n)] * 8\ + [(n,0,0)] * 8 \ + [(0,n,0)] * 8 \ + [(0,0,n)] * 8 \ + [(n,n,0)] * 8 \ + [(n,0,n)] * 8 \ + [(0,n,n)] * 8 \ + [(n//2,n//2,n//2)] * 8 s.set_pixels(screen) i += 1 time.sleep(.01)
if (igetb < 0): igetb = 0 print("Inverted text colour: ") print(igetr, igetg, igetb) farge = (getr, getg, getb) fargelist = [] # print(type(fargelist)) while len(fargelist) < 64: fargelist.append(farge) # print(fargelist) sense.set_pixels(fargelist) # Vi burde skrive tallet også fra "var tall". Bruker show_message i første omgang # sense.show_message("Min "+str(min),0.050,back_colour=fargelist[0],text_colour=(igetr,igetg,igetb)) sense.show_message(str(tall), 0.120, back_colour=fargelist[0], text_colour=(igetr, igetg, igetb)) time.sleep(1.1) sense.show_message(str(tall), 0.060, back_colour=fargelist[0], text_colour=(igetr, igetg, igetb))
from gpiozero import MotionSensor import time import led_images import camera sense = SenseHat() mot = MotionSensor(4) sense.set_rotation(180) time_since_pic = 0 pic_interval = 10 pic_count = 0 while True: if mot.motion_detected: # Yes motion sense.set_pixels(led_images.green_dot) # Take a pic every x seconds if time_since_pic == 0 or time_since_pic >= pic_interval: imagepath = 'public/photo' + str(pic_count) + '.jpg' pic_count += 1 sense.set_pixels(led_images.flash) camera.take_photo(imagepath) sense.set_pixels(led_images.green_dot) # Reset counter time_since_pic = 0 else: # No motion sense.set_pixels(led_images.red_dot) time_since_pic = pic_interval
while True: acc = sense.get_accelerometer_raw() x = acc['x'] y = acc['y'] z = acc['z'] x=round(x, 1) y=round(y, 1) z=round(z, 1) #up = what_is_up(x, y, z) if x > THRESHOLD or x < -THRESHOLD: #up == X_AXIS: if x > 0: DOT_POSITION = get_new_dot_position(DOT_POSITION, DOWN) else: DOT_POSITION = get_new_dot_position(DOT_POSITION, UP) if y > THRESHOLD or y < THRESHOLD: #up == Y_AXIS: if y > 0: DOT_POSITION = get_new_dot_position(DOT_POSITION, LEFT) else: DOT_POSITION = get_new_dot_position(DOT_POSITION, RIGHT) if DOT_POSITION not in PAINTED_PIXELS: PAINTED_PIXELS.append(copy(DOT_POSITION)) grid = get_grid(DOT_POSITION, PAINTED_PIXELS) sense.set_pixels(grid) sleep(0.1)
print 'Could not detect single face! Check the image in capture.pgm' \ ' to see what was captured and try again with only one face visible.' continue x, y, w, h = result # Crop and resize image to face. crop = face.resize(face.crop(image, x, y, w, h)) found = False for user, model in models: label, confidence = model.predict(crop) print 'Predicted {0} face with confidence {1} (lower is more confident).'.format( 'POSITIVE' if label == config.POSITIVE_LABEL else 'NEGATIVE', confidence), 'for user', user if label == config.POSITIVE_LABEL and confidence < config.POSITIVE_THRESHOLD: print 'Recognized face! Hello', user found = True sense.set_pixels(tick) time.sleep(3) sense.show_message("Hi "+user+"!") sense.clear() break if not found: print 'Did not recognize face' sense.set_pixels(cross) time.sleep(3) sense.clear() print "Capture another face to test"
from sense_hat import SenseHat import time from PIL import Image import os # Open image file image_file = os.path.join(os.sep,"/home","pi","Downloads","download.png") img = Image.open(image_file) # Generate rgb values for image pixels rgb_img = img.convert('RGB') image_pixels = list(rgb_img.getdata()) # Get the 64 pixels you need pixel_width = 6 image_width = pixel_width*8 sense_pixels = [] start_pixel = 0 while start_pixel < (image_width*64): sense_pixels.extend(image_pixels[start_pixel:(start_pixel+image_width):pixel_width]) start_pixel += (image_width*pixel_width) # Display the image sense = SenseHat() sense.set_rotation(r=180) print(sense_pixels) sense.set_pixels(sense_pixels) time.sleep (3) sense.clear()
#! /usr/bin/python from sense_hat import SenseHat import time sense = SenseHat() X = [65, 105, 225] # Royal Blue O = [0, 0, 0] # Black question_mark = [ X, X, O, O, O, O, X, X, X, X, O, X, X, O, X, X, X, X, O, X, X, O, X, X, X, X, X, X, X, X, X, X, X, X, O, X, X, O, X, X, X, X, O, X, X, O, X, X, X, X, O, O, O, O, X, X, O, O, O, O, O, O, O, O ] sense.set_pixels(question_mark) time.sleep(5) sense.clear()
for i in range(7): row[i] = row[i + 1] row[-1] = blue return matrix def draw_astronaut(event): global y global x sense.set_pixel(x, y, blue) if event.action == "pressed": if event.direction == "up" and y > 0: y -= 1 elif event.direction == "down" and y < 7: y += 1 elif event.direction == "right" and x < 7: x += 1 elif event.direction == "left" and x > 0: x -= 1 sense.set_pixel(x, y, yellow) sense.stick.direction_any = draw_astronaut while True: matrix = draw_matrix(matrix) for i in range(3): sense.set_pixels(flatten(matrix)) matrix = move_pipes(matrix) sleep(1)
from sense_hat import SenseHat import time sense = SenseHat() sense.set_rotation(180) var = 1 X = [0, 0, 200] # blue O = [255, 255, 255] # White mail = [ O, O, O, O, O, O, O, O, O, O, X, X, X, X, O, O, O, O, X, X, X, X, O, O, O, X, O, O, O, O, X, O, O, X, X, O, O, X, X, O, O, X, X, X, X, X, X, O, O, X, X, X, X, X, X, O, O, O, O, O, O, O, O, O ] sense.set_pixels(mail) #time.sleep(1)
from sense_hat import SenseHat sense = SenseHat() r = (255, 0, 0) # red o = (255, 128, 0) # orange y = (255, 255, 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 heart = [ k, r, r, k, k, r, r, k, r, r, r, r, r, r, r, r, r, r, r, r, r, r, r, r, r, r, r, r, r, r, r, r, r, r, r, r, r, r, r, r, k, r, r, r, r, r, r, k, k, k, r, r, r, r, k, k, k, k, k, r, r, k, k, k ] sense.set_pixels(heart)
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)
#sense.stick.wait_for_event() explode = False initTime = time.time() deltaTime = 0 deltaTime_prev = -1 while not explode: deltaTime = time.time() - initTime deltaTime = round(deltaTime, 2) if not deltaTime_prev == deltaTime: deltaTime_prev = deltaTime if timer != 0: angle = 2 * np.pi * float(deltaTime) / timer + np.pi * int( np.pi) / 2 #https://xkcd.com/1275 image = getLineImage(4, -angle, 4, [255, 0, 0]) try: sense.set_pixels(image) except: print("error") pass if deltaTime >= timer: explode = True print("BOOOM!") path = "./img/explosion/explosion" for frame in range(12): sense.load_image(path + str(frame) + ".jpg") time.sleep(0.1) sense.clear()