def show_temperature(delay): clear() temp = weather.temperature() write_string("%.2f" % temp + "c", kerning=False) show() time.sleep(delay) g.labels(host=host).set(temp)
def update_display(cost, trend): ''' Function to update the display ''' if (len(cost) > 1) and (len(cost) < 7): # Start with a clear buffer md.clear() # Right justify string char_offset = 6 - len(cost) md.write_string(cost, offset_x=(8 * char_offset), kerning=False) # Add trend - character set here: https://github.com/pimoroni/microdot-phat/blob/master/library/microdotphat/font.py if trend == 'UP': # Solid upwards triangle md.write_char(chr(9650), offset_x=0) elif trend == 'up': # Open upwards triangle md.write_char(chr(9651), offset_x=0) elif trend == 'down': # Open downwards triangle md.write_char(chr(9661), offset_x=0) elif trend == 'DOWN': # Solid downwards triangle md.write_char(chr(9660), offset_x=0) # Write the buffer to the display md.show()
def withPhat(): # global prevLevel #can remove next while True: tijd = time.localtime() #create a struct_time object if tijd[4] in interval_List: #and check if the number of minutes is in the interval_List currTime = time.asctime()[ 11:16] #if yes create an hour and minute string using .asctime currTime = currTime + ':00' #add the zeros getNap() #get and set current nap_list # walk through it searching match with currTime nap_list[i][1] # for i in nap_list: doesn't work in this case (because I need the index number?) for i in range(len(nap_list)): if nap_list[i][1] == currTime: currLevel = int(nap_list[i][5]) #currLevel is an int prevLevel = int(nap_list[i - 1][5]) diffLevel = currLevel - prevLevel #print(str('%+d' % diffLevel)) #+d formatting for pos and neg numbers print(currTime, str(currLevel), str('%+d' % diffLevel)) #prevLevel = currLevel # Microdot Phat code follows display = str(currLevel) + str('%+d' % diffLevel) microdotphat.clear() microdotphat.write_string(display, kerning=False) microdotphat.show() time.sleep(65) # waits a bit more than a minute time.sleep(5)
def display(): global roomTemp global systemTemp if ON_PI: write_string(str(systemTemp)[0:2] + " " + str(roomTemp)[0:2], kerning=False) show()
def feedme(feed): feed = feedparser.parse(feed.encode('utf-8')) for i in range(1): print(feed['entries'][i]['title']) write_string(feed['entries'][0]['title'], offset_x=1) scroll() show() time.sleep(0.05)
def write_to_display(message, brightness=1): if i2c_present: clear() set_brightness(brightness) write_string(message.rjust(6), kerning=False) show() else: print(message)
def DisplayTemp(NextDisplayTime, SensorVal, unitstr): TimeNow = time.time() if TimeNow > NextDisplayTime: NextDisplayTime = NextDisplayTime + DisplayInterval #print("Displaying Temperature on MicroDot Phat...") write_string("%.1f" % SensorVal + unitstr, kerning=False) show() return NextDisplayTime
def microdot(): clear() write_string( "%.1f" % temperature + "C", kerning=False) show() time.sleep(5) clear() write_string( "%.0f" % humidity + "% RH", kerning=False) show() time.sleep(5)
def logic(state, backend_change): if backend_change: print("BACKEND CHANGE") return None config = state["config"] # Update values state["driftPause"] = max(state["driftPause"] - 1.0 / CALLS_PER_SECOND, 0) if state["driftPause"] == 0: state["value"] += state["drift"] / CALLS_PER_SECOND / 60 state["rndMagnitude"] = state["rndMagnitude"] * config["rndMagnitudeDecay"] bnSpeed = config["brownNoiseSpeed"] bnValue = state["brownNoiseValue"] + random.uniform(-bnSpeed, bnSpeed) bnMax = config["brownNoiseMax"] state["brownNoiseValue"] = min(bnMax, max(-bnMax, bnValue)) state[ "sinePosition"] += 2 * math.pi / config["sineSpeed"] / CALLS_PER_SECOND if state["sinePosition"] > 2 * math.pi: state["sinePosition"] -= 2 * math.pi # Check whether we are adjusting the value adjustment = getAdjustment(config) if adjustment: state["value"] += adjustment state["driftPause"] = config["driftDelayAfterAdjust"] state["rndMagnitude"] = config["maxRndMagnitude"] state["drift"] = random.uniform(state["minDriftPerMinute"], state["maxDriftPerMinute"]) if random.random() < config["probDriftDown"]: state["drift"] = -state["drift"] # Limits if state["value"] < config.get("safeRangeMin", 0) / 2: state["value"] = config.get("safeRangeMin", 0) / 2 if state["value"] > config.get("safeRangeMax", 1000) * 2: state["value"] = config.get("safeRangeMax", 1000) * 2 # Print value sine = math.sin(state["sinePosition"]) * config["sineMagnitude"] #rnd = random.uniform(-state["rndMagnitude"], state["rndMagnitude"]) rnd = random.gauss(0, state["rndMagnitude"]) value = state["value"] + state["brownNoiseValue"] + rnd + sine state["displayValue"] = value # display actual brown sine white-mag #print("{:.1f}\t{:.2f}\t{:+.2f}\t{:+.2f}\t{:.2f}".format(value, state["value"], state["brownNoiseValue"], sine, state["rndMagnitude"])) microdotphat.write_string("{:.2f}".format(value), kerning=False) microdotphat.show() return state
def mostra_data(): tempo_data = 0 while tempo_data < tempo_switch: clear() t = datetime.datetime.now() if t.second % 2 == 0: set_decimal(3, 1) else: set_decimal(3, 0) write_string(t.strftime('%a %d').upper(), kerning=False) show() time.sleep(0.05) tempo_data = tempo_data + 1
def progression_worker(h): t_progress = 0 print "---> pyneurocl - starting progression_worker" while (t_progress < 100): time.sleep(1) t_progress = h.train_progress() if microdot: clear() write_string(str(t_progress) + "%") show() else: print "--->" + str(t_progress) + "%" return
def microdot(): clear() write_string("%.1f" % temperature + "C", kerning=False) show() time.sleep(5) # Uncomment to display pressure if needed #clear() #write_string( "%.0f" % pressure + "hPa", kerning=False) #show() #time.sleep(5) clear() write_string("%.0f" % humidity + "% RH", kerning=False) show() time.sleep(5)
def show_time(duration=10): repeat_in = 0.05 repeat_times = int(duration / repeat_in) for counter in range(0, repeat_times): microdotphat.clear() t = datetime.datetime.now() if t.second % 2 == 0: microdotphat.set_decimal(3, 1) else: microdotphat.set_decimal(3, 0) microdotphat.write_string(t.strftime(' %H%M'), kerning=False) microdotphat.show() time.sleep(repeat_in)
def readStream(): currentTitle = titleBus.get() url = "https://rc1.nobexinc.com//nowplaying.ashx?stationid=70642" response = urllib.urlopen(url) data = json.loads(response.read()) title = data['artist'] + ' - ' + data['songName'] if (title != currentTitle): write_string(" # " + title, kerning=False) titleBus.put(title) else: titleBus.put(currentTitle)
def clock(): while True: clockEndTime = time.time() + showClock while time.time() < clockEndTime: clear() t = datetime.datetime.now() if t.second % 2 == 0: set_decimal(2, 1) set_decimal(4, 1) else: set_decimal(2, 0) set_decimal(4, 0) write_string(t.strftime('%H%M%S'), kerning=False) show() time.sleep(0.05)
def mostra_saldo(): tempo_saldo = 0 saldo_euro = leggehttp() while tempo_saldo < tempo_switch: clear() char_euro() t = datetime.datetime.now() if t.second % 2 == 0: set_decimal(3, 1) else: set_decimal(3, 0) write_string(saldo_euro, offset_x=8, kerning=False) show() time.sleep(0.05) tempo_saldo = tempo_saldo + 1
def main(): """asdasd""" try: vala = int(sys.argv[1]) valb = int(sys.argv[2]) valc = int(sys.argv[3]) except: print("Exception reading input") counter = 1.0 soundon = is_sound_on() stride, Note_Freq = boop_beeps(vala, valb, valc) for val in range(vala, valb + stride, stride): sleep_time = min((counter / (abs(vala - valb) + 1.000))**1.8 * (10.0 / (abs(vala - valb) + 1.0)), 3.000) if soundon: try: # bus.read_byte(112) #check to see if rainbow hat is connected rainbowhat.buzzer.midi_note(Note_Freq, .05) except: pass try: if valc > 29: mystring = "0" + ( str(val).rjust(len(str(val)))[0:2 + len(str(val)) - 5] + str(val)[-3 + len(str(val).rjust(5)) - 5:]).rjust(5) rainbow_show_message('{:04.2f}'.format(val / 100)) rainbow_led_pricechange(valc - 100) #100 for curve currency microdotphat.set_decimal(1, 1) else: mystring = ( str(val).rjust(len(str(val)))[0:2 + len(str(val)) - 5] + "," + str(val)[-3 + len(str(val).rjust(5)) - 5:]).rjust(6) rainbow_show_message(str(val)) rainbow_led_pricechange(valc) microdotphat.write_string(mystring, offset_x=0, kerning=False) microdotphat.show() except: pass counter = counter + 1.0 sleep(sleep_time) sleep(.4) #needed so we can hear the last sound effect
def getNap(): global nap_list try: with requests.Session() as s: download = s.get(csv_url) decoded_content = download.content.decode('utf-8') cr = csv.reader(decoded_content.splitlines(), delimiter=';') nap_list = list(cr) return nap_list except IndexError: microdotphat.clear() microdotphat.write_string('IndEr1', kerning=False) microdotphat.show() print('IndexError 1: getNAP') except ConnectionError: microdotphat.clear() microdotphat.write_string('ConErr', kerning=False) microdotphat.show() print('ConnectionError: getNAP')
def render_string(s, scroll_x=8, scroll_y=0, scroll_sleep=1, kerning_flag=False): # init view clear() # render string write_string(s, kerning=kerning_flag) show() time.sleep(scroll_sleep) # render to end for i in range(len(s)): # scroll -> render scroll(scroll_x, scroll_y) show() time.sleep(scroll_sleep)
def print_string_fade(text): start = time.time() speed = 3 shown = True b = 0 while shown: b = (math.sin((time.time() - start) * speed) + 1) / 2 microdotphat.set_brightness(b) if b < 0.002 and shown: microdotphat.clear() microdotphat.write_string(text, kerning=False) microdotphat.show() shown = False if b > 0.998: shown = True time.sleep(0.01)
def __init__(self): write_string("start",kerning=False) time.sleep(1); threading.Thread.__init__(self) self.threadID = 'HVAC system' GPIO.setmode(GPIO.BCM) GPIO.setup(AC_PIN, GPIO.OUT) GPIO.setup(FAN_PIN, GPIO.OUT) GPIO.setup(HEAT_PIN, GPIO.OUT) self.sensor = MCP9808.MCP9808() self.sensor.begin() self.socket = ControlWebsocket.serverSocket() self.socket.daemon = True self.socket.start() #wait for 1 seconds for the service to configure time.sleep(1) self.init_values() self.roomTemp = self.sensor.readTempC() self.updateDisplay() self.wasConncetd = True
def mostra_orologio(): #verifico se c'e' connessione ad Internet connesso_internet = 0 connesso_internet = connessione() tempo_orologio = 0 while tempo_orologio < tempo_switch: clear() t = datetime.datetime.now() if t.second % 2 == 0: set_decimal(3, 1) else: set_decimal(3, 0) # se manca la connessione ad internet, durante la visualizzazione dell'ora viene anteposto un asterisco if (connesso_internet == 0): write_string(t.strftime(' %H%M'), kerning=False) else: write_string(t.strftime('*%H%M'), kerning=False) show() time.sleep(0.05) tempo_orologio = tempo_orologio + 1
async def initLogger(): print("Start logger...") await asyncio.sleep(1) while True: if len(cache) == 0: await asyncio.sleep(2) else: try: for key in cache: print(cache[key]) # Write to PHAT clear() write_string(cache[key], kerning=False) show() await asyncio.sleep(2) except Exception: pass
def job(): with urllib.request.urlopen( "https://api.nasa.gov/insight_weather/?api_key=YOUR-API-KEY-HERE&feedtype=json&ver=1.0" ) as url: data = json.loads(url.read()) days = list(data.keys()) res = [] for el in days: try: res.append(int(el)) except ValueError: pass print(res) for i in data[str(res[-1])].values(): mn = int((i["mn"])) mx = int(i["mx"]) break text = "The live temp on Mars on day " + str(res[-1]) + " is max: " + str( mx) + "c and min: " + str(mn) + "c " print(text) write_string(text, offset_x=0, kerning=False) show()
def withPhat(): while True: tijd = time.localtime() #create a struct_time object if tijd[4] in interval_List: #and check if the number of minutes is in the interval_List currTime = time.asctime()[ 11:16] #if yes create an hour and minute string using .asctime currTime = currTime + ':00' #add the zeros getNap() #get and set current nap_list # walk through it searching match with currTime nap_list[i][1] # for i in nap_list: doesn't work in this case (because I need the index number?) for i in range(len(nap_list)): try: if nap_list[i][1] == currTime: currLevel = int(nap_list[i][5]) #currLevel is an int prevLevel = int(nap_list[i - 1][5]) diffLevel = currLevel - prevLevel #print(str('%+d' % diffLevel)) #+d formatting for pos and neg numbers print(currTime, str(currLevel), str('%+d' % diffLevel)) # Microdot Phat code follows display = str(currLevel) + str('%+d' % diffLevel) microdotphat.clear() microdotphat.write_string(display, kerning=False) microdotphat.show() lookAhead(nap_list, currTime) #send nap_list to lookAhead except IndexError: microdotphat.clear() microdotphat.write_string('IndEr2', kerning=False) microdotphat.show() logging.info('IndexError 2 in withPhat') print('IndexError 2 in withPhat') time.sleep(65) #not sure how long to wait continue #does this work here? time.sleep(65) # waits a bit more than a minute to escape if = true time.sleep(5)
def main(): key = 'cc8047a5-a693-417a-9721-c6213690acbb' ely = '324249' cambridge = '350731' #fcDataType = wxfcs or wxobs weatherType = { 'NA': 'Huh?', '1': 'Sunny', '2': 'Cloudy', '3': 'Cloudy', '4': 'Huh?', '5': 'Misty', '6': 'Foggy', '7': 'Cloudy', '8':"O'cast", '9': 'L-Shwr', '10': 'L-Shwr', '11': 'Drizzl', '12': 'L-Rain', '13': 'H-Shwr', '14': 'H-Shwr', '15': 'H-Rain', '16': 'L-Sleet', '17': 'L-Sleet', '18': 'Sleet', '19': 'L-Hail', '20': 'L-Hail', '21': 'Hail!!', '22': 'L-Snow', '23': 'L-Snow', '24': 'L-Snow', '25': 'Snow', '26': 'Snow', '27': 'H-Snow', '28': 'Stormy', '29': 'Stormy', '30': 'Stormy' } while True: response = urllib2.urlopen('http://datapoint.metoffice.gov.uk/public/data/val/wxfcs/all/json/' + ely + '?res=3hourly&key=' + key) fcData = response.read() fcDataStr = fcData.decode('utf-8') fcDataDict = json.loads(fcDataStr) dataDate = (fcDataDict['SiteRep']['DV']['dataDate']) fcDate = (fcDataDict['SiteRep']['DV']['Location']['Period'][1]['value']) fcTime = (fcDataDict['SiteRep']['DV']['Location']['Period'][1]['Rep'][3]['$']) fcTemp = (fcDataDict['SiteRep']['DV']['Location']['Period'][1]['Rep'][3]['T']) fcPp = (fcDataDict['SiteRep']['DV']['Location']['Period'][1]['Rep'][3]['Pp']) fcWeather = (fcDataDict['SiteRep']['DV']['Location']['Period'][1]['Rep'][3]['W']) print '\n' print '**** New Data ****' print 'Forecast Date = ' + fcDate print 'Forecast time = ' + fcTime print 'Temp DegC = ' + fcTemp print 'Rain % = '+ fcPp print 'Weather type = ' + fcWeather weather = weatherType[fcWeather] print weather msg = 'Forecast: 9AM tomorrow' #write_string(msg, offset_x = 7, kerning = False) write_string(weather, offset_y = 0, kerning = False) write_string('T: ' + fcTemp, offset_y = 7, kerning = False) write_string('R% ' + fcPp, offset_y = 14, kerning = False) for updateInterval in range(900): show() time.sleep(4) for pixelRow in range(7): scroll_vertical() show() time.sleep(0.03) clear()
def display_strings_array(lines): delay = 0.03 line_height = microdotphat.HEIGHT + 2 lengths = [0] * len(lines) offset_left = 0 for line, text in enumerate(lines): lengths[line] = microdotphat.write_string(text, offset_x=offset_left, offset_y=line_height * line, kerning=False) offset_left += lengths[line] microdotphat.set_pixel(0, (len(lines) * line_height) - 1, 0) current_line = 0 microdotphat.show() pos_x = 0 pos_y = 0 for current_line in range(len(lines)): time.sleep(delay * 10) for y in range(lengths[current_line]): microdotphat.scroll(1, 0) pos_x += 1 time.sleep(delay) microdotphat.show() if current_line == len(lines) - 1: microdotphat.scroll_to(0, 0) else: for x in range(line_height): microdotphat.scroll(0, 1) pos_y += 1 microdotphat.show() time.sleep(delay)
#!/usr/bin/env python import datetime import time from microdotphat import write_string, set_decimal, clear, show print("""Thermal Displays the temperature measured from thermal zone 0, using /sys/class/thermal/thermal_zone0/temp Press Ctrl+C to exit. """) delay = 1 while True: clear() path="/sys/class/thermal/thermal_zone0/temp" f = open(path, "r") temp_raw = int(f.read().strip()) temp = float(temp_raw / 1000.0) write_string( "%.2f" % temp + "c", kerning=False) show() time.sleep(delay)
#!/usr/bin/env python import time from microdotphat import HEIGHT, write_string, scroll_vertical, show print("""Vertical Text Scrolls text messages vertically. Press Ctrl+C to exit. """) lines = ['One', 'Two', 'Three', 'Four', 'Five'] for line, text in enumerate(lines): write_string(text, offset_y = line*7, kerning=False) show() while True: time.sleep(1) for x in range(7): scroll_vertical() show() time.sleep(0.02)
#!/usr/bin/env python import time import sys import microdotphat print("""Scrolling Text Scrolls a single word char by char across the screen. Usage: {name} "your message" Press Ctrl+C to exit. """.format(name=sys.argv[0])) text = "Ninja" if len(sys.argv) > 1: text = sys.argv[1] microdotphat.write_string(text, offset_x=0, kerning=False) microdotphat.show() time.sleep(0.5) while True: microdotphat.scroll(amount_x=8) microdotphat.show() time.sleep(0.5)
string = 0 shown = True show() # Start time. Phase offset by math.pi/2 start = time.time() while True: # Fade the brightness in/out using a sine wave b = (math.sin((time.time() - start) * speed) + 1) / 2 set_brightness(b) # At minimum brightness, swap out the string for the next one if b < 0.002 and shown: clear() write_string(strings[string], kerning=False) string += 1 string %= len(strings) show() shown = False # At maximum brightness, confirm the string has been shown if b > 0.998: shown = True # Sleep a bit to save resources, this wont affect the fading speed time.sleep(0.01)
headers = {'Content-Type' : 'application/json'} response = requests.get(url,data=json_data, headers=headers) parsedjson = json.loads(response.text) StationCode=[] BikesAvailable=[] DocksAvailable=[] for i in range(len(parsedjson['stations'])): StationCode.append(str(parsedjson['stations'][i]['n'])) BikesAvailable.append(int(parsedjson['stations'][i]['ba'])) DocksAvailable.append(int(parsedjson['stations'][i]['da'])) ErieCode='M32047' VassarCode='M32042' KendallTCode='M32004' KendallT2Code='M32003' BikesErie=BikesAvailable[StationCode.index(ErieCode)] BikesVassar=BikesAvailable[StationCode.index(VassarCode)] DocksKendallT=DocksAvailable[StationCode.index(KendallTCode)] DocksKendallT2=DocksAvailable[StationCode.index(KendallT2Code)] BikeStatus='E'+str(min(9,BikesErie))+'V'+str(min(9,BikesVassar))+'K'+str(min(9,DocksKendallT+DocksKendallT2)) #print BikeStatus while True: clear() write_string(BikeStatus, kerning=False) show()
#!/usr/bin/env python import time import sys from microdotphat import write_string, scroll, show print("""Scrolling Text Scrolls a message across the screen. Usage: {name} "your message" Press Ctrl+C to exit. """.format(name=sys.argv[0])) text = "In the old #BILGETANK we'll keep you in the know! " if len(sys.argv) > 1: text = sys.argv[1] write_string(text, offset_x=0) while True: scroll() show() time.sleep(0.05)
import strava import datetime import time from microdotphat import set_brightness, write_string, set_decimal, clear, show st = strava.Strava() set_brightness(0.1) while True: clear() t = datetime.datetime.now() if t.second > 10: if t.second % 2 == 0: set_decimal(2, 1) set_decimal(4, 1) else: set_decimal(2, 0) set_decimal(4, 0) write_string(t.strftime("%H%M%S"), kerning=False) else: total_distance = "{:6.0f}".format(st.get_total_distance()) write_string(total_distance, kerning=False) show() time.sleep(1)
line_height = HEIGHT + 2 lines = ["In the old #BILGETANK we'll keep you in the know", "In the old #BILGETANK we'll fix your techie woes", "And we'll make things", "And we'll break things", "'til we're altogether aching", "Then we'll grab a cup of grog down in the old #BILGETANK"] lengths = [0] * len(lines) offset_left = 0 for line, text in enumerate(lines): lengths[line] = write_string(text, offset_x=offset_left, offset_y=line_height * line) offset_left += lengths[line] set_pixel(0, (len(lines) * line_height) - 1, 0) current_line = 0 show() while True: pos_x = 0 pos_y = 0 for current_line in range(len(lines)): time.sleep(delay*10) for y in range(lengths[current_line]): scroll(1,0)
import pyowm import datetime import time from microdotphat import HEIGHT, write_string, scroll_vertical, show, clear owm = pyowm.OWM('09d46b1004c007a330052dcde0109616') observation = owm.weather_at_place("Mountain View,CA") while True: w = observation.get_weather() #wind = w.get_wind() status = w.get_status() temperature = w.get_temperature('fahrenheit') temp = str(temperature["temp"]) + "F" t = datetime.datetime.now() alltime = t.strftime('%I' + ":" + '%M') lines = [status, temp, alltime] for line, text in enumerate(lines): write_string(text, offset_y=line * 7, kerning=False) show() while True: time.sleep(1) for x in range(7): scroll_vertical() show() time.sleep(0.02)
#!/usr/bin/env python import time import datetime from microdotphat import write_string, set_decimal, clear, show while True: clear() t = datetime.datetime.now() if t.second % 2 == 0: set_decimal(2, 1) set_decimal(4, 1) else: set_decimal(2, 0) set_decimal(4, 0) write_string(t.strftime('%H%M%S'), kerning=False) show() time.sleep(0.05)
import time from microdotphat import write_string, scroll, clear, show clear() write_string('Forecast, SNOWCATS! ') while True: scroll() show() time.sleep(0.01)
def write_kokudaland(offset_x=0, offset_y=0): font = [[ 0x00, 0x62, 0x42, 0x42, 0x46],[ # ko 0x00, 0x18, 0x24, 0x42, 0x00],[ # ku 0x44, 0x3E, 0x54, 0x56, 0x55],[ # da 0x00, 0x4A, 0x4A, 0x2A, 0x1A],[ # la 0x00, 0x44, 0x44, 0x20, 0x1E],[ # n 0x00, 0x7E, 0x08, 0x12, 0x11] # d ] for (i, char) in enumerate(font): write_customchar(char, offset_x=i*8+offset_x, offset_y=offset_y) def write_customchar(char, offset_x=0, offset_y=0): for x in range(5): for y in range(7): p = (char[x] & (1 << y)) > 0 set_pixel(offset_x + x, offset_y + y, p) write_kokudaland() write_nishi(offset_y=7) write_string("g-17a", offset_x=8, offset_y = 7, kerning=False) show() while True: time.sleep(5) for i in range(7): scroll_vertical() show() time.sleep(0.05)