def generate_chart(data, color, ripple, orientation, lowlight): info_chart = [] domain_min = data[0][0] domain_max = data[0][0] ad_min = data[0][1] ad_max = data[0][1] #calculate minimum, maximum, and interval values to scale graph appropriately for hour in data: if hour[0] > domain_max: domain_max = hour[0] elif hour[0] < domain_min: domain_min = hour[0] if hour[1] > ad_max: ad_max = hour[1] elif hour[1] < ad_min: ad_min = hour[1] domain_interval = (domain_max - domain_min) / 8 ad_interval = (ad_max - ad_min) / 8 #append scaled values to new list for hour in data: info_chart.append([int((hour[0] - domain_min) / domain_interval) if domain_interval > 0 \ else 0, int((hour[1] - ad_min) / ad_interval) if ad_interval > 0 else 0]) info_chart = list(reversed(info_chart[:8])) sense = SenseHat() sense.clear() sense.set_rotation(orientation) if lowlight: sense.low_light = True else: sense.low_light = False #set pixel values on rgb display for row in range(0, 8): if info_chart[row][0] > 0: for col in range(0, info_chart[row][0]): #if color not set, default to red for all values if color == 'traffic': sense.set_pixel(row, 7 - col, color_dict(info_chart[row][0])) if ripple: time.sleep(0.01) elif color == 'ads': sense.set_pixel(row, 7 - col, color_dict(info_chart[row][1])) if ripple: time.sleep(0.01) else: sense.set_pixel(row, 7 - col, (255, 0, 0)) if ripple: time.sleep(0.01)
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 display_sense(): if request.method == 'POST': global running global nameList global localList if running == "no": name = request.form['name'] show = request.form['show'] sense = SenseHat() sense.set_rotation(180) sense.low_light = True running = "yes" sense.show_message(show) nameList.append(" " + name) localList.append(" " + show) running = "no" conn = sqlite3.connect('./static/data/senseDisplay.db') curs = conn.cursor() curs.execute( "INSERT INTO messages (name, message) VALUES((?),(?))", (name, show)) conn.commit() conn.close() return render_template("index.html", names=nameList, msgs=localList)
def main(): #initialize Pygame which handles joystick inputs on SenseHat pygame.init() pygame.display.set_mode((640, 480)) subprocess.call(["mpc","clear"]) subprocess.call(["mpc","load","playlist1"]) subprocess.call(["mpc","enable","1"]) # SenseHat initialization and configuration sense = SenseHat() sense.low_light = True sense.rotation = 90 #initialize last weather update time last_update_time = 0 #Main loop while True: #Handle Senshat Joystick inputs for event in pygame.event.get(): #if event.type == KEYDOWN: #radio_commands(event) #print('DN') if event.type == KEYUP: radio_commands(event) print('SenseHat Input')
def init_sense(): """ Initialize the sense hat """ sense = SenseHat() sense.clear() sense.low_light = True # This thing is very, very bright return sense
def init_sense_hat(): logger.info("Initializing Raspberry Pi SenseHat...") sense = SenseHat() sense.clear() sense.low_light = False sense.set_rotation(0) sense.set_pixels(get_pi_logo()) return sense
def display_all(): global running global localList if running == "no": sense = SenseHat() sense.set_rotation(180) sense.low_light = True running = "yes" sense.show_message("".join(localList)) running = "no" return render_template("index.html")
def main(): # Parse args parser = argparse.ArgumentParser() parser.add_argument('-s', '--single', help='Changes the execution mode to a single run.', action='store_true') parser.add_argument('-i', '--interval', help='Interval for measurements in seconds.', type=int) parser.add_argument('-m', '--max', help='Maximum number of iterations.', type=int) args = parser.parse_args() interval = 600 # 10 min max_iterations = 0 # override interval if args.interval and args.interval > 0: interval = args.interval # override default max value if args.max and args.max > 0: max_iterations = args.max #return sense = SenseHat() sense.low_light = True if args.single: print('Running a single measurement.') measure(sense) elif max_iterations == 0: print('No max iterations was chosen - runing in infinite loop.') i = 0 while True: indicate_measurement(sense, i) i += 1 measure(sense) time.sleep(interval) else: print('Max iterations was chosen - runing a limited number of iterations.') for i in range(0, max_iterations): indicate_measurement(sense, i) print('Measurement {} of {}. {} left.'.format(i + 1, max_iterations, max_iterations - i - 1)) measure(sense) time.sleep(interval) exit_pi(sense)
def main(): if len(sys.argv) > 1: if sys.argv[1] == 'test': test() else: try: print(SayTime(*(sys.argv[1].split(':'))).words()) except TypeError: print('Invalid time ({})'.format(sys.argv[1])) else: sense = SenseHat() sense.low_light = True sense.set_rotation(180) sense.show_message(SayTime_t().words(), scroll_speed=0.1, text_colour=(50, 0, 50))
def mostra_avanzamento(percentuale): s = SenseHat() s.low_light = True avanzamento = [] accesi = int(percentuale * 64) spenti = 64 - accesi for i in range(accesi): avanzamento.append(b) for i in range(spenti): avanzamento.append(n) s.set_pixels(avanzamento) sleep(0.3)
def start_climate_station(self, interval=60, nightly=False, rotation=0): """ :param interval: refresh rate of checking temperature :param nightly: dim the light if value is true :param rotation: rotate the Sense Hat LED to fit proper direction :return: no return value. Start the climate station in daemon mode. """ sense = SenseHat() # sense.clear() sense.rotation = rotation sense.low_light = nightly while True: self.clear_temp_row(sense) self.display_temp(sense) sleep(interval)
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 display_sense(): if request.method == 'POST': global running global localList if running == "no": show = request.form['show'] sense = SenseHat() sense.set_rotation(180) sense.low_light = True running = "yes" sense.show_message(show) localList.append(" " + show) running = "no" return render_template("index.html")
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 main(): from sense_hat import SenseHat sense = SenseHat() sense.clear() sense.low_light = True sense.set_imu_config(True, True, True) sensor_start = sense.get_accelerometer() sensor_sensitivity = .0001 move_list = [] ex_coll = get_db('zs5_mongo', 'sensor')['freezer'] while True: sensor_in = sense.get_accelerometer() move_size = (sensor_in['roll'] - sensor_start['roll'])**2 + ( sensor_in['pitch'] - sensor_start['pitch'])**2 + ( sensor_in['yaw'] - sensor_start['yaw'])**2 sensor_start = sensor_in if move_size >= sensor_sensitivity: sense.show_letter('M') move_dict = {'move_ts': datetime.utcnow().timestamp(), **sensor_in} ex_coll.insert_one(move_dict) time.sleep(.2) sense.clear()
def get_side_mapping(): global project_mapping sideMappingJson = {} try: sideMappingJson = requests.get(hickery_api_url).json() except requests.ConnectionError as e: sense = SenseHat() sense.low_light = True sense.clear([255, 0, 0]) sleep(.5) sense.clear() print("An exception has occurred - {}".format(e)) for sideMappingJson in sideMappingJson['sideMappings']: if (sideMappingJson['sideNumber'] == 1): project_mapping[0] = sideMappingJson['harvestTask'] elif (sideMappingJson['sideNumber'] == 2): project_mapping[90] = sideMappingJson['harvestTask'] elif (sideMappingJson['sideNumber'] == 3): project_mapping[180] = sideMappingJson['harvestTask'] elif (sideMappingJson['sideNumber'] == 4): project_mapping[270] = sideMappingJson['harvestTask'] return project_mapping
def temp_record_deamon(): """loops the hat""" sense = SenseHat() sense.low_light = True c_hist = [] while True: sense.clear() draw_temp_scale_in_col(0, sense) current_temp = round(sense.get_temperature(), 1) stat_record = Stats(temp=current_temp) db.session.add(stat_record) db.session.commit() print(current_temp) c_hist.append(current_temp) if len(c_hist) > 7: c_hist.pop(0) for i in range(min(len(c_hist), 7)): current_c_hist = c_hist[-(i + 1)] draw_temp_in_col(i + 1, current_c_hist, sense) sleep(10)
def ticker(): delta_t = time.time() - tick_launch ticker_x = f'{delta_t:.3f}:' debug_time = time.localtime(time.time()) ticker_x = str(ticker_x) + (" ") + str(time.asctime()) + (" ") return ticker_x sleeptime_l = 1.0 sleeptime_m = sleeptime_l / 2 sleeptime_s = sleeptime_l / 4 sleeptime_watchtick = 1 s = SenseHat() s.low_light = False s.rotation = 90 nightmode = False nightmodehours = [0, 1, 2, 3, 4, 5, 7, 9, 11, 13, 15, 17, 19, 21, 22, 23, 24] G = green = [0, 255, 0] g = green_low = [0, 100, 0] Y = yellow = [255, 255, 0] y = yellow_low = [100, 100, 0] B = blue = [0, 0, 255] b = blue_low = [0, 0, 100] R = red = [255, 0, 0] r = red_low = [100, 0, 0] W = white = [255, 255, 255] w = white_low = [100, 100, 100]
from sense_hat import SenseHat import random import time s = SenseHat() screen = [] for i in range(64): n = i * 4 screen.append((n,n,n)) while True: s.set_pixels(screen) s.low_light = not s.low_light time.sleep(1)
def main(): #parameters last_update_time = 0 #Initialize Sense Hat sense = SenseHat() sense.low_light = True sense.rotation = 90 #Initialize Google Calendar credentials = get_credentials() http = credentials.authorize(httplib2.Http()) service = discovery.build('calendar', 'v3', http=http) # Main Loop while True: # Fetch weather & calendar data every update period if time.time()-last_update_time > update_period*60: Weather = get_weather(url) last_update_time = time.time() Baro = get_press(AltitudeAboveSeaLevel) Humidity = sense.get_humidity() print('Current, Max, Min temp:',Weather.CurrentTemp,Weather.ForecastMaxTemp,Weather.ForecastMinTemp) print('Weather info updated at:', strftime("%a, %d %b %Y %H:%M:%S", localtime())) print('Local Pressure',Baro) now = datetime.datetime.utcnow().isoformat() + 'Z' # 'Z' indicates UTC time print('Getting the upcoming 10 events') eventsResult = service.events().list( calendarId='primary', timeMin='2011-06-03T10:00:00-07:00', maxResults=2, singleEvents=True, orderBy='startTime').execute() events = eventsResult.get('items', []) print(events) if not events: print('No upcoming events found.') for event in events: start = event['start'].get('dateTime', event['start'].get('date')) print(start, event['summary']) # Fetch Calendar data # display Weather info on SenseHat for event in events: eventtime=dateutil.parser.parse(event['start'].get('dateTime')) print(eventtime.strftime('%I:%M')) sense.show_message(eventtime.strftime('%I:%M')) sense.show_message(event['summary']) # if ShowTemperature: # sense.show_message('{} {}{}'.format('T:', str(Weather.CurrentTemp),' '), text_colour=Weather.CurrentColor,scroll_speed=0.15) # sense.show_message('{} {}'.format('Max:', str(Weather.ForecastMaxTemp)), text_colour=Weather.MaxColor,scroll_speed=0.15) # sense.show_message('{} {}'.format('Min:', str(Weather.ForecastMinTemp)), text_colour=Weather.MinColor,scroll_speed=0.15) # if ShowTime: # sense.show_message('{} {}'.format('Heure:',strftime("%H:%M",localtime()))) # if ShowWeatherPicto: # if Weather.Picto > 0: # sense.load_image("Soleil.png") # time.sleep(3) # if ShowPressure: # sense.show_message('{} {}'.format(format(Baro, '.1f'),'hPa'), text_colour=Weather.CurrentColor,scroll_speed=0.15) # #print(format(Baro, '.1f'),'hPa') # if ShowHumidity: # sense.show_message('{} {} {}'.format(format(Humidity, '.1f'),'%','Hum.'), text_colour=Weather.CurrentColor,scroll_speed=0.15) # #print(format(Humidity, '.1f'),'%','Hum.') time.sleep(1)
for i in (6, 7): for j in (3, 4): self.__sense.set_pixel (i, j, self.__red) pass pass def __down (self): # display green square at bottom for i in (3, 4): for j in (6, 7): self.__sense.set_pixel (i, j, self.__green) pass pass pass if __name__ == '__main__': from argparse import ArgumentParser as AP from sense_hat import SenseHat p = AP (description='activate RepeatMe') p.add_argument ('--makey', action='store_true', default=False, help='use keyboard (e.g. Makey Makey) as input') p.add_argument ('--dim', action='store_true', default=False, help='force LED matrix dim') args = p.parse_args () sense = SenseHat () sense.clear () sense.low_light = args.dim r = RepeatMe (sense, 0.5, args.makey) pass
from sense_hat import SenseHat # importing Sense Hat library from time import sleep #Importing time library and method sleep sense = SenseHat() # setting up sensehat sense.low_light = True # setting the led light to low r = (255, 0, 0) w = (255, 255, 255) g = (0, 255, 0) door11 = [ w, w, r, w, w, w, r, w, w, r, r, w, w, r, r, w, w, w, r, w, w,
wind_speed = 0.0 sunrise = datetime.now() sunset = datetime.now() temp_interior = 0.0 temp_interior_alt = 0.0 pressure_interior = 0.0 humidity_interior = 0.0 # initialisiere Flask server app = Flask(__name__) # initialisiere SenseHat-Erweiterung sense = SenseHat() sense.low_light = True def get_location(): """Ermittelt die Stadt zur eigenen IP-Adresse.""" url = "https://ipinfo.io/" try: r = requests.get(url) except: print("error while querying info...") data = json.loads(r.text) return data['city'] def get_weather_for_city(city): """Fragt das aktuelle Wetter bei openweathermap.org ab und gibt Temperatur,
from sense_hat import SenseHat import time import random senseHat = SenseHat() senseHat.low_light = True GREEN = (0, 255, 0) RED = (255, 0, 0) START_DELAY = 3 MATRIX_MIN_VALUE = 0 MATRIX_MAX_VALUE = 7 MATRIX_SIZE = 8 while True: # variables: gameOverFlag = False growSnakeFlag = False generateRandomFoodFlag = False snakeMovementDelay = 0.5 snakeMovementDelayDecrease = -0.02 # start delay: time.sleep(START_DELAY) # set default snake starting position (values are chosen by preference): snakePosX = [3] snakePosY = [6] # generate random food position: while True:
pixelOffset = 0 index = 0 for indexLoop in range(0, 4): for counterLoop in range(0, 4): if (hour >= 10): clockImage[index] = number[int(hour/10)*16+pixelOffset] clockImage[index+4] = number[int(hour%10)*16+pixelOffset] clockImage[index+32] = number[int(minute/10)*16+pixelOffset] clockImage[index+36] = number[int(minute%10)*16+pixelOffset] pixelOffset = pixelOffset + 1 index = index + 1 index = index + 4 # Colour the hours and minutes for index in range(0, 64): if (clockImage[index]): if index < 32: clockImage[index] = hourColour else: clockImage[index] = minuteColour else: clockImage[index] = empty # Display the time sense.set_rotation(90) # Optional sense.low_light = True # Optional sense.set_pixels(clockImage)
print("[ledMatrixBridge] clear pixels") sense.clear() if key == "showMessage": if showDebug: print("[ledMatrixBridge] show message", payload['msg']) sense.show_message(payload["msg"], payload["speed"], payload["textColor"], payload["backgroundColor"]) if key == "showLetter": if showDebug: print("[ledMatrixBridge] show letter", payload['value']) sense.show_letter(payload["value"]) if key == "lowLight": if showDebug: print("[ledMatrixBridge] set low light", payload['value']) sense.low_light(bool(payload["value"])) if key == "gamma": if showDebug: print("[ledMatrixBridge] set gamma", payload['value']) sense.low_light(int(payload["value"])) if key == "gamma": if showDebug: print("[ledMatrixBridge] reset gamma") sense.gamma_reset()
def rainbow_hearts(): import requests from os import system url = "http://3.140.244.63:8081/check" # "http://192.168.0.190:8081/check" path = "/home/pi/Desktop/personal-projects" from sense_hat import SenseHat import time sense = SenseHat() sense.low_light = True # Create variables to hold each RGB color we want to use # red r = (255, 0, 0) # pink p = (204, 0, 204) # orange o = (255, 128, 0) # yellow y = (255, 255, 0) # green g = (0, 255, 0) # aqua a = (0, 255, 255) # blue b = (0, 0, 255) # purple pr = (128, 0, 255) # empty (no color) e = (0, 0, 0) red_heart = [ e, e, e, e, e, e, e, e, e, r, r, e, r, r, e, e, r, r, r, r, r, r, r, e, r, r, r, r, r, r, r, e, r, r, r, r, r, r, r, e, e, r, r, r, r, r, e, e, e, e, r, r, r, e, e, e, e, e, e, r, e, e, e, e ] pink_heart = [ e, e, e, e, e, e, e, e, e, p, p, e, p, p, e, e, p, p, p, p, p, p, p, e, p, p, p, p, p, p, p, e, p, p, p, p, p, p, p, e, e, p, p, p, p, p, e, e, e, e, p, p, p, e, e, e, e, e, e, p, e, e, e, e ] orange_heart = [ e, e, e, e, e, e, e, e, e, o, o, e, o, o, e, e, o, o, o, o, o, o, o, e, o, o, o, o, o, o, o, e, o, o, o, o, o, o, o, e, e, o, o, o, o, o, e, e, e, e, o, o, o, e, e, e, e, e, e, o, e, e, e, e ] yellow_heart = [ e, e, e, e, e, e, e, e, e, y, y, e, y, y, e, e, y, y, y, y, y, y, y, e, y, y, y, y, y, y, y, e, y, y, y, y, y, y, y, e, e, y, y, y, y, y, e, e, e, e, y, y, y, e, e, e, e, e, e, y, e, e, e, e ] green_heart = [ e, e, e, e, e, e, e, e, e, g, g, e, g, g, e, e, g, g, g, g, g, g, g, e, g, g, g, g, g, g, g, e, g, g, g, g, g, g, g, e, e, g, g, g, g, g, e, e, e, e, g, g, g, e, e, e, e, e, e, g, e, e, e, e ] aqua_heart = [ e, e, e, e, e, e, e, e, e, a, a, e, a, a, e, e, a, a, a, a, a, a, a, e, a, a, a, a, a, a, a, e, a, a, a, a, a, a, a, e, e, a, a, a, a, a, e, e, e, e, a, a, a, e, e, e, e, e, e, a, e, e, e, e ] blue_heart = [ e, e, e, e, e, e, e, e, e, b, b, e, b, b, e, e, b, b, b, b, b, b, b, e, b, b, b, b, b, b, b, e, b, b, b, b, b, b, b, e, e, b, b, b, b, b, e, e, e, e, b, b, b, e, e, e, e, e, e, b, e, e, e, e ] purple_heart = [ e, e, e, e, e, e, e, e, e, pr, pr, e, pr, pr, e, e, pr, pr, pr, pr, pr, pr, pr, e, pr, pr, pr, pr, pr, pr, pr, e, pr, pr, pr, pr, pr, pr, pr, e, e, pr, pr, pr, pr, pr, e, e, e, e, pr, pr, pr, e, e, e, e, e, e, pr, e, e, e, e ] heart_colors = [ red_heart, pink_heart, orange_heart, blue_heart, purple_heart, aqua_heart, green_heart, yellow_heart ] i = True sense.clear() count = 1 while i: for color in heart_colors: try: if requests.get(url).content == "1": sense.set_pixels(color) else: sense.clear() time.sleep(1) except: print "Could not connect" try: if (count % 120) == 0: system("git -C " + path + " pull") system("sudo systemctl daemon-reload") print "Successfully updated" count = 0 count += 1 except: print "Failed to update"
def intro_video(): s = SenseHat() s.low_light = True w = (255, 255, 255) # bianco / white n = (0, 0, 0) # nero / black r = (255, 0, 0) # rosso / red b = (0, 0, 255) # blu / blue v = (0, 153, 0) # verde / green # countdown + immagine razzo / countdown + rocket image p = [ r, r, r, n, n, b, n, n, n, n, r, n, n, w, n, n, r, r, r, n, w, b, w, n, n, n, r, n, w, w, w, n, r, r, r, n, w, w, w, n, n, n, n, n, w, w, w, n, n, n, n, n, w, w, w, n, n, n, n, w, b, b, b, w ] s.set_pixels(p) sleep(1) s.set_pixel(2, 3, n) s.set_pixel(0, 3, r) sleep(1) for y in range(0, 5): s.set_pixel(0, y, n) s.set_pixel(1, y, r) s.set_pixel(2, y, n) sleep(1) # immagine razzo / rocket image p = [ n, n, n, n, n, w, n, n, n, n, n, n, w, b, w, n, n, n, n, n, w, w, w, n, n, n, n, n, w, w, w, n, n, n, n, n, w, w, w, n, n, n, n, n, w, w, w, n, n, n, n, w, b, b, b, w, n, n, n, r, r, n, r, r ] s.set_pixels(p) # IT: animazione razzo: sposta una riga in alto e aggiunge riga nera in fondo # EN: rocket animation: move one row to the top and add a blank line at the bottom for u in range(0, 7): sleep(0.2) p2 = p for q in range(8, 64): p2[q - 8] = p[q] for q in range(0, 8): p2[q + 56] = n s.set_pixels(p2) # bandiera ITA / ITA flag sleep(0.2) p = [ v, v, v, w, w, r, r, r, v, v, v, w, w, r, r, r, v, v, v, w, w, r, r, r, v, v, v, w, w, r, r, r, v, v, v, w, w, r, r, r, v, v, v, w, w, r, r, r, v, v, v, w, w, r, r, r, v, v, v, w, w, r, r, r, ] s.set_pixels(p) # messaggio di presentazione / presentation message sleep(1) s.show_message("Lamponi Team (ITALIA)", scroll_speed=0.04)
#!/usr/bin/python import sys import math import colorsys from random import randint import time from sys import exit import pygame from sense_hat import SenseHat sense = SenseHat() sense.low_light = False # Makes sure the SenseHat isn't in low light mode. This screws with the RGB values. sense.clear() # Clear the SenseHat screen ''' ----------------------------- Spirit Level for Raspberry Pi For use with the Sense Hat And using the pygame library. Remember to run with sudo: "sudo python3 spirit-level-plus.py" DISCLAIMER: I am not by any reach of the imagination a professional programmer. My code is very messy and there are very likely much better ways to do this. If you have any recommendations about how to clean up my code, or just any questions in general, feel free to reach out to me via my github account at https://github.com/dansushi/ Authored by Dan Schneider (2015), along with some helpful coding techniques borrowed from
while True: celcius = int(round(sense.get_temperature())) fahrenheit = int(round(1.8 * celcius + 32)) # 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)
from sense_hat import SenseHat import time s = SenseHat() s.low_light = True blue = (0, 0, 255) nothing = (0, 0, 0) def showW(): B = blue O = nothing logo = [ O, B, O, O, O, B, O, O, O, B, O, O, O, B, O, O, O,
from sense_hat import SenseHat import time s = SenseHat() s.low_light = True green = (0, 255, 0) yellow = (255, 255, 0) blue = (0, 0, 255) red = (255, 0, 0) white = (255,255,255) nothing = (0,0,0) pink = (255,105, 180) def trinket_logo(): G = green Y = yellow B = blue O = nothing logo = [ O, O, O, O, O, O, O, O, O, Y, Y, Y, B, G, O, O, Y, Y, Y, Y, Y, B, G, O, Y, Y, Y, Y, Y, B, G, O, Y, Y, Y, Y, Y, B, G, O, Y, Y, Y, Y, Y, B, G, O, O, Y, Y, Y, B, G, O, O, O, O, O, O, O, O, O, O, ] return logo
# python\sens_pacman.py from espeak import espeak from sense_hat import SenseHat import sens_defn import curses import time ## definitions sensehat = SenseHat() sensehat.low_light = True sensehat.set_rotation(180) stdscr = curses.initscr() curses.noecho() curses.cbreak() stdscr.keypad(True) msg = "GO!" px = 4 py = 4 qx = 2 qy = 2 ## beg sensehat.show_message(msg, text_colour=sens_defn.G) sensehat.set_pixel(qx, qy, 255, 0, 0) sensehat.set_pixel(px, py, 255, 255, 0) ## exec while True:
def main(): sense = SenseHat() sense.low_light = True last_update_time = 0 sense.rotation = 90 SunPictos = [1, 2, 3, 4, 5, 6, 13, 14, 15] SunCloudPictos = [7, 8, 9, 10, 11, 12, 31, 32] CloudPictos = [16, 17, 18, 19, 20, 21, 22, 23] RainPictos = [23, 25, 33, 35] SnowPictos = [24, 26, 29, 34] StormPictos = [27, 28, 30] while True: # Fetch weather data every update period if time.time() - last_update_time > update_period * 60: Weather = get_weather(url) last_update_time = time.time() Baro = get_press(AltitudeAboveSeaLevel) Humidity = sense.get_humidity() print('Current, Max, Min temp, Picto:', Weather.CurrentTemp, Weather.ForecastMaxTemp, Weather.ForecastMinTemp, Weather.Picto) print('Weather info updated at:', strftime("%a, %d %b %Y %H:%M:%S", localtime())) print('Local Pressure', Baro) # display Time & Weather info on SenseHat if ShowTime: sense.show_message('{} {}'.format('Heure:', strftime("%H:%M", localtime())), text_colour=(180, 180, 180)) if ShowTemperature: sense.show_message('{} {}{}'.format('T:', str(Weather.CurrentTemp), ' '), text_colour=Weather.CurrentColor, scroll_speed=0.15) sense.show_message('{} {}'.format('Max:', str(Weather.ForecastMaxTemp)), text_colour=Weather.MaxColor, scroll_speed=0.15) sense.show_message('{} {}'.format('Min:', str(Weather.ForecastMinTemp)), text_colour=Weather.MinColor, scroll_speed=0.15) if ShowWeatherPicto: if Weather.Picto in SunPictos: for i in range(0, 10): sense.load_image( "/home/pi/SenseHat/WeatherMonitor/Images/soleil.png") time.sleep(0.3) sense.load_image( "/home/pi/SenseHat/WeatherMonitor/Images/soleil2.png") time.sleep(0.3) elif Weather.Picto in SunCloudPictos: sense.load_image( "/home/pi/SenseHat/WeatherMonitor/Images/soleil&nuage.png") time.sleep(5) elif Weather.Picto in CloudPictos: sense.load_image( "/home/pi/SenseHat/WeatherMonitor/Images/nuage.png") time.sleep(5) elif Weather.Picto in RainPictos: sense.load_image( "/home/pi/SenseHat/WeatherMonitor/Images/nuage&pluie.png") time.sleep(5) elif Weather.Picto in SnowPictos: sense.load_image( "/home/pi/SenseHat/WeatherMonitor/Images/nuage&neige.png") time.sleep(5) elif Weather.Picto in StormPictos: sense.load_image( "/home/pi/SenseHat/WeatherMonitor/Images/nuages&eclairs.png" ) time.sleep(5) if ShowPressure: sense.show_message('{} {}'.format(format(Baro, '.1f'), 'hPa'), text_colour=Weather.CurrentColor, scroll_speed=0.15) #print(format(Baro, '.1f'),'hPa') if ShowHumidity: sense.show_message('{} {} {}'.format(format(Humidity, '.1f'), '%', 'Hum.'), text_colour=Weather.CurrentColor, scroll_speed=0.15) #print(format(Humidity, '.1f'),'%','Hum.') time.sleep(1)
print("Time out of range, setting to default.") t = [23, 8] break else: t = [23, 8] rotation = 0 #Setup the rotation if it was provided if args.rotation: rotation = int(((round(args.rotation[0] / 90, 0) % 4) * 90)) sense = SenseHat() #Set the LED matrix to bright if the argument was provided if args.bright: sense.low_light = False else: sense.low_light = True groupings = generateNumberGroupings(numbers, 2, (5, 8), (5, 4)) now = datetime.now() target = datetime.now() #[time, [avgT, minT, maxT], [avgP, minP, maxP], [avgH, minH, maxH]] metric = [0, [[20, 0, 0], [1000, 0, 0], [50, 0, 0]]] while True: data = [] #From t 0 to 59 for i in range(60): start = datetime.now()
from sense_hat import SenseHat sense = SenseHat() sense.load_image("/home/pi/testit1/CoffeeCup.gif") sense.low_light = False
def main(): sense = SenseHat() sense.low_light = True last_update_time = 0 sense.rotation = 90 SunPictos = [1,2,3,4,5,6,13,14,15] SunCloudPictos = [7,8,9,10,11,12,31,32] CloudPictos = [16,17,18,19,20,21,22,23] RainPictos = [23,25,33,35] SnowPictos = [24,26,29,34] StormPictos = [27,28,30] while True: # Fetch weather data every update period if time.time()-last_update_time > update_period*60: Weather = get_weather(url) last_update_time = time.time() Baro = get_press(AltitudeAboveSeaLevel) Humidity = sense.get_humidity() print('Current, Max, Min temp, Picto:',Weather.CurrentTemp,Weather.ForecastMaxTemp,Weather.ForecastMinTemp,Weather.Picto) print('Weather info updated at:', strftime("%a, %d %b %Y %H:%M:%S", localtime())) print('Local Pressure',Baro) # display Time & Weather info on SenseHat if ShowTime: sense.show_message('{} {}'.format('Heure:',strftime("%H:%M",localtime())),text_colour=(180,180,180)) if ShowTemperature: sense.show_message('{} {}{}'.format('T:', str(Weather.CurrentTemp),' '), text_colour=Weather.CurrentColor,scroll_speed=0.15) sense.show_message('{} {}'.format('Max:', str(Weather.ForecastMaxTemp)), text_colour=Weather.MaxColor,scroll_speed=0.15) sense.show_message('{} {}'.format('Min:', str(Weather.ForecastMinTemp)), text_colour=Weather.MinColor,scroll_speed=0.15) if ShowWeatherPicto: if Weather.Picto in SunPictos: for i in range (0,10): sense.load_image("/home/pi/SenseHat/WeatherMonitor/Images/soleil.png") time.sleep(0.3) sense.load_image("/home/pi/SenseHat/WeatherMonitor/Images/soleil2.png") time.sleep(0.3) elif Weather.Picto in SunCloudPictos: sense.load_image("/home/pi/SenseHat/WeatherMonitor/Images/soleil&nuage.png") time.sleep(5) elif Weather.Picto in CloudPictos: sense.load_image("/home/pi/SenseHat/WeatherMonitor/Images/nuage.png") time.sleep(5) elif Weather.Picto in RainPictos: sense.load_image("/home/pi/SenseHat/WeatherMonitor/Images/nuage&pluie.png") time.sleep(5) elif Weather.Picto in SnowPictos: sense.load_image("/home/pi/SenseHat/WeatherMonitor/Images/nuage&neige.png") time.sleep(5) elif Weather.Picto in StormPictos: sense.load_image("/home/pi/SenseHat/WeatherMonitor/Images/nuages&eclairs.png") time.sleep(5) if ShowPressure: sense.show_message('{} {}'.format(format(Baro, '.1f'),'hPa'), text_colour=Weather.CurrentColor,scroll_speed=0.15) #print(format(Baro, '.1f'),'hPa') if ShowHumidity: sense.show_message('{} {} {}'.format(format(Humidity, '.1f'),'%','Hum.'), text_colour=Weather.CurrentColor,scroll_speed=0.15) #print(format(Humidity, '.1f'),'%','Hum.') time.sleep(1)
from sense_hat import SenseHat import time sense = SenseHat() sense.low_light = False starting_value = 50 color = [starting_value]*3 adding_value = (255 - starting_value) / 64 sense.clear() while True: for i in range(3): for y in range(8): for x in range(8): #sense.set_pixel(x, y, 255*y/7, 0, 255*x/7) color[i] = int(color[i] + adding_value) #color[1] = int(color[1] + multiplicator) #color[2] = int(color[2] + multiplicator) sense.set_pixel(x, y, color) print(y, x) time.sleep(0.1) color[i] = starting_value #sense.clear()
print("Time out of range, setting to default.") t = [23, 8] break else: t = [23, 8] rotation = 0 #Setup the rotation if it was provided if args.rotation: rotation = int(((round(args.rotation[0]/90, 0) % 4) * 90)) sense = SenseHat() #Set the LED matrix to bright if the argument was provided if args.bright: sense.low_light = False else: sense.low_light = True groupings = generateNumberGroupings(numbers, 2, (5, 8), (5, 4)) now = datetime.now() target = datetime.now() #[time, [avgT, minT, maxT], [avgP, minP, maxP], [avgH, minH, maxH]] metric = [0, [[20, 0, 0], [1000, 0, 0], [50, 0, 0]]] while True: data = [] #From t 0 to 59 for i in range(60): start = datetime.now()
# Main controller for Qiskit on Raspberry PI SenseHat. # Start by importing and simplifying required modules. from sense_hat import SenseHat hat = SenseHat() # Set default SenseHat configuration. hat.clear() hat.low_light = True # Background icon X = [255, 0, 255] # Magenta Y = [255, 192, 203] # Pink O = [0, 0, 0] # Black super_position = [ O, O, O, Y, X, O, O, O, O, O, Y, X, X, Y, O, O, O, Y, O, O, X, O, Y, O, O, Y, O, O, X, O, Y, O, O, Y, O, O, X, O, Y, O, O, Y, O, O, X, O, Y, O, O, O, Y, O, X, Y, O, O, O, O, O, X, X, X, O, O ] hat.set_pixels(super_position) # Understand which direction is down, and rotate the SenseHat display accordingly. def set_display(): acceleration = hat.get_accelerometer_raw() x = acceleration['x'] y = acceleration['y'] z = acceleration['z'] x = round(x, 0)
#!/usr/bin/python import sys import time import datetime import clock_digits from sense_hat import SenseHat sense = SenseHat() # create sense object sense.set_rotation(180) # better when USB cable sticks out the top sense.low_light = True # don't hurt my eyes sense.clear() # always start with a clean slate charWidth = 4 charHeight = 4 # returns the specified row of the digit def digitrow(digit, row): return digit[row * charWidth : (row * charWidth) + charWidth] # main display routine # takes a list of 4 digits and displays them on the LED-matrix def display(digits): if len(digits) > 4: return x = [0, 0, 0] # off screen = [ x, x, x, x, x, x, x, x, x, x, x, x, x, x, x, x, x, x, x, x, x, x, x, x,
r -= 1 if (g == 255 and b < 255 and r == 0): b += 1 if (b == 255 and g > 0 and r == 0): g -= 1 if (b == 255 and r < 255 and g == 0): r += 1 if (r == 255 and b > 0 and g == 0): b -= 1 pix[0] = r pix[1] = g pix[2] = b sense.low_light = True while (True): for pix in pixels: next_colour(pix) sense.set_pixels(pixels) #msleep(2) c = enterMod.getKey() if c == 1: sense.clear([0, 0, 0]) sys.exit()
def display_score(self): sense = SenseHat() sense.low_light = True sense.clear() sense.show_message('Score: ') sense.show_letter(str(self.player.score))