class Display(): """ Creates a display command instance. Its update method calles the update method for all the blocks, and hence should be called at the frequency which updates are desired. """ def __init__(self): self.lcd = Adafruit_CharLCDPlate() self.lcd.begin(16,2) self.lcd.clear() self.lcd.home() self.time = TimeBlock(self.lcd) self.status = StatusBlock(self.lcd) self.query = QueryBlock(self.lcd) self.lastState = OFF self.state = OFF def update(self,state=None): self.time.update() self.status.update() # set our own lastState and state based on the query block self.lastState = self.query.lastState if state and state == IDLE: self.state = self.query.update(enterIdleState=True) elif state and state == PROCESS: self.state = self.query.update(enterProcessState=True) elif state and state == QUERY: self.state = self.query.update(enterQueryState=True) else: self.state = self.query.update() if DEBUG: print state,self.state # turn off if we just changed to OFF # turn on if we just changed from OFF if self.state == OFF and self.lastState != OFF: self.off() if self.state != OFF and self.lastState == OFF: self.on() if DEBUG: print self.state def on(self): self.query.update(enterIdleState=True) self.lcd.display() self.lcd.backlight(self.lcd.ON) def off(self): self.lcd.noDisplay() self.lcd.backlight(self.lcd.OFF) def fail(self,message=''): self.lcd.display() self.lcd.clear() self.lcd.home() self.lcd.backlight(self.lcd.ON) self.lcd.message("EPIC FAIL\n%s" % message)
class Display(): def __init__(self): self.lcd = Adafruit_CharLCDPlate(busnum=1) def clear(self): self.lcd.clear() def start(self): self.lcd.begin(16, 2) self.lcd.backlight(self.lcd.ON) def stop(self): self.clear() self.lcd.backlight(self.lcd.OFF) def message(self, message=""): self.start() self.lcd.message(message) def button_pressed(self, button=None): if self.lcd.buttonPressed(button): time.sleep(.2) return(True) else: return(False) def button_left(self): return(self.button_pressed(self.lcd.LEFT)) def button_right(self): return(self.button_pressed(self.lcd.RIGHT)) def button_up(self): return(self.button_pressed(self.lcd.UP)) def button_down(self): return(self.button_pressed(self.lcd.DOWN)) def button_select(self): return(self.button_pressed(self.lcd.SELECT)) def blink_cursor(self): self.lcd.blink() def move_cursor(self, col=0, row=0): self.lcd.setCursor(col, row)
class LCDPlate(): def __init__(self): self.lcd = Adafruit_CharLCDPlate() self.lcd.begin(16, 2) self.lcd.clear() self.lcd.backlight(self.lcd.GREEN) def update_active(self, result, heat, cool, fan): if result == 'cool': self.lcd.backlight(self.lcd.BLUE) elif result == 'heat': self.lcd.backlight(self.lcd.RED) elif result == 'off': self.lcd.backlight(self.lcd.GREEN) def update_temperature(self, temp): self.lcd.clear() self.lcd.message("Temp: %.1fF" % temp) def off(self): self.lcd.backlight(self.lcd.OFF) self.lcd.clear()
class LCDPlate(): def __init__(self): self.lcd = Adafruit_CharLCDPlate() self.lcd.begin(16, 2) self.lcd.clear() self.lcd.backlight(self.lcd.GREEN) def update_active(self, result, heat, cool, fan): if result == 'cool': self.lcd.backlight(self.lcd.BLUE) elif result == 'heat': self.lcd.backlight(self.lcd.RED) elif result == 'off': self.lcd.backlight(self.lcd.GREEN) def update_temperature(self, temp): self.lcd.clear() self.lcd.message("Temp: %.1fF" % temp) def off(self): self.lcd.backlight(self.lcd.OFF) self.lcd.clear()
tilt = 1 elif tilt < -1: tilt = -1 elif m==1: panOld=pan tiltOld=tilt pan = "{:.4f}".format(pan) tilt = "{:.4f}".format(tilt) lcd.clear() lcd.message("{}\n{} {}".format(mode[m],pan,tilt)) data = [throttle,turn,pan,tilt,shotD,shotB] convertBit(data) try: global isRunning lcd.begin(16,2) lcd.clear() lcd.backlight(lcd.ON); lcd.message("System Starting") controllerServer = SocketServer.UDPServer(('', portListen), receiverHandler) ser = serial.Serial('/dev/ttyACM0', 9600) data = [0,0,0,0,0,0] convertBit(data) sleep(2) isRunning = True while isRunning: controllerServer.serve_forever() print 'Finished' except KeyboardInterrupt: print 'Terminated' data = [0,0,0,0,0,0]
import tty import termios import logging import thread import time import fcntl import os import RPi.GPIO as GPIO import nfc from Adafruit_CharLCDPlate import Adafruit_CharLCDPlate from Adafruit_CharLCDPlate2 import Adafruit_CharLCDPlate2 emptyLine = " " lcd1 = Adafruit_CharLCDPlate() lcd2 = Adafruit_CharLCDPlate2() lcd1.begin(20, 4) lcd2.begin(20, 4); lcd1.clear() lcd2.clear() lcd1.message("Welcome.\nStarting...") lcd1.backlight(lcd.ON) time.sleep(2) def sendPOST (message): params = urllib.urlencode({'@number': message, '@type': 'issue', '@action': 'show'}) headers = {"Content-type": "application/x-www-form-urlencoded","Accept": "text/plain"} conn = httplib.HTTPConnection("bugs.python.org") conn.request("POST", "", params, headers) response = conn.getresponse() print response.status, response.reason data = response.read()
signal.signal(signal.SIGTERM, handler) # Determine hardware revision and initialize LCD revision = "unknown" cpuinfo = open("/proc/cpuinfo", "r") for line in cpuinfo: item = line.split(':', 1) if item[0].strip() == "Revision": revision = item[1].strip() if revision.startswith('a'): lcd = Adafruit_CharLCDPlate(busnum=1) else: lcd = Adafruit_CharLCDPlate() lcd.begin(16, 2) lcd.message(" Naomi Project\n Ver. 1.4.") sleep(2) # Try to import game list script, if it fails, signal error on LCD try: from gamelist import games except (SyntaxError, ImportError) as e: lcd.clear() lcd.message("Game List Error!\n Check Syntax") sleep(5) games = {} # Purge game dictionary of game files that can't be found missing_games = [] for key, value in games.iteritems():
def go(filename, token): print "here we go" lcd = Adafruit_CharLCDPlate() lcd.begin(16, 2) lcd.clear() lcd.message("UP=LOG,LFT=fixWW\nDWN=File,RGT=Info") sleep(1) i=0 lcd.ON prev = -1 while not (lcd.buttonPressed(lcd.SELECT)): # The ELSE on all button pushes which handle multiple clicks is the first entry point if (lcd.buttonPressed(lcd.RIGHT)): # cycle through: WEATHER, IP, and TIME then repeat lcd.clear() if prev == "r1": prev = "r2" lcd.message('Your IP address:\n %s' % _IP()) sleep(1) elif prev == "r2": prev = -1 #lcd.message('The time:\n%s' % strftime('%y/%m/%d %I:%M %p', gmtime())) lcd.message('The time:\n%s' % str(gpsd.utc)) sleep(1) else: prev = "r1" content = _WEATHER(gpsd.fix.latitude, gpsd.fix.longitude) lcd.message(content) sleep(1) if (lcd.buttonPressed(lcd.LEFT)): # reconnects the internet if disconnected lcd.clear() if prev == 'l1': prev = -1 msg = pushSpecial (gpsd, fsURL, userName, passWord) lcd.message(msg) sleep(1) else: prev = 'l1' sats = gpsd.satellites gSatCount = 0 for item in sats: if item.used == True: gSatCount += 1 totSats = len(sats) lcd.message("%s Sats of\n %s used" % (gSatCount, totSats)) sleep(1) if (lcd.buttonPressed(lcd.UP)): # starts the GPS logging prev = 'u1' while prev == 'u1': lcd.clear() try: msg = push (gpsd, fsURL, userName, passWord, filename, token) content = str("{0:.3f},{1:.3f}\n{2}").format(msg[0], msg[1], msg[2]) except Exception, e: print str(e) content = str(e) lcd.message(content +str(i)) ### press DOWN 1 second after an updated msg to quit logging sleep(1) if (lcd.buttonPressed(lcd.UP)): prev = -1 lcd.clear() lcd.message("stopped\ncollecting") ### i+=1 sleep(int(pCollectTime)) ''' out = True while out: lcd.clear() try: msg = push (gpsd, fsURL, userName, passWord, pushOnConnect) content = str("{0:.3f},{1:.3f}\n{2}").format(msg[0], msg[1], msg[2]) except Exception, e: print str(e) content = "cant get lat/lon" lcd.message(content +str(i)) ### press DOWN 1 second after an updated msg to quit logging sleep(1) if (lcd.buttonPressed(lcd.DOWN)): out = False lcd.clear() lcd.message("stopped\ncollecting") ### i+=1 sleep(int(pCollectTime)) ''' if (lcd.buttonPressed(lcd.DOWN)): # shows how many lines in current .CSV file # 2nd push starts a new file print prev lcd.clear() if prev == "d1": prev = -1 curNum = os.path.splitext(filename[filename.rfind('_')+1:])[0] newNum = int(curNum) +1 filename= filename.replace(str(curNum), str(newNum)) lcd.message("now using:\n %s" % filename) sleep(1) else: prev = 'd1' try: with open(filename) as f: for i, l in enumerate(f): pass lines = i+1 except IOError: lines = "???" lcd.message("f: %s has\n %s lines" % (filename, lines)) sleep(1)
class UI_Adafruit(Thread): _db = None _pi_rev = None _lcd = None menu = None prevmenu = None nextmenu = None _scandone = False _pressedButtons = [] _index = 0 # Simple lookup dict for menu class names _menus = { UIAdaMenus.main : UIAdaMainMenu, UIAdaMenus.nodes : UIAdaNodesMenu, UIAdaMenus.games : UIAdaGamesMenu, UIAdaMenus.config : UIAdaConfigMenu } def __init__(self, prefs, nodeman, games): super(UI_Adafruit, self).__init__() self.__logger = logging.getLogger("UI_Adafruit " + str(id(self))) self.__logger.debug("init logger") self._lcd = Adafruit_CharLCDPlate() MBus.add_handler(GameList_ScanEventMessage, self.handle_GameList_ScanEventMessage) MBus.add_handler(FOAD, self.die) # Let the user know that we're doing things self._lcd.begin(16, 2) self._lcd.message("CANTBoot Loading\n Hold up.") self._games = games self._nodes = nodeman.nodes def die(self, data): self.line1="Goodbye George<3" self.line2="" sleep(2) self.line1 = "" try: menu.exitmenu = True sleep(0.5) except: pass def handle_GameList_ScanEventMessage(self, message: GameList_ScanEventMessage): self._lcd.clear() if message.payload == "donelol": self._scandone = True self._lcd.message("Init Success") else: self.line1= message.payload self.line2 ='Scanning...' # THE MEAT(tm) def runui(self): sel_idx = 0 nextmenu = None while 1: # Don't do anything until we've booted up successfully if self._scandone: menu = UIAdaNodesMenu(self._lcd, self._nodes) if nextmenu: prevmenu = nextmenu if nextmenu == UIAdaMenus.main: menu = UIAdaMainMenu(self._lcd) elif nextmenu == UIAdaMenus.nodes: menu = UIAdaNodesMenu(self._lcd, self._nodes) elif nextmenu == UIAdaMenus.games: menu = UIAdaGamesMenu(self._lcd, self._games, self._nodes[sel_idx].node_id) #menu = UIAdaGamesMenu(self._lcd, self._games, '0') menuret = menu.run_menu() nextmenu = menuret[0] sel_idx = menuret[1] #process return values here and determine if we need to do anything special, e.g. load a game else: # We're not done booting, hang on a second (literally). sleep(1) '''
#!/usr/bin/python from Adafruit_CharLCDPlate import Adafruit_CharLCDPlate from subprocess import * from time import sleep, strftime from datetime import datetime import json import urllib2 import time lcd = Adafruit_CharLCDPlate() lcd.begin(16, 1) def BTC(): stamp = json.load(urllib2.urlopen('https://www.bitstamp.net/api/ticker/')) current_price = stamp["last"] # > $1000 rollover, Rounds/Converts to int if (int(round(float(current_price))) > 1000): stamp_price = int(round(float(current_price))) else: stamp_price = current_price return stamp_price def DOGE(): cryptsy = json.load( urllib2.urlopen( 'http://pubapi.cryptsy.com/api.php?method=singlemarketdata&marketid=132' ))
class WatchBox(): # Begin Extended from Adafruit_CharLCDPlate ------------------------------- # Port expander input pin definitions SELECT = 0 RIGHT = 1 DOWN = 2 UP = 3 LEFT = 4 btn = ( (SELECT, 'Select'), (LEFT, 'Gauche'), (UP, 'Haut'), (DOWN, 'Bas'), (RIGHT, 'Droite') ) # LED colors COLORS = {} COLORS['OFF'] = 0x00 COLORS['RED'] = 0x01 COLORS['GREEN'] = 0x02 COLORS['BLUE'] = 0x04 COLORS['YELLOW'] = 0x01 + 0x02 COLORS['TEAL'] = 0x02 + 0x04 COLORS['VIOLET'] = 0x01 + 0x04 COLORS['WHITE'] = 0x01 + 0x02 + 0x04 COLORS['ON'] = 0x01 + 0x02 + 0x04 # END Extended from Adafruit_CharLCDPlate --------------------------------- curMenuIndex = 'MAIN' # Level previousMenuIndex = '' curMenuPosition = 0 # Position dans le menu actuel cursorStyle = "=> " menuSize = 0 menuSequence = {} # Contient l'arborescence complète parcouru curIndexMenuSequence = 0 menu = {} # Contient la liste des éléments permettant de générer le menu menu['MAIN'] = ( ( 'Run' , 'START' ), ( 'Settings' , 'SETTINGS' ), ( 'About' , 'ABOUT' ), ( 'Quit' , 'QUIT' ) ) menu['SETTINGS'] = ( ( 'Color' , 'COLORS' ), ( 'Back' , 'BACK' ) ) menu['COLORS'] = ( ( 'Red' , 'RED' ), ( 'Green' , 'GREEN' ), ( 'Blue' , 'BLUE' ), ( 'Yellow' , 'YELLOW' ), ( 'Teal' , 'TEAL' ), ( 'Violet' , 'VIOLET' ), ( 'White' , 'WHITE' ), ( 'Back' , 'BACK' ) ) isStarted = False lcd = '' config = '' ''' Redéfinition des méthodes de la classe Adafruit pour gagner du temps dans l'écriture ''' def backlight(self , backlight): _backlight = self.COLORS[backlight] self.lcd.backlight( _backlight ) def clear(self): self.lcd.clear() def message(self,msg): self.lcd.message(msg) def buttonPressed(self,btn): return self.lcd.buttonPressed(btn) def scrollDisplayLeft(self): self.lcd.scrollDisplayLeft() def numlines(self): return self.lcd.numlines ''' Fonctions servant pour la gestion du Menu ''' ''' Fonction permettant d'initialiser la gestion du menu ''' def InitMenu(self): self.lcd = Adafruit_CharLCDPlate() self.lcd.begin(16, 2) self.isStarted = True # Initialisation du Menu self.menuSequence[self.curIndexMenuSequence] = 'MAIN' self.initMenuSize() self.readConfigFile() ''' Fonction permettant d'initialiser le rétro éclairage de l'écran''' def initBacklight(self): backlight = self.config.get('Main','backlight') self.backlight( backlight ) ''' Fonction permettant d'initialiser le nombre d'éléments dans le menu courant ''' def initMenuSize(self): self.menuSize = len(self.menu[self.menuSequence[self.curIndexMenuSequence]]) ''' Fonction permettant d'afficher les éléments du menu / de gérer les actions ''' def getItems( self , btn ): curIndex = self.curMenuPosition # On récupère la position actuelle dans le menu # Gestion du bouton if btn == self.lcd.SELECT: # Le bouton "select" est appuyé curMenuIndex = self.menuSequence[self.curIndexMenuSequence] # Il faut effectuer l'action demandée associée au menu courant if self.menu[curMenuIndex][curIndex][1] == 'QUIT' : self.ActionQuit() return True if self.menu[curMenuIndex][curIndex][1] == 'ABOUT' : self.ActionAbout() return True if self.menu[curMenuIndex][curIndex][1] == 'BACK' : if self.menuSequence[self.curIndexMenuSequence] != 'MAIN': self.curIndexMenuSequence-=1 self.initMenuSize() self.getItems( -1 ) return True if curMenuIndex == 'COLORS' : # Demande de changement de couleur du rétro éclairage color = self.menu[curMenuIndex][curIndex][1] self.writeConfigFile('Main','backlight',color) self.backlight( color ) self.getItems( -1 ) return True if self.menu[self.menu[curMenuIndex][curIndex][1]] : # On regarde si l'action est associée à un sous menu CurrentmenuNameIndexed = self.menuSequence[self.curIndexMenuSequence] NextmenuNameIndexed = self.menu[curMenuIndex][curIndex][1] print("Current Index :"+CurrentmenuNameIndexed) print("Next Index : "+NextmenuNameIndexed) self.menuSequence[self.curIndexMenuSequence] = CurrentmenuNameIndexed # On stocke l'id du menu actuel self.curIndexMenuSequence+=1 # On déplace le pointer vers la droite self.menuSequence[self.curIndexMenuSequence] = NextmenuNameIndexed # On stocke l'id du nouveau menu self.initMenuSize() # On recalcule le nombre d'éléments dans le menu self.curMenuPosition = 0 # On se place au premier élément du nouveau menu self.getItems( -1 ) # On affiche le menu return True else: self.lcd.clear() if btn == self.lcd.DOWN: curIndex+=1 if btn == self.lcd.UP: curIndex-=1 # Cas des sortie du menu (haut / bas) if curIndex < 0: curIndex = self.menuSize-1 if curIndex >= self.menuSize: curIndex = 0 # Génération du texte à afficher print(self.menu[self.menuSequence[self.curIndexMenuSequence]][curIndex][0]) msg = self.cursorStyle + self.menu[self.menuSequence[self.curIndexMenuSequence]][curIndex][0]+"\n" if (curIndex+1) != self.menuSize: msg+= self.menu[self.menuSequence[self.curIndexMenuSequence]][(curIndex+1)][0] # Mise à jours de la position courante du curseur dans menu self.curMenuPosition = curIndex # On affiche le texte sur l'afficheur print(msg) self.clear() self.message(msg) ''' Action permettant de quitter l'application ''' def ActionQuit(self): self.isStarted = False self.message("Bye...") print("Ending application...") ''' Action permettant d'afficher le About ''' def ActionAbout(self): msg = ( 'Test Application Adafruit' , 'Damien Broqua < *****@*****.**>' ) stringSize = len(msg[0]) if len(msg[1]) > stringSize: stringSize = len(msg[1]) loop = True maxloop = stringSize - self.numlines() + 1 counterScroll = 0 self.lcd.clear() wait = True while loop == True: self.message( msg[0]+"\n"+msg[1]) if stringSize > self.numlines(): sleep(0.5) self.scrollDisplayLeft() counterScroll+=1 else: sleep(4) loop = False if counterScroll > maxloop: loop = False if self.buttonPressed(self.lcd.LEFT): # L'utilisateur appuie sur le bouton de gauche pour revenir au menu précédent wait = False loop = False if wait == True: # L'utilisateur n'a pas appuyé sur le bouton de gauche, on lui ré affiche pendant 2 secondes le message initial sleep(2) # Petite pause pour revoir le message initial self.curMenuIndex = 'MAIN' # On se repositionne sur le menu principal self.getItems(-1) # On affiche le menu principal def readConfigFile(self): try: with open('config.cfg'): self.config = ConfigParser.RawConfigParser() self.config.read('config.cfg') except IOError: self.createConfigFile() def createConfigFile(self): # Initialisation des variables sauvegardées self.config = ConfigParser.RawConfigParser() self.config.add_section('Main') self.config.set('Main', 'backlight', 'RED') # Writing our configuration file to 'example.cfg' with open('config.cfg', 'wb') as configfile: self.config.write(configfile) def writeConfigFile(self , section , col , value ): self.config.set(section,col,value) with open('config.cfg', 'wb') as configfile: self.config.write(configfile)
import smbus configfile = 'lcdmenu.xml' # set DEBUG=1 for print debug statements DEBUG = 0 DISPLAY_ROWS = 2 DISPLAY_COLS = 16 # set busnum param to the correct value for your pi lcd = Adafruit_CharLCDPlate(busnum = 1) # in case you add custom logic to lcd to check if it is connected (useful) #if lcd.connected == 0: # quit() lcd.begin(DISPLAY_COLS, DISPLAY_ROWS) lcd.backlight(lcd.OFF) # commands def DoQuit(): lcd.clear() lcd.message('Are you sure?\nPress Sel for Y') while 1: if lcd.buttonPressed(lcd.LEFT): break if lcd.buttonPressed(lcd.SELECT): lcd.clear() lcd.backlight(lcd.OFF) quit() sleep(0.25)
class Display(): CHAR_SET ={'default': [ [0b00000, # 0 <- 0b00010, 0b00110, 0b01110, 0b00110, 0b00010, 0b00000, 0b00000], [0b00000, # 1 -> 0b01000, 0b01100, 0b01110, 0b01100, 0b01000, 0b00000, 0b00000], [0b00000, # 2 ^ 0b00000, 0b00100, 0b01110, 0b11111, 0b00000, 0b00000, 0b00000], [0b00000, # 3 v 0b00000, 0b11111, 0b01110, 0b00100, 0b00000, 0b00000, 0b00000], [0b00110, # 4 Degree 0b01001, 0b01001, 0b00110, 0b00000, 0b00000, 0b00000, 0b00000], [0b11111, # 5 Black Block 0b11111, 0b11111, 0b11111, 0b11111, 0b11111, 0b11111, 0b11111], [0b10101, # 6 Gray Block 0b01010, 0b10101, 0b01010, 0b10101, 0b01010, 0b10101, 0b01010], [0b10010, # 7 Light Gray Block 0b01001, 0b00100, 0b10010, 0b01001, 0b00100, 0b10010, 0b01001] ], 'TemperatureExtend': [ [0b11111, # 0 Black Block 0b11111, 0b11111, 0b11111, 0b11111, 0b11111, 0b11111, 0b11111], [0b11111, # 1 Dark Gray Block 0b01101, 0b10110, 0b11011, 0b01101, 0b10110, 0b11011, 0b11111], [0b11111, # 2 Gray Block 0b01010, 0b10101, 0b01010, 0b10101, 0b01010, 0b10101, 0b11111], [0b11111, # 3 Light Gray Block 0b01001, 0b00100, 0b10010, 0b01001, 0b00100, 0b10010, 0b11111], [0b00111, # 4 Left 0b01000, 0b10000, 0b10000, 0b10000, 0b10000, 0b01000, 0b00111], [0b11100, # 5 Right 0b11110, 0b11111, 0b11111, 0b11111, 0b11111, 0b11110, 0b11100], [0b00110, # 6 Degree 0b01001, 0b01001, 0b00110, 0b00000, 0b00000, 0b00000, 0b00000] ]} OPSET = (Adafruit_CharLCDPlate.LEFT, Adafruit_CharLCDPlate.RIGHT, Adafruit_CharLCDPlate.UP, Adafruit_CharLCDPlate.DOWN, Adafruit_CharLCDPlate.SELECT) OPLANG = {Adafruit_CharLCDPlate.LEFT:'LEFT', Adafruit_CharLCDPlate.RIGHT:'RIGHT', Adafruit_CharLCDPlate.UP:'UP', Adafruit_CharLCDPlate.DOWN:'DOWN', Adafruit_CharLCDPlate.SELECT:'SELECT'} MENU = {0:' SELECT ' + chr(1) + ' \nSystem Info', 1:' ' + chr(0) + ' SELECT ' + chr(1) + ' \nNetwork Info', 2:' ' + chr(0) + ' SELECT ' + chr(1) + ' \nTemperature', 3:' ' + chr(0) + ' SELECT ' + chr(1) + ' \nDisk Info', 4:' ' + chr(0) + ' SELECT ' + chr(1) + ' \nSystem Tools', 5:' ' + chr(0) + ' SELECT ' + chr(1) + ' \nWeather', 98:' ' + chr(0) + ' SELECT ' + chr(1) + ' \nSetting', 99:' ' + chr(0) + ' SELECT \nExit'} # State transition table STT = { # MENU_0 SYSTEM INFO 0:{ 0:{ Adafruit_CharLCDPlate.RIGHT : (1, 0), Adafruit_CharLCDPlate.SELECT: (0, 1) }, # DEFAULT 1:{ Adafruit_CharLCDPlate.LEFT: (0, 0) } }, # MENU_1 NETWORK INFO 1:{ 0:{ Adafruit_CharLCDPlate.LEFT : (0, 0), Adafruit_CharLCDPlate.RIGHT : (2, 0), Adafruit_CharLCDPlate.SELECT: (1, 1) }, # DEFAULT 1:{ Adafruit_CharLCDPlate.LEFT : (1, 0), Adafruit_CharLCDPlate.UP : (1, 2), Adafruit_CharLCDPlate.DOWN : (1, 3) }, # PAGE UP 2:{ Adafruit_CharLCDPlate.LEFT : (1, 0), Adafruit_CharLCDPlate.UP : (1, 2), Adafruit_CharLCDPlate.DOWN : (1, 3) }, # PAGE DOWN 3:{ Adafruit_CharLCDPlate.LEFT : (1, 0), Adafruit_CharLCDPlate.UP : (1, 2), Adafruit_CharLCDPlate.DOWN : (1, 3) } }, # MENU_2 TEMPERATURE 2:{ 0:{ Adafruit_CharLCDPlate.LEFT : (1, 0), Adafruit_CharLCDPlate.RIGHT : (3, 0), Adafruit_CharLCDPlate.SELECT: (2, 1) }, # DEFAULT 1:{ Adafruit_CharLCDPlate.LEFT: (2, 0) } }, # MENU_3 DISK INFO 3:{ 0:{ Adafruit_CharLCDPlate.LEFT : (2, 0), Adafruit_CharLCDPlate.RIGHT : (4, 0), Adafruit_CharLCDPlate.SELECT: (3, 1) }, # DEFAULT 1:{ Adafruit_CharLCDPlate.LEFT: (3, 0) } }, # MENU_4 SYSTEM TOOLS 4:{ 0:{ Adafruit_CharLCDPlate.LEFT : (3, 0), Adafruit_CharLCDPlate.RIGHT : (5, 0), Adafruit_CharLCDPlate.SELECT: (4, 1) }, # TOOL LIST 1:{ Adafruit_CharLCDPlate.LEFT : (4, 0), Adafruit_CharLCDPlate.UP : (4, 2), Adafruit_CharLCDPlate.DOWN : (4, 3), Adafruit_CharLCDPlate.SELECT: (4, 4) }, # TOOL LIST UP 2:{ Adafruit_CharLCDPlate.LEFT : (4, 0), Adafruit_CharLCDPlate.UP : (4, 2), Adafruit_CharLCDPlate.DOWN : (4, 3), Adafruit_CharLCDPlate.SELECT: (4, 4) }, # TOOL LIST DOWN 3:{ Adafruit_CharLCDPlate.LEFT : (4, 0), Adafruit_CharLCDPlate.UP : (4, 2), Adafruit_CharLCDPlate.DOWN : (4, 3), Adafruit_CharLCDPlate.SELECT: (4, 4) }, # TOOL DIALOG SELECT ONE 4:{ Adafruit_CharLCDPlate.SELECT: (4, 6), Adafruit_CharLCDPlate.RIGHT : (4, 5) }, # TOOL DIALOG SELECT TWO 5:{ Adafruit_CharLCDPlate.SELECT: (4, 7), Adafruit_CharLCDPlate.LEFT : (4, 4) }, # TOOL DIALOG SELECT EXCUTE ONE 6:{ Adafruit_CharLCDPlate.SELECT: (4, 1) }, # TOOL DIALOG SELECT EXCUTE TWO 7:{ Adafruit_CharLCDPlate.SELECT: (4, 1) } }, # MENU_5 WEATHER 5:{ 0:{ Adafruit_CharLCDPlate.LEFT : (4, 0), Adafruit_CharLCDPlate.RIGHT : (98, 0), Adafruit_CharLCDPlate.SELECT: (5, 1) }, # DEFAULT 1:{ Adafruit_CharLCDPlate.LEFT: (5, 0) } }, # MENU_98 SETTING 98:{ 0:{ Adafruit_CharLCDPlate.LEFT : (4, 0), Adafruit_CharLCDPlate.RIGHT : (99, 0), Adafruit_CharLCDPlate.SELECT: (98, 1) }, # SETTING LIST 1:{ Adafruit_CharLCDPlate.LEFT : (98, 0), Adafruit_CharLCDPlate.UP : (98, 2), Adafruit_CharLCDPlate.DOWN : (98, 3), Adafruit_CharLCDPlate.SELECT: (98, 4) }, # SETTING LIST UP 2:{ Adafruit_CharLCDPlate.LEFT : (98, 0), Adafruit_CharLCDPlate.UP : (98, 2), Adafruit_CharLCDPlate.DOWN : (98, 3), Adafruit_CharLCDPlate.SELECT: (98, 4) }, # SETTING LIST DOWN 3:{ Adafruit_CharLCDPlate.LEFT : (98, 0), Adafruit_CharLCDPlate.UP : (98, 2), Adafruit_CharLCDPlate.DOWN : (98, 3), Adafruit_CharLCDPlate.SELECT: (98, 4) }, # SETTING DIALOG SELECT ONE 4:{ Adafruit_CharLCDPlate.SELECT: (98, 6), Adafruit_CharLCDPlate.RIGHT : (98, 5) }, # SETTING DIALOG SELECT TWO 5:{ Adafruit_CharLCDPlate.SELECT: (98, 7), Adafruit_CharLCDPlate.LEFT : (98, 4) }, # SETTING DIALOG SELECT EXCUTE ONE 6:{ Adafruit_CharLCDPlate.SELECT: (98, 1) }, # SETTING DIALOG SELECT EXCUTE TWO 7:{ Adafruit_CharLCDPlate.SELECT: (98, 1) } }, # MENU_99 EXIT 99:{ 0:{ Adafruit_CharLCDPlate.LEFT : (98, 0), Adafruit_CharLCDPlate.SELECT: (99, 1) }, # NO 1:{ Adafruit_CharLCDPlate.SELECT: (99, 0), Adafruit_CharLCDPlate.RIGHT : (99, 2) }, # YES 2:{ Adafruit_CharLCDPlate.SELECT: (99, 3), Adafruit_CharLCDPlate.LEFT : (99, 1) }, # EXIT 3:{ } } } def __init__(self, curMenu = 0, debug = False): # Init EventMethods self.AUTO_REFRESH_PERIOD = 5 self.EventMethods = { 'EventMethods_0_1': self.EventMethods_SystemInfo, 'EventMethods_1_1': self.EventMethods_NetworkInfo, 'EventMethods_1_2': self.EventMethods_NetworkInfo_Up, 'EventMethods_1_3': self.EventMethods_NetworkInfo_Down, 'EventMethods_2_1': self.EventMethods_Temperature, 'EventMethods_3_1': self.EventMethods_DiskInfo, 'EventMethods_4_1': self.EventMethods_Tools, 'EventMethods_4_2': self.EventMethods_Tools_Up, 'EventMethods_4_3': self.EventMethods_Tools_Down, 'EventMethods_4_4': self.EventMethods_Tools_One, 'EventMethods_4_5': self.EventMethods_Tools_Two, 'EventMethods_4_6': self.EventMethods_Tools_Excute_One, 'EventMethods_4_7': self.EventMethods_Tools_Excute_Two, 'EventMethods_5_1': self.EventMethods_Weather, 'EventMethods_98_1': self.EventMethods_Setting, 'EventMethods_98_2': self.EventMethods_Setting_Up, 'EventMethods_98_3': self.EventMethods_Setting_Down, 'EventMethods_98_4': self.EventMethods_Setting_One, 'EventMethods_98_5': self.EventMethods_Setting_Two, 'EventMethods_98_6': self.EventMethods_Setting_Excute_One, 'EventMethods_98_7': self.EventMethods_Setting_Excute_Two, 'EventMethods_99_1': self.EventMethods_Exit_No, 'EventMethods_99_2': self.EventMethods_Exit_Yes, 'EventMethods_99_3': self.EventMethods_Exit } self.TOOLS_NUM = 2 self.TOOLS_LIST = ( {'name':'Reboot', 'handle':self.EventMethods_Reboot }, {'name':'Power Off', 'handle':self.EventMethods_PowerOff } ) self.SETTING_NUM = 3 self.SETTING_LIST = ( {'name':'Backlight', 'handle':self.EventMethods_Backlight }, {'name':'Auto Refresh', 'handle':self.EventMethods_AutoRefresh }, {'name':'Weather Report', 'handle':self.EventMethods_Backlight } ) # Init LCD self.lcd = Adafruit_CharLCDPlate() self.lcd.begin(16, 2) self.lcd.backlight(Adafruit_CharLCDPlate.RED) sleep(1) self.lcd.backlight(Adafruit_CharLCDPlate.GREEN) sleep(1) self.lcd.backlight(Adafruit_CharLCDPlate.BLUE) sleep(1) self.lcd.backlight(Adafruit_CharLCDPlate.ON) # Init Char Set self.loadCharset() # Set default screen self.curMenu = curMenu self.curPage = 0 self.debug = debug # Init AutoRefeashMethods self.AutoRefreshMethod = None thread.start_new_thread(self.autoRefresh, ()) def loadCharset(self, charset = 'default'): for i, item in enumerate(self.CHAR_SET[charset]): self.lcd.createChar(i, item) def autoRefresh(self): if(self.debug): print 'Auto refresh thread started!' while True: if self.AutoRefreshMethod != None: try: self.EventMethods[self.AutoRefreshMethod]() except Exception, e: if(self.debug): print str(e) if(self.debug): print self.AutoRefreshMethod, ' fired!' sleep(self.AUTO_REFRESH_PERIOD)
import RPi.GPIO as GPIO from time import sleep from datetime import datetime import time from Adafruit_CharLCDPlate import Adafruit_CharLCDPlate from Adafruit_I2C import Adafruit_I2C import gaugette.rotary_encoder import gaugette.switch import MySQLdb as mdb #MYSQL con = mdb.connect("localhost", "pitunes", "pitunes", "pitunes") #LCD lcd = Adafruit_CharLCDPlate() lcd.begin(20, 4) lcd.clear() #Volume control volume_max = 60 volume_visual_max = 18 volume_default = 5 i2c = Adafruit_I2C(0x2A, 1, False) i2c.write8(0x10, volume_default) #Default Volumelevel #Rotary Encoders enc_right_pin_a = 11 enc_right_pin_b = 10 sw_right_pin = 6 enc_left_pin_a = 14 enc_left_pin_b = 13
# set busnum param to the correct value for your pi lcd = Adafruit_CharLCDPlate(busnum=1) # in case you add custom logic to lcd to check if it is connected (useful) #if lcd.connected == 0: # quit() awb_choice = 0 iso_choice = 0 AWB_MODES = [ 'off', 'auto', 'sunlight', 'cloudy', 'shade', 'tungsten', 'fluorescent', 'incandescent', 'flash', 'horizon' ] ISO_MODES = [0, 100, 200, 320, 400, 500, 640, 800] lcd.begin(DISPLAY_COLS, DISPLAY_ROWS) lcd.backlight(lcd.OFF) # commands def DoQuit(): lcd.clear() lcd.message('Are you sure?\nPress Sel for Y') while 1: if lcd.buttonPressed(lcd.LEFT): break if lcd.buttonPressed(lcd.SELECT): lcd.clear() lcd.backlight(lcd.OFF) quit() sleep(0.25)
destination = d.destination line_length_wo_dest = len(route) + len(time) + 2 line_length = line_length_wo_dest + len(destination) destination_avail = line_width - line_length_wo_dest if line_length > line_width: destination_avail = line_width - line_length_wo_dest if destination_avail > 0: destination = destination[0:destination_avail] else: destination = "" else: destination = destination.ljust(destination_avail) str_departure = ("%s %s %s" % (route, destination, time)) menu.add_item(MenuItem(str_departure.encode('ascii', errors='replace'), load_data)) line_width = 16 lcd = Adafruit_CharLCDPlate() lcd.begin(line_width, 2) menu = Menu(lcd, "Main Menu") menu.set_item_prefix("") load_data() menu.get_action()()
class Display(): CHAR_SET = { 'default': [ [ 0b00000, # 0 <- 0b00010, 0b00110, 0b01110, 0b00110, 0b00010, 0b00000, 0b00000 ], [ 0b00000, # 1 -> 0b01000, 0b01100, 0b01110, 0b01100, 0b01000, 0b00000, 0b00000 ], [ 0b00000, # 2 ^ 0b00000, 0b00100, 0b01110, 0b11111, 0b00000, 0b00000, 0b00000 ], [ 0b00000, # 3 v 0b00000, 0b11111, 0b01110, 0b00100, 0b00000, 0b00000, 0b00000 ], [ 0b00110, # 4 Degree 0b01001, 0b01001, 0b00110, 0b00000, 0b00000, 0b00000, 0b00000 ], [ 0b11111, # 5 Black Block 0b11111, 0b11111, 0b11111, 0b11111, 0b11111, 0b11111, 0b11111 ], [ 0b10101, # 6 Gray Block 0b01010, 0b10101, 0b01010, 0b10101, 0b01010, 0b10101, 0b01010 ], [ 0b10010, # 7 Light Gray Block 0b01001, 0b00100, 0b10010, 0b01001, 0b00100, 0b10010, 0b01001 ] ], 'TemperatureExtend': [ [ 0b11111, # 0 Black Block 0b11111, 0b11111, 0b11111, 0b11111, 0b11111, 0b11111, 0b11111 ], [ 0b11111, # 1 Dark Gray Block 0b01101, 0b10110, 0b11011, 0b01101, 0b10110, 0b11011, 0b11111 ], [ 0b11111, # 2 Gray Block 0b01010, 0b10101, 0b01010, 0b10101, 0b01010, 0b10101, 0b11111 ], [ 0b11111, # 3 Light Gray Block 0b01001, 0b00100, 0b10010, 0b01001, 0b00100, 0b10010, 0b11111 ], [ 0b00111, # 4 Left 0b01000, 0b10000, 0b10000, 0b10000, 0b10000, 0b01000, 0b00111 ], [ 0b11100, # 5 Right 0b11110, 0b11111, 0b11111, 0b11111, 0b11111, 0b11110, 0b11100 ], [ 0b00110, # 6 Degree 0b01001, 0b01001, 0b00110, 0b00000, 0b00000, 0b00000, 0b00000 ] ] } OPSET = (Adafruit_CharLCDPlate.LEFT, Adafruit_CharLCDPlate.RIGHT, Adafruit_CharLCDPlate.UP, Adafruit_CharLCDPlate.DOWN, Adafruit_CharLCDPlate.SELECT) OPLANG = { Adafruit_CharLCDPlate.LEFT: 'LEFT', Adafruit_CharLCDPlate.RIGHT: 'RIGHT', Adafruit_CharLCDPlate.UP: 'UP', Adafruit_CharLCDPlate.DOWN: 'DOWN', Adafruit_CharLCDPlate.SELECT: 'SELECT' } MENU = { 0: ' SELECT ' + chr(1) + ' \nSystem Info', 1: ' ' + chr(0) + ' SELECT ' + chr(1) + ' \nNetwork Info', 2: ' ' + chr(0) + ' SELECT ' + chr(1) + ' \nTemperature', 3: ' ' + chr(0) + ' SELECT ' + chr(1) + ' \nDisk Info', 4: ' ' + chr(0) + ' SELECT ' + chr(1) + ' \nSystem Tools', 5: ' ' + chr(0) + ' SELECT ' + chr(1) + ' \nWeather', 98: ' ' + chr(0) + ' SELECT ' + chr(1) + ' \nSetting', 99: ' ' + chr(0) + ' SELECT \nExit' } # State transition table STT = { # MENU_0 SYSTEM INFO 0: { 0: { Adafruit_CharLCDPlate.RIGHT: (1, 0), Adafruit_CharLCDPlate.SELECT: (0, 1) }, # DEFAULT 1: { Adafruit_CharLCDPlate.LEFT: (0, 0) } }, # MENU_1 NETWORK INFO 1: { 0: { Adafruit_CharLCDPlate.LEFT: (0, 0), Adafruit_CharLCDPlate.RIGHT: (2, 0), Adafruit_CharLCDPlate.SELECT: (1, 1) }, # DEFAULT 1: { Adafruit_CharLCDPlate.LEFT: (1, 0), Adafruit_CharLCDPlate.UP: (1, 2), Adafruit_CharLCDPlate.DOWN: (1, 3) }, # PAGE UP 2: { Adafruit_CharLCDPlate.LEFT: (1, 0), Adafruit_CharLCDPlate.UP: (1, 2), Adafruit_CharLCDPlate.DOWN: (1, 3) }, # PAGE DOWN 3: { Adafruit_CharLCDPlate.LEFT: (1, 0), Adafruit_CharLCDPlate.UP: (1, 2), Adafruit_CharLCDPlate.DOWN: (1, 3) } }, # MENU_2 TEMPERATURE 2: { 0: { Adafruit_CharLCDPlate.LEFT: (1, 0), Adafruit_CharLCDPlate.RIGHT: (3, 0), Adafruit_CharLCDPlate.SELECT: (2, 1) }, # DEFAULT 1: { Adafruit_CharLCDPlate.LEFT: (2, 0) } }, # MENU_3 DISK INFO 3: { 0: { Adafruit_CharLCDPlate.LEFT: (2, 0), Adafruit_CharLCDPlate.RIGHT: (4, 0), Adafruit_CharLCDPlate.SELECT: (3, 1) }, # DEFAULT 1: { Adafruit_CharLCDPlate.LEFT: (3, 0) } }, # MENU_4 SYSTEM TOOLS 4: { 0: { Adafruit_CharLCDPlate.LEFT: (3, 0), Adafruit_CharLCDPlate.RIGHT: (5, 0), Adafruit_CharLCDPlate.SELECT: (4, 1) }, # TOOL LIST 1: { Adafruit_CharLCDPlate.LEFT: (4, 0), Adafruit_CharLCDPlate.UP: (4, 2), Adafruit_CharLCDPlate.DOWN: (4, 3), Adafruit_CharLCDPlate.SELECT: (4, 4) }, # TOOL LIST UP 2: { Adafruit_CharLCDPlate.LEFT: (4, 0), Adafruit_CharLCDPlate.UP: (4, 2), Adafruit_CharLCDPlate.DOWN: (4, 3), Adafruit_CharLCDPlate.SELECT: (4, 4) }, # TOOL LIST DOWN 3: { Adafruit_CharLCDPlate.LEFT: (4, 0), Adafruit_CharLCDPlate.UP: (4, 2), Adafruit_CharLCDPlate.DOWN: (4, 3), Adafruit_CharLCDPlate.SELECT: (4, 4) }, # TOOL DIALOG SELECT ONE 4: { Adafruit_CharLCDPlate.SELECT: (4, 6), Adafruit_CharLCDPlate.RIGHT: (4, 5) }, # TOOL DIALOG SELECT TWO 5: { Adafruit_CharLCDPlate.SELECT: (4, 7), Adafruit_CharLCDPlate.LEFT: (4, 4) }, # TOOL DIALOG SELECT EXCUTE ONE 6: { Adafruit_CharLCDPlate.SELECT: (4, 1) }, # TOOL DIALOG SELECT EXCUTE TWO 7: { Adafruit_CharLCDPlate.SELECT: (4, 1) } }, # MENU_5 WEATHER 5: { 0: { Adafruit_CharLCDPlate.LEFT: (4, 0), Adafruit_CharLCDPlate.RIGHT: (98, 0), Adafruit_CharLCDPlate.SELECT: (5, 1) }, # DEFAULT 1: { Adafruit_CharLCDPlate.LEFT: (5, 0) } }, # MENU_98 SETTING 98: { 0: { Adafruit_CharLCDPlate.LEFT: (4, 0), Adafruit_CharLCDPlate.RIGHT: (99, 0), Adafruit_CharLCDPlate.SELECT: (98, 1) }, # SETTING LIST 1: { Adafruit_CharLCDPlate.LEFT: (98, 0), Adafruit_CharLCDPlate.UP: (98, 2), Adafruit_CharLCDPlate.DOWN: (98, 3), Adafruit_CharLCDPlate.SELECT: (98, 4) }, # SETTING LIST UP 2: { Adafruit_CharLCDPlate.LEFT: (98, 0), Adafruit_CharLCDPlate.UP: (98, 2), Adafruit_CharLCDPlate.DOWN: (98, 3), Adafruit_CharLCDPlate.SELECT: (98, 4) }, # SETTING LIST DOWN 3: { Adafruit_CharLCDPlate.LEFT: (98, 0), Adafruit_CharLCDPlate.UP: (98, 2), Adafruit_CharLCDPlate.DOWN: (98, 3), Adafruit_CharLCDPlate.SELECT: (98, 4) }, # SETTING DIALOG SELECT ONE 4: { Adafruit_CharLCDPlate.SELECT: (98, 6), Adafruit_CharLCDPlate.RIGHT: (98, 5) }, # SETTING DIALOG SELECT TWO 5: { Adafruit_CharLCDPlate.SELECT: (98, 7), Adafruit_CharLCDPlate.LEFT: (98, 4) }, # SETTING DIALOG SELECT EXCUTE ONE 6: { Adafruit_CharLCDPlate.SELECT: (98, 1) }, # SETTING DIALOG SELECT EXCUTE TWO 7: { Adafruit_CharLCDPlate.SELECT: (98, 1) } }, # MENU_99 EXIT 99: { 0: { Adafruit_CharLCDPlate.LEFT: (98, 0), Adafruit_CharLCDPlate.SELECT: (99, 1) }, # NO 1: { Adafruit_CharLCDPlate.SELECT: (99, 0), Adafruit_CharLCDPlate.RIGHT: (99, 2) }, # YES 2: { Adafruit_CharLCDPlate.SELECT: (99, 3), Adafruit_CharLCDPlate.LEFT: (99, 1) }, # EXIT 3: {} } } def __init__(self, curMenu=0, debug=False): # Init EventMethods self.AUTO_REFRESH_PERIOD = 5 self.EventMethods = { 'EventMethods_0_1': self.EventMethods_SystemInfo, 'EventMethods_1_1': self.EventMethods_NetworkInfo, 'EventMethods_1_2': self.EventMethods_NetworkInfo_Up, 'EventMethods_1_3': self.EventMethods_NetworkInfo_Down, 'EventMethods_2_1': self.EventMethods_Temperature, 'EventMethods_3_1': self.EventMethods_DiskInfo, 'EventMethods_4_1': self.EventMethods_Tools, 'EventMethods_4_2': self.EventMethods_Tools_Up, 'EventMethods_4_3': self.EventMethods_Tools_Down, 'EventMethods_4_4': self.EventMethods_Tools_One, 'EventMethods_4_5': self.EventMethods_Tools_Two, 'EventMethods_4_6': self.EventMethods_Tools_Excute_One, 'EventMethods_4_7': self.EventMethods_Tools_Excute_Two, 'EventMethods_5_1': self.EventMethods_Weather, 'EventMethods_98_1': self.EventMethods_Setting, 'EventMethods_98_2': self.EventMethods_Setting_Up, 'EventMethods_98_3': self.EventMethods_Setting_Down, 'EventMethods_98_4': self.EventMethods_Setting_One, 'EventMethods_98_5': self.EventMethods_Setting_Two, 'EventMethods_98_6': self.EventMethods_Setting_Excute_One, 'EventMethods_98_7': self.EventMethods_Setting_Excute_Two, 'EventMethods_99_1': self.EventMethods_Exit_No, 'EventMethods_99_2': self.EventMethods_Exit_Yes, 'EventMethods_99_3': self.EventMethods_Exit } self.TOOLS_NUM = 2 self.TOOLS_LIST = ({ 'name': 'Reboot', 'handle': self.EventMethods_Reboot }, { 'name': 'Power Off', 'handle': self.EventMethods_PowerOff }) self.SETTING_NUM = 3 self.SETTING_LIST = ({ 'name': 'Backlight', 'handle': self.EventMethods_Backlight }, { 'name': 'Auto Refresh', 'handle': self.EventMethods_AutoRefresh }, { 'name': 'Weather Report', 'handle': self.EventMethods_Backlight }) # Init LCD self.lcd = Adafruit_CharLCDPlate() self.lcd.begin(16, 2) self.lcd.backlight(Adafruit_CharLCDPlate.RED) sleep(1) self.lcd.backlight(Adafruit_CharLCDPlate.GREEN) sleep(1) self.lcd.backlight(Adafruit_CharLCDPlate.BLUE) sleep(1) self.lcd.backlight(Adafruit_CharLCDPlate.ON) # Init Char Set self.loadCharset() # Set default screen self.curMenu = curMenu self.curPage = 0 self.debug = debug # Init AutoRefeashMethods self.AutoRefreshMethod = None thread.start_new_thread(self.autoRefresh, ()) def loadCharset(self, charset='default'): for i, item in enumerate(self.CHAR_SET[charset]): self.lcd.createChar(i, item) def autoRefresh(self): if (self.debug): print 'Auto refresh thread started!' while True: if self.AutoRefreshMethod != None: try: self.EventMethods[self.AutoRefreshMethod]() except Exception, e: if (self.debug): print str(e) if (self.debug): print self.AutoRefreshMethod, ' fired!' sleep(self.AUTO_REFRESH_PERIOD)
class menuLCD(treeList): OFFTIME = 20 EXITFILE = '/tmp/menuLCD.exit' def __init__(self): sleep(.5) self.lcd = Adafruit_CharLCDPlate(busnum=1) sleep(.5) self.lcd.begin(16, 2) sleep(.5) self.lcd.clear() self.lcd.message("Menu LCD library \nversion 1.0!") treeList.__init__(self) self.button = ((self.lcd.SELECT, 'Select'), (self.lcd.LEFT , 'Left' ), (self.lcd.UP , 'Up' ), (self.lcd.DOWN , 'Down' ), (self.lcd.RIGHT , 'Right' )) self.elapsed = 0 self.time2Sleep = 0 self.displayOn = False if os.path.isfile(self.EXITFILE): os.remove(self.EXITFILE) sleep(1) ################################################################################################################## def exitMenu(self): if self.ynQuestion('are you sure?'): self.shutdown() sys.exit(0) ################################################################################################################## def ynQuestion(self, text): self.lcd.clear() sleep(.1) self.lcd.message(text+'\n'+'left(n) right(y)') response = False exitLoop = False while not exitLoop: for btn in self.button: if self.lcd.buttonPressed(btn[0]): if btn[0] == self.lcd.RIGHT: exitLoop = True response = True if btn[0] == self.lcd.LEFT: exitLoop = True response = False sleep(.1) return response ################################################################################################################## def keyUp(self): response = False for btn in self.button: if self.lcd.buttonPressed(btn[0]): if btn[0] == self.lcd.UP: response=True return response ################################################################################################################## def keyDown(self): response = False for btn in self.button: if self.lcd.buttonPressed(btn[0]): if btn[0] == self.lcd.DOWN: response=True return response ################################################################################################################## def keyRight(self): response = False for btn in self.button: if self.lcd.buttonPressed(btn[0]): if btn[0] == self.lcd.RIGHT: response=True return response ################################################################################################################## def keyLeft(self): response = False for btn in self.button: if self.lcd.buttonPressed(btn[0]): if btn[0] == self.lcd.LEFT: response=True return response ################################################################################################################## def keySelect(self): response = False for btn in self.button: if self.lcd.buttonPressed(btn[0]): if btn[0] == self.lcd.SELECT: response=True return response ################################################################################################################## def keyPressed(self): response = False for btn in self.button: if self.lcd.buttonPressed(btn[0]): if btn[0] == self.lcd.RIGHT or btn[0] == self.lcd.LEFT or btn[0] == self.lcd.UP or btn[0] == self.lcd.DOWN: response=True return response ################################################################################################################## def shutdown(self): self.turnOnDisplay() self.clearLCD() self.message2LCD('Exiting...') sleep(2) self.turnOffDisplay() ################################################################################################################## def setTime2Sleep(self,t): self.OFFTIME = t ################################################################################################################## def message2LCD(self, msn): self.lcd.message(msn) ################################################################################################################## def clearLCD(self): self.lcd.clear() ################################################################################################################## def turnOffDisplay(self): if self.displayOn: self.lcd.noDisplay() self.lcd.backlight(self.lcd.OFF) self.displayOn = False ################################################################################################################## def turnOnDisplay(self): if not self.displayOn: self.lcd.display() self.lcd.backlight(self.lcd.ON) self.displayOn = True ################################################################################################################## def resetTime2Sleep(self): self.elapsed = time() self.time2Sleep = 0 ################################################################################################################## def lcdRefresh(self): self.turnOnDisplay() self.lcd.clear() sleep(.1) menuString = '%s\n[%s]'%(treeList.activeItemString(self),treeList.activePosition(self)) self.lcd.message(menuString) sleep(.1) ################################################################################################################## def checkButtons(self): for btn in self.button: if self.lcd.buttonPressed(btn[0]): self.resetTime2Sleep() if self.displayOn: if btn[0] == self.lcd.RIGHT: treeList.goNext(self) if btn[0] == self.lcd.LEFT: treeList.goPrev(self) if btn[0] == self.lcd.DOWN: if treeList.activeEntryHasItems(self): treeList.goDown(self) else: treeList.goNext(self) if btn[0] == self.lcd.UP: treeList.goUp(self) if btn[0] == self.lcd.SELECT: if treeList.typeOfActiveItem(self) == treeList.CMD: treeList.command(self)() self.resetTime2Sleep() self.lcdRefresh() ################################################################################################################## def check2Sleep(self): if self.time2Sleep < self.OFFTIME: self.time2Sleep = time() - self.elapsed else: self.turnOffDisplay() ################################################################################################################## def check4Exit(self): returnValue = True if os.path.isfile(self.EXITFILE): os.remove(self.EXITFILE) returnValue=False return returnValue ################################################################################################################## def play(self): treeList.goTop(self) self.lcdRefresh() self.resetTime2Sleep() while self.check4Exit(): self.check2Sleep() self.checkButtons() self.shutdown() sys.exit(0) ################################################################################################################## def addExitEntry(self, *parentName): if len(parentName)>0: treeList.addItem(self,parentName[0],'Exit', self.exitMenu) else: treeList.addItem(self,treeList.ROOT,'Exit', self.exitMenu)
#!/usr/bin/python from Adafruit_CharLCDPlate import Adafruit_CharLCDPlate from subprocess import * from time import sleep, strftime from datetime import datetime import json import urllib2 import time lcd = Adafruit_CharLCDPlate() lcd.begin(16,1) #Add support for user prompt on launch to select between different APIs/Currencies print "OPTIONS: BTC_mtgox, BTC_btce, BTC_bitstamp, DOGE_cryptsy" input_var = input("Enter your choice (Case Sensitive): ") print ("You entered: " + input_var) def BTC_mtgox(): mtgox = json.load(urllib2.urlopen('http://data.mtgox.com/api/1/BTCUSD/ticker')) if mtgox["result"] != "success": raise Exception("MtGox API failed!") current_price = mtgox["return"]["last"]["value"] #Prefix for display prefix = "BTC/USD: $" # > $1000 rollover, Rounds/Converts to int if (int(round(float(current_price))) > 1000):
# # A demo of some of the built in helper functions of # the Adafruit_CharLCDPlate.py This is 20x4 display specific. # # Using Adafruit_CharLCD code with the I2C and MCP230xx code aswell #---------------------------------------------------------------- numcolumns = 20 numrows = 4 from time import sleep from Adafruit_CharLCDPlate import Adafruit_CharLCDPlate lcd = Adafruit_CharLCDPlate() lcd.begin(numcolumns, numrows) lcd.backlight(lcd.ON) lcd.message("LCD 20x4\nDemonstration") sleep(2) while True: #Text on each line alone. lcd.clear() lcd.setCursor(0, 0) lcd.message("Line 1") sleep(1) lcd.clear() lcd.setCursor(0, 1) lcd.message("Line 2")
print lines else: lcd.write(line, True) #!/usr/bin/python if __name__ == '__main__': from time import sleep numcolumns = 20 numrows = 4 eol = LCD_EoL_Handling(numcolumns, numrows) lcd.backlight(lcd.ON) lcd.begin(numcolumns, numrows) eol.message("CharLCD\nEnd of Line Handling\nWith Forced\nCarriage Returns") sleep(2) lcd.clear() eol.message("Short String") sleep(2) lcd.clear() eol.message("Longer string then can't fit in one line",0) sleep(2) lcd.clear() eol.message("Longer string then can't fit in one line",1) sleep(2)
class Display(): BARRIER = [ [[0b00000, # Frame 0 0b00000, 0b00000, 0b00100, 0b01110, 0b01110, 0b11111, 0b11111], [0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000]], [[0b00000, # Frame 1 in 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000], [0b00000, 0b00000, 0b00000, 0b01000, 0b11100, 0b11100, 0b11110, 0b11110]], [[0b00000, # Frame 1 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00001, 0b00001], [0b00000, 0b00000, 0b00000, 0b10000, 0b11000, 0b11000, 0b11100, 0b11100]], [[0b00000, # Frame 2 in 0b00000, 0b00000, 0b00000, 0b00001, 0b00001, 0b00011, 0b00011], [0b00000, 0b00000, 0b00000, 0b00000, 0b10000, 0b10000, 0b11000, 0b11000]], [[0b00000, # Frame 2 0b00000, 0b00000, 0b00001, 0b00011, 0b00011, 0b00111, 0b00111], [0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b10000, 0b10000]], [[0b00000, # Frame 3 0b00000, 0b00000, 0b00010, 0b00111, 0b00111, 0b01111, 0b01111], [0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000]]] RUNNER = [ [[0b00000, # Frame 0 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000], [0b00000, 0b00000, 0b00000, 0b01110, 0b11111, 0b10101, 0b11111, 0b01110]], [[0b00000, # Frame 1 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000], [0b00000, 0b00000, 0b00000, 0b01110, 0b11111, 0b10101, 0b11111, 0b01110]], [[0b00000, # Frame 2 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000], [0b00100, 0b01110, 0b11111, 0b10101, 0b11111, 0b01110, 0b01110, 0b00000]], [[0b00000, # Frame 3 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b01110], [0b11111, 0b10101, 0b11111, 0b01110, 0b00100, 0b00000, 0b00000, 0b00000]], [[0b00000, # Frame 4 0b00000, 0b00000, 0b00000, 0b00000, 0b01110, 0b01110, 0b10101], [0b11111, 0b01110, 0b00100, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000]], [[0b00000, # Frame 5 0b00000, 0b00000, 0b00000, 0b01110, 0b11111, 0b10101, 0b11111], [0b01110, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000]], [[0b00000, # Frame 6 0b00000, 0b01110, 0b11111, 0b10101, 0b11111, 0b01110, 0b01110], [0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000]], [[0b00000, # Frame 7 0b01110, 0b10101, 0b11111, 0b01110, 0b00000, 0b00000, 0b00000], [0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000]], [[0b01110, # Frame 8 0b10101, 0b11111, 0b01110, 0b00000, 0b00000, 0b00000, 0b00000], [0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000]], [[0b11111, # Frame 9 0b10101, 0b01110, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000], [0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000]]] def __init__(self): # Init LCD self.lcdString = [[' ' for col in range(Layer.WIDTH)] for row in range(Layer.HEIGHT)] # Init layer self.canvas = Layer() self.runner = Layer() self.barrier = Layer() # Init pixelSet self.pixelSet = [list(Layer.EMPTY) for i in range(8)] # Init LCD self.lcd = Adafruit_CharLCDPlate() self.lcd.begin(16, 2) self.lcd.backlight(Adafruit_CharLCDPlate.ON) # Init Game self.game = Game(self.lcd) def mergeLayers(self): # Merge layer to canvas #self.canvas.mergeLayer(self.runner).mergeLayer(self.barrier) self.canvas.mergeLayer(self.barrier) self.canvas.mergeLayer(self.runner) def updateLcdString(self): # Update game screen count = 0 for row in range(Layer.HEIGHT): for col in range(Layer.WIDTH): if self.canvas.bitmap[row][col] == Layer.EMPTY: self.lcdString[row][col] = ' ' else: index = self.findInPixelSet(self.canvas.bitmap[row][col], count) #print '[', str(row), '][', str(col), ']: ' + str(index) #print self.canvas.bitmap[row][col] if index == -1: self.pixelSet[count] = list(self.canvas.bitmap[row][col]) self.lcdString[row][col] = chr(count) count += 1 else: self.lcdString[row][col] = chr(index) # Update score board score = str(self.game.score) index = 0 for i in range(Layer.WIDTH - len(score), Layer.WIDTH): self.lcdString[0][i] = score[index] index += 1 def loadCharset(self): for i, item in enumerate(self.pixelSet): self.lcd.createChar(i, item) def findInPixelSet(self, pixel, count): for i in range(count): if self.pixelSet[i] == pixel: return i return -1 def draw(self): if self.game.state == Game.STATE_START: self.lcd.message('Press SELECT to\n START GAME ') elif self.game.state == Game.STATE_END: self.lcd.message(' SCORE ' + str(self.game.score) + '\n GAME OVER ') else: line_1 = ''.join(self.lcdString[0]) line_2 = ''.join(self.lcdString[1]) self.lcd.message(line_1 + '\n' + line_2) self.loadCharset() def drawBarriers(self): for barrier in self.game.barriers: self.barrier.drawPointX(barrier[1], barrier[0], self.game.frame, self.BARRIER[self.game.frame]) def drawRunner(self): self.runner.drawPointY(1, 0, self.RUNNER[self.game.runner]) def run(self): while True: self.game.tick() if self.game.state == Game.STATE_RUNNING: self.drawBarriers() self.drawRunner() self.mergeLayers() self.updateLcdString() self.game.gameOver(self.barrier.bitmap[1][1], self.runner.bitmap[1][1]) self.draw() self.canvas = Layer() self.runner = Layer() self.barrier = Layer() sleep(.03)
imageNames = [] currentImageSelection = 0 listOfDrives = [] writeStatusLine = "" justCompleted = False nowWriting = False stopWritingNow = False lastPressedTime = time.time() lcd = Adafruit_CharLCDPlate() lcd.begin(COLUMNS, ROWS) lcd.clear() def getConnectedDrives(): commandOutput = runCommandAndGetStdout( "lsblk -d | awk -F: '{print $1}' | awk '{print $1}'") splitted = commandOutput.splitlines() drives = [] for drive in splitted: if drive != "NAME" and not drive.startswith("mmc"): drives.append(drive) return drives
class DisplayIPAddressDaemon: # initialize the LCD plate # use busnum = 0 for raspi version 1 (256MB) # and busnum = 1 for raspi version 2 (512MB) LCD = "" # lcd = "" # Define a queue to communicate with worker thread LCD_QUEUE = "" # Globals astring = "" setscroll = "" # Buttons NONE = 0x00 SELECT = 0x01 RIGHT = 0x02 DOWN = 0x04 UP = 0x08 LEFT = 0x10 UP_AND_DOWN = 0x0C LEFT_AND_RIGHT = 0x12 def __init__(self): self.LCD = Adafruit_CharLCDPlate(busnum = 0) # self.lcd = Adafruit_CharLCDPlate() self.LCD_QUEUE = Queue() self.stdin_path = '/dev/null' self.stdout_path = '/dev/tty' self.stderr_path = '/dev/tty' self.pidfile_path = '/var/run/testdaemon.pid' self.pidfile_timeout = 5 # ---------------------------- # WORKER THREAD # ---------------------------- # Define a function to run in the worker thread def update_lcd(self,q): while True: msg = q.get() # if we're falling behind, skip some LCD updates while not q.empty(): q.task_done() msg = q.get() self.LCD.setCursor(0,0) self.LCD.message(msg) q.task_done() return # ---------------------------- # MAIN LOOP # ---------------------------- def run(self): global astring, setscroll # Setup AdaFruit LCD Plate self.LCD.begin(16,2) self.LCD.clear() self.LCD.backlight(self.LCD.ON) # Create the worker thread and make it a daemon worker = Thread(target=self.update_lcd, args=(self.LCD_QUEUE,)) worker.setDaemon(True) worker.start() self.display_ipaddr() def delay_milliseconds(self, milliseconds): seconds = milliseconds / float(1000) # divide milliseconds by 1000 for seconds sleep(seconds) # ---------------------------- # DISPLAY TIME AND IP ADDRESS # ---------------------------- def display_ipaddr(self): show_eth0 = "ip addr show eth0 | cut -d/ -f1 | awk '/inet/ {printf \"e%15.15s\", $2}'" ipaddr = self.run_cmd(show_eth0) self.LCD.backlight(self.LCD.ON) i = 29 muting = False keep_looping = True while (keep_looping): # Every 1/2 second, update the time display i += 1 #if(i % 10 == 0): if(i % 5 == 0): self.LCD_QUEUE.put(datetime.now().strftime('%b %d %H:%M:%S\n')+ ipaddr, True) # Every 3 seconds, update ethernet or wi-fi IP address if(i == 60): ipaddr = self.run_cmd(show_eth0) i = 0 self.delay_milliseconds(99) # ---------------------------- def run_cmd(self,cmd): p = Popen(cmd, shell=True, stdout=PIPE, stderr=STDOUT) output = p.communicate()[0] return output