def print_to_LCDScreen (message): try: lcd = Adafruit_CharLCD() lcd.begin(16,2) for x in range(0, 16): for y in range(0, 2): lcd.setCursor(x, y) lcd.message('>') time.sleep(.025) lcd.noDisplay() lcd.clear() lcd.message(str(message)) for x in range(0, 16): lcd.DisplayLeft() lcd.display() for x in range(0, 16): lcd.scrollDisplayRight() time.sleep(.05) # lcd.noDisplay() # lcd.display() # lcd.blink() # lcd.noCursor() # lcd.clear() # lcd.noBlink() # lcd.begin(16, 2) # lcd.setCursor(7, 0) # lcd.message('123') # lcd.message('x') # lcd.clear() return 'ok' except Exception,e: return e
class BBQpi_Config(): def __init__(self): # Configuration self.pins_T0 = 3 # chip select pin for 1st thermocouple self.pins_T1 = 5 # chip select pin for 2nd thermocouple self.pins_out = 11 # output pin self.pins_clock = 7 # clock pin self.pins_relay = 24 # relay switch pin self.plot_avg = 5 # number of temp readings to be averaged self.control_time = 0 # initialize control time self.control_delay = 35 # control delay in second self.control_tolerance = 2 # tolerance self.alert_delay = 60 # alert delay in seconds self.alert_time = 0 # initialize alert time self.alert_email = '*****@*****.**' # Send message to email/smtp self.out_temp = 'temp.csv' # output file name for temperature data self.out_control = 'control.csv' # input file name for control parameters self.network_cmd0 = "ip addr show wlan0 | grep inet | awk '{print $2}' | cut -d/ -f1" self.network_cmd1 = "ip addr show eth0 | grep inet | awk '{print $2}' | cut -d/ -f1" self.network_smtp = ['*****@*****.**', '030206raspberrypi'] self.network_tweet = "/usr/local/bin/twitter [email protected] set " #Initialize components: self.LCD = Adafruit_CharLCD() self.LCD.begin(16, 1) self.RELAY = BBQpi_relay(self.pins_relay) self.T0 = BBQpi_thermocouple(self.pins_T0, self.pins_out, self.pins_clock) self.T1 = BBQpi_thermocouple(self.pins_T1, self.pins_out, self.pins_clock) # Initialize output files if os.path.isfile(self.out_temp): os.remove(self.out_temp) self.f = open(self.out_temp, 'wb') self.CSV = csv.writer(self.f, delimiter=',', quoting=csv.QUOTE_MINIMAL) # Find the devices IP Address self.ipaddr = '' try: self.ipaddr = run_cmd(self.network_cmd0) except: pass if (self.ipaddr == ''): self.ipaddr = run_cmd(self.network_cmd1) def sendmail(self, header, message): server = smtplib.SMTP("smtp.gmail.com", 587) server.starttls() server.login(self.network_smtp[0], self.network_smtp[1]) server.sendmail(header, self.alert_email, message) def sendtweet(self, message): print "trying to send a tweet!" tweetcommand = self.network_tweet + message subprocess.call(tweetcommand, shell=True)
class Display(Thread): # TODO: move this to a config file COLS = 16 ROWS = 2 COL_OFFSET = 2 # You may choose to add an offset to the original position DURATION = 15 PREFIX = "WARNING: " def __init__(self, msg): Thread.__init__(self) LCDReactor.Display.START_POSITION = LCDReactor.Display.COLS - LCDReactor.Display.COL_OFFSET self.msgs = [LCDReactor.Display.PREFIX, msg] self.lcd = CharLCD(pin_rs=2, pin_e=4, pins_db=[3, 14, 25, 24]) def init_display(self): self.lcd.clear() self.lcd.begin(LCDReactor.Display.COLS, LCDReactor.Display.ROWS) def display_message(self): self.lcd.setCursor(LCDReactor.Display.START_POSITION, 0) self.lcd.message(self.msgs[0]) self.lcd.setCursor(LCDReactor.Display.START_POSITION, 1) self.lcd.message(self.msgs[1]) def shift_text(self): self.lcd.DisplayLeft() time.sleep(0.3) def loop_message(self): # Calculate the maximum length and the start position # Needed for when the time runs out and the message is in the # middle of the LCD position = LCDReactor.Display.START_POSITION max_len = max(len(self.msgs[0]), len(self.msgs[1])) start_time = time.time() # Display for n seconds while time.time() < start_time + LCDReactor.Display.DURATION: self.shift_text() position = (position + 1) % max_len # If the text is in the middle of the screen, we want to shift it # off. The best way is to take the current position and move it # until the the position is out of the display. # "Out of display" is given by max_len (maximum image size) + # START_POSITION, since it starts in the right side of the LCD for x in range(position, LCDReactor.Display.START_POSITION + max_len): self.shift_text() self.lcd.clear() def display(self): self.init_display() self.display_message() self.loop_message() def run(self): self.display()
def printLCD(string1, string2): '''Prints string1 and string2 onto a 16x2 character LCD.''' lcd = Adafruit_CharLCD() lcd.begin(16,1) lcd.clear() sleep(0.5) lcd.message(string1+"\n") lcd.message(string2)
def Pantalla(Linea1, Linea2): lcd = Adafruit_CharLCD() lcd.begin(16,1) lcd.clear() lcd.message(Linea1+"\n") lcd.message(Linea2) lcd.cerrar()
class LCD_display(object): bus = 1 # Note you need to change the bus number to 0 if running on a revision 1 Raspberry Pi. address = 0x20 # I2C address of the MCP230xx chip. gpio_count = 8 # Number of GPIOs exposed by the MCP230xx chip, should be 8 or 16 depending on chip. # LCD 20x4 num_columns = 20 num_lines = 4 def __init__(self, init=True): # Create MCP230xx GPIO adapter. mcp = MCP230XX_GPIO(self.bus, self.address, self.gpio_count) # Create LCD, passing in MCP GPIO adapter. self.lcd = Adafruit_CharLCD(pin_rs=1, pin_e=2, pin_bl=7, pins_db=[3,4,5,6], GPIO=mcp) if init: self.initialisation() def initialisation(self): self.lcd.clear() self.lcd.begin(self.num_columns, self.num_lines) self.lcd.backlightOn() self.lcd.setCursor(0, 0) #self.lcd.message(datetime.datetime.now().strftime(' %a %d %b - %H:%M')) def line_message(self, row, text): # set the position (row from 0 to 3) self.lcd.setCursor(0, row) # display the message self.lcd.message(text) def temperature(self, text): #set the position self.lcd.setCursor(0, 1) #display the message and value self.lcd.message("Temperature: %.2f" % text) self.lcd.write4bits( 0xDF, True) #display the degree symbol "°" self.lcd.message("C") def humidity(self, text): #set the position self.lcd.setCursor(0, 2) #display the message and value self.lcd.message("Humidity: %.2f%%RH" % text) def pressure(self, text): #set the position self.lcd.setCursor(0, 3) #display the message and value self.lcd.message("Pressure: %.2fhPa" % text) def date(self): #set the position self.lcd.setCursor(0, 0) #display the message and value self.lcd.message(datetime.datetime.now().strftime(' %a %d %b %H:%M'))
class PapaDisplayCtrl: """Class to display text from PaPasPy """ def __init__(self): self.lcd = Adafruit_CharLCD() self.lcd.begin(16,1) self.lcd.clear() def display(self, msg): self.lcd.clear() self.lcd.message(msg)
def run(self): global lcd loadconfig() if (mod_config["lcd"] == "yes"): lcd = Adafruit_CharLCD() lcd.begin(16,1) while True: loadcurrentconditions() evaluaterules() timestamp = time.time() while (time.time() - timestamp < mod_config["interval"]): if (mod_config["lcd"] == "yes"): lcd_showcurrentconditions()
def init(): global lcd global sub pins = rospy.get_param('/pibot/pins/LCD1602') lcd = Adafruit_CharLCD(pin_rs=pins['RS'], pin_e=pins['EN'], pins_db=pins['DATA'], GPIO=None) lcd.begin(16, 2) lcd.clear() lcd.write(' PiBot Loaded \n Hello World! ') lcd.setCursor(0, 0) rospy.init_node('lcd1602') sub = rospy.Subscriber('/pibot/lcd1602', String, handler)
def __init__(self, sortedlist, config): nokia_lcds = [] #get bus pins first hd44780bus = config['local']['buses']['hd44780'] nokiabus = config['local']['buses']['nokia'] hd44780data_pins = [] for i in range(8): thispin = 'LCD_D' + str(i) if thispin in hd44780bus: hd44780data_pins.append(hd44780bus[thispin]) nokia_rst = nokiabus['LCD_RST'] nokia_dc = nokiabus['LCD_DC'] for ctrlid in sortedlist: dispdef = config['local']['controls'][ctrlid]['display'] if dispdef['type'] == 'hd44780': newlcd = Adafruit_CharLCD(pin_rs=hd44780bus['LCD_RS'], pins_db=hd44780data_pins) newlcd.pin_e = dispdef['pin'] GPIO.setup(newlcd.pin_e, GPIO.OUT) GPIO.output(newlcd.pin_e, GPIO.LOW) newlcd.begin(dispdef['width'], dispdef['height']) self.lcd[ctrlid] = newlcd print "Control %s is hd44780 on pin %s" % (ctrlid, newlcd.pin_e) else: if "contrast" in dispdef: contrast = int(dispdef['contrast']) else: contrast = 0xbb newlcd = NokiaLCD(pin_DC=nokia_dc, pin_RST=nokia_rst, pin_SCE=dispdef['pin'], contrast=contrast) newlcd.width = dispdef['width'] newlcd.height = dispdef['height'] newlcd.display_init() self.lcd[ctrlid] = newlcd nokia_lcds.append(newlcd) print "Control %s is nokia on pin %s" % (ctrlid, dispdef['pin']) # Do this now as it does not work in the big loop for some reason. if len(nokia_lcds) > 0: nokia_lcds[0].reset_all_displays() for nokia_lcd in nokia_lcds: nokia_lcd.display_init()
class GpioDisplay: def __init__(self, *_args): if GPIO.RPI_REVISION == 2: self.lcd = Adafruit_CharLCD(pins_db=[23, 17, 27, 22]) else: self.lcd = Adafruit_CharLCD() self.lcd.begin(16, 2) def clear(self): self.lcd.clear() def move_to(self, row, col): self.lcd.setCursor(row, col) def write(self, string): self.lcd.message(string) def backlight(self, r, g, b): # not implemented pass
def __init__(self, sortedlist, config): nokia_lcds = [] #get bus pins first hd44780bus = config['local']['buses']['hd44780'] nokiabus = config['local']['buses']['nokia'] hd44780data_pins = [] for i in range(8): thispin = 'LCD_D'+str(i) if thispin in hd44780bus: hd44780data_pins.append(hd44780bus[thispin]) nokia_rst = nokiabus['LCD_RST'] nokia_dc = nokiabus['LCD_DC'] for ctrlid in sortedlist: dispdef = config['local']['controls'][ctrlid]['display'] if dispdef['type'] == 'hd44780': newlcd = Adafruit_CharLCD(pin_rs = hd44780bus['LCD_RS'], pins_db=hd44780data_pins) newlcd.pin_e = dispdef['pin'] GPIO.setup(newlcd.pin_e, GPIO.OUT) GPIO.output(newlcd.pin_e, GPIO.LOW) newlcd.begin(dispdef['width'], dispdef['height']) self.lcd[ctrlid] = newlcd print "Control %s is hd44780 on pin %s" % (ctrlid, newlcd.pin_e) else: if "contrast" in dispdef: contrast = int(dispdef['contrast']) else: contrast = 0xbb newlcd = NokiaLCD(pin_DC=nokia_dc, pin_RST=nokia_rst, pin_SCE=dispdef['pin'], contrast=contrast) newlcd.width = dispdef['width'] newlcd.height = dispdef['height'] newlcd.display_init() self.lcd[ctrlid] = newlcd nokia_lcds.append(newlcd) print "Control %s is nokia on pin %s" % (ctrlid, dispdef['pin']) # Do this now as it does not work in the big loop for some reason. if len(nokia_lcds) > 0: nokia_lcds[0].reset_all_displays() for nokia_lcd in nokia_lcds: nokia_lcd.display_init()
class GpioDisplay: def __init__(self, *_args): if GPIO.RPI_REVISION == 2: self.lcd = Adafruit_CharLCD(pins_db=[23, 17, 27, 22]) else: self.lcd = Adafruit_CharLCD() self.lcd.begin(16,2) def clear(self): self.lcd.clear() def move_to(self, row, col): self.lcd.setCursor(row, col) def write(self, string): self.lcd.message(string) def backlight(self, r, g, b): # not implemented pass
def print_to_LCDScreen(message): try: lcd = Adafruit_CharLCD() lcd.begin(16, 2) for x in range(0, 16): for y in range(0, 2): lcd.setCursor(x, y) lcd.message('>') time.sleep(.025) lcd.noDisplay() lcd.clear() lcd.message(str(message)) for x in range(0, 16): lcd.DisplayLeft() lcd.display() for x in range(0, 16): lcd.scrollDisplayRight() time.sleep(.05) return 'ok' except Exception as e: return 'ok' # e
class PrinterWorkerThread(threading.Thread): def __init__(self, print_q): super(PrinterWorkerThread, self).__init__() self.print_q = print_q self.stoprequest = threading.Event() self.lcd = Adafruit_CharLCD() self.lcd.begin(16,1) self.lcd.clear() def run(self): while not self.stoprequest.isSet(): try: to_print = self.print_q.get(True, 0.05) self.lcd.clear() self.lcd.message('%s' %(to_print)) #self.lcd.message("Test") print("%s") % (to_print) except Queue.Empty: continue def join(self,timeout=None): self.stoprequest.set() super(PrinterWorkerThread, self).join(timeout)
def setup(): global lock, lcd, a_one, a_two lock = threading.RLock() GPIO.setmode(GPIO.BCM) GPIO.setup(AUTH_PIN, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) GPIO.setup(AUTH_INDICATOR, GPIO.OUT) GPIO.output(AUTH_INDICATOR, False) GPIO.setup(RING_STOP, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) GPIO.add_event_detect(RING_STOP, GPIO.RISING, callback=stop_alarms, bouncetime=300) GPIO.setup(ALARM_INDICATOR, GPIO.OUT) GPIO.output(ALARM_INDICATOR, ALARM_ACTIVE) GPIO.setup(ALARM_TOGGLE, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) GPIO.add_event_detect(ALARM_TOGGLE, GPIO.RISING, callback=alarm_toggle, bouncetime=300) a_one = Alarm(22) a_two = Alarm(27) lcd = Adafruit_CharLCD(pins_db=[23, 16, 21, 12], GPIO=GPIO) lcd.begin(16, 2)
class Scroller: def __init__(self): random.seed() self.width = 40 self.height = 2 self.timeoutmin = 20 self.timeoutmax = 100 self.wait_time = 40 self.separator = ' +++ ' self.paused = False self.paused_loop = 0 self.busy = False self.busy_loop = 0 self.elapsed = '' self.lines = [] self.offset = [] self.tag = [] for i in range(self.height): self.lines.append('') self.offset.append(0) self.tag.append('') self.ascii_art = {} self.load_ascii_art() # 0 - animation running # > 0 - animation countdown # -1 - animation and countdown disabled self.easter_egg_countdown = -1 self.animation_index = self.ascii_art.keys()[random.randrange(0, len(self.ascii_art))] self.animation_phase = 0 self.lcd = Adafruit_CharLCD() self.lcd.begin(40, 2) self.lcd.define_char(1, [0, 0x10, 0x08, 0x04, 0x02, 0x01, 0, 0]) self.lcd.define_char(2, [0, 31, 14, 4, 21, 10, 0, 0]) self.current_lines = ["", ""] def tr(self, s): result = ''.encode('latin-1') for c in unicode(s, 'UTF-8'): #print(c, ord(c)) if ord(c) == 92: result += u'\x01'.encode('latin-1') elif ord(c) < 128: result += c.encode('latin-1') elif ord(c) == 246: result += u'\xef'.encode('latin-1') elif ord(c) == 252: result += u'\xf5'.encode('latin-1') elif ord(c) == 228: result += u'\xe1'.encode('latin-1') elif ord(c) == 223: result += u'\xe2'.encode('latin-1') elif ord(c) == 169: result += '(c)'.encode('latin-1') else: pass #print(c) #print(ord(c)) return result def load_ascii_art(self): with open('ascii-art.txt') as f: while True: tag = f.readline().strip() if len(tag) == 0: break self.ascii_art[tag] = [] while True: line1 = f.readline().rstrip() if len(line1) == 0: break line2 = f.readline().rstrip() line1 = self.tr(line1) line2 = self.tr(line2) if len(line1) > len(line2): line2 += ' ' * (len(line1) - len(line2)) if len(line2) > len(line1): line1 += ' ' * (len(line2) - len(line1)) self.ascii_art[tag].append(line1) self.ascii_art[tag].append(line2) def set_line(self, i, s = '', tag = ''): if s == None: s = '' if tag == self.tag[i]: if self.offset[i] > 0: return s = self.tr(s) if s != self.lines[i]: self.lines[i] = s self.offset[i] = -self.wait_time self.tag[i] = tag if self.lines[0] == '' and self.lines[1] == '': if self.easter_egg_countdown < 0: self.easter_egg_countdown = random.randrange(self.timeoutmin, self.timeoutmax) self.animation_index = self.ascii_art.keys()[random.randrange(0, len(self.ascii_art))] self.animation_phase = 0 else: self.easter_egg_countdown = -1 def set_paused(self, paused): self.paused = paused def set_busy(self, busy): self.busy = busy def set_elapsed(self, elapsed): self.elapsed = elapsed def render(self): result_lines = [] if self.easter_egg_countdown > 0: self.easter_egg_countdown -= 1 if self.easter_egg_countdown == 0: # animation for i in range(2): offset = -len(self.ascii_art[self.animation_index][i]) + self.animation_phase frames = len(self.ascii_art[self.animation_index]) / 2 part = self.ascii_art[self.animation_index][i + (2 * (self.animation_phase % frames))] if offset < 0: part = part[-offset:] else: part = (' ' * offset) + part part += ' ' * self.width part = part[:self.width] result_lines.append(part) if (offset > self.width): self.easter_egg_countdown = random.randrange(self.timeoutmin, self.timeoutmax) self.animation_index = self.ascii_art.keys()[random.randrange(0, len(self.ascii_art))] self.animation_phase = 0 self.animation_phase = self.animation_phase + 1 else: # print lines for i in range(self.height): line = self.lines[i] cropped = line if len(line) > self.width: cropped += self.separator cropped += line offset = self.offset[i] if offset < 0: offset = 0 cropped += ' ' * self.width cropped = cropped[offset:(offset + self.width)] if i == 0: if self.busy: cropped = cropped[:-2] self.busy_loop = (self.busy_loop + 1) % 4 cropped += ' ' cropped += ('/-' + u'\x01'.encode('latin-1') + '|')[self.busy_loop] if i == 1: if self.paused: cropped = cropped[:-2] self.paused_loop = (self.paused_loop + 1) % 4 cropped += ' ' cropped += '.oOo'[self.paused_loop] #else: #if self.elapsed != '': #cropped = cropped[:-(len(self.elapsed) + 2)] #cropped += "|%s" % self.elapsed if i == 0: cropped = cropped[:-2] cropped += ' ' cropped += '"' if i == 1: cropped = cropped[:-2] cropped += ' ' cropped += u'\x02'.encode('latin-1') result_lines.append(cropped) #os.system("clear") #self.lcd.clear() self.lcd.setCursor(0, 0) for index, cropped in enumerate(result_lines): #if cropped != self.current_lines[index]: self.current_lines[index] = cropped self.lcd.message(cropped) #print(cropped) #print(cropped) #print() def animate(self): for i in range(self.height): line = self.lines[i] if len(line) <= self.width: self.offset[i] = 0 else: self.offset[i] += 1 if self.offset[i] == len(line) + len(self.separator): self.offset[i] = -self.wait_time def clear(self): for i in range(self.height): self.set_line(i, '')
#!/usr/bin/env python from Adafruit_CharLCD import Adafruit_CharLCD lcd = Adafruit_CharLCD() lcd.begin(20, 1) lcd.clear() lcd.message("Line 1 Line 1\nLine 2 Line 2\nLine 3 Line 3\nLine 4 Line 4")
class launcher: def __init__(self): # Need a state set for this launcher. self.menu = ["Remote Control"] self.menu += ["Three Point Turn"] self.menu += ["Straight Line Speed"] self.menu += ["Line Following"] self.menu += ["Proximity"] self.menu += ["Quit Challenge"] self.menu += ["Power Off Pi"] self.menu_quit_challenge = 3 # default menu item is remote control self.menu_state = 0 self.menu_button_pressed = False self.drive = None self.wiimote = None # Current Challenge self.challenge = None self.challenge_name = "" GPIO.setwarnings(False) self.GPIO = GPIO # LCD Display self.lcd = Adafruit_CharLCD( pin_rs=25, pin_e=24, pins_db=[23, 17, 27, 22], GPIO=self.GPIO ) self.lcd.begin(16, 1) self.lcd.clear() self.lcd.message('Initiating...') self.lcd_loop_skip = 5 # Shutting down status self.shutting_down = False def menu_item_selected(self): """Select the current menu item""" # If ANYTHING selected, we gracefully # kill any challenge threads open self.stop_threads() if self.menu[self.menu_state]=="Remote Control": # Start the remote control logging.info("Entering into Remote Control Mode") self.challenge = rc.rc(self.drive, self.wiimote) # Create and start a new thread running the remote control script self.challenge_thread = threading.Thread(target=self.challenge.run) self.challenge_thread.start() # Ensure we know what challenge is running if self.challenge: self.challenge_name = self.menu[self.menu_state] # Move menu index to quit challenge by default self.menu_state = self.menu_quit_challenge elif self.menu[self.menu_state]=="Three Point Turn": # Start the three point turn challenge logging.info("Starting Three Point Turn Challenge") self.challenge = ThreePointTurn(self.drive) # Create and start a new thread running the remote control script self.challenge_thread = threading.Thread(target=self.challenge.run) self.challenge_thread.start() # Ensure we know what challenge is running if self.challenge: self.challenge_name = self.menu[self.menu_state] # Move menu index to quit challenge by default self.menu_state = self.menu_quit_challenge elif self.menu[self.menu_state]=="Straight Line Speed": # Start the straight line speed challenge logging.info("Starting Straight Line Speed Challenge") self.challenge = StraightLineSpeed(self.drive) # Ensure we know what challenge is running if self.challenge: self.challenge_name = self.menu[self.menu_state] # Move menu index to quit challenge by default self.menu_state = self.menu_quit_challenge elif self.menu[self.menu_state]=="Line Following": # Start the Line Following challenge logging.info("Starting Line Following Challenge") self.challenge = LineFollowing(self.drive) # Ensure we know what challenge is running if self.challenge: self.challenge_name = self.menu[self.menu_state] # Move menu index to quit challenge by default self.menu_state = self.menu_quit_challenge elif self.menu[self.menu_state]=="Proximity": # Start the Proximity challenge logging.info("Starting Proximity Challenge") self.challenge = Proximity(self.drive) # Ensure we know what challenge is running if self.challenge: self.challenge_name = self.menu[self.menu_state] # Move menu index to quit challenge by default self.menu_state = self.menu_quit_challenge elif self.menu[self.menu_state]=="Quit Challenge": # Reset menu item back to top of list self.menu_state = 0 logging.info("No Challenge Challenge Thread") elif self.menu[self.menu_state]=="Power Off Pi": # Power off the raspberry pi safely # by sending shutdown command to terminal logging.info("Shutting Down Pi") os.system("sudo shutdown -h now") self.shutting_down = True def set_neutral(self, drive, wiimote): """Simple method to ensure motors are disabled""" if drive: drive.set_neutral() drive.disable_drive() if wiimote is not None: # turn on leds on wii remote wiimote.led = 2 def set_drive(self, drive, wiimote): """Simple method to highlight that motors are enabled""" if wiimote is not None: # turn on leds on wii remote #turn on led to show connected drive.enable_drive() wiimote.led = 1 def stop_threads(self): """Method neatly closes any open threads started by this class""" if self.challenge: self.challenge.stop() self.challenge = None self.challenge_thread = None logging.info("Stopping Challenge Thread") else: logging.info("No Challenge Challenge Thread") # Safety setting self.set_neutral(self.drive, self.wiimote) def run(self): """ Main Running loop controling bot mode and menu state """ # Tell user how to connect wiimote self.lcd.clear() self.lcd.message( 'Press 1+2 \n' ) self.lcd.message( 'On Wiimote' ) # Initiate the drivetrain self.drive = drivetrain.DriveTrain(pwm_i2c=0x40) self.wiimote = None try: self.wiimote = Wiimote() except WiimoteException: logging.error("Could not connect to wiimote. please try again") if not self.wiimote: # Tell user how to connect wiimote self.lcd.clear() self.lcd.message( 'Wiimote \n' ) self.lcd.message( 'Not Found' + '\n' ) # Constantly check wiimote for button presses loop_count = 0 while self.wiimote: buttons_state = self.wiimote.get_buttons() nunchuk_buttons_state = self.wiimote.get_nunchuk_buttons() joystick_state = self.wiimote.get_joystick_state() # logging.info("joystick_state: {0}".format(joystick_state)) # logging.info("button state {0}".format(buttons_state)) # Always show current menu item # logging.info("Menu: " + self.menu[self.menu_state]) if loop_count >= self.lcd_loop_skip: # Reset loop count if over loop_count = 0 self.lcd.clear() if self.shutting_down: # How current menu item on LCD self.lcd.message( 'Shutting Down Pi' + '\n' ) else: # How current menu item on LCD self.lcd.message( self.menu[self.menu_state] + '\n' ) # If challenge is running, show it on line 2 if self.challenge: self.lcd.message( '[' + self.challenge_name + ']' ) # Increment Loop Count loop_count = loop_count + 1 # Test if B button is pressed if joystick_state is None or (buttons_state & cwiid.BTN_B) or (nunchuk_buttons_state & cwiid.NUNCHUK_BTN_Z): # No nunchuk joystick detected or B or Z button # pressed, must go into neutral for safety logging.info("Neutral") self.set_neutral(self.drive, self.wiimote) else: # Enable motors self.set_drive(self.drive, self.wiimote) if ((buttons_state & cwiid.BTN_A) or (buttons_state & cwiid.BTN_UP) or (buttons_state & cwiid.BTN_DOWN)): # Looking for state change only if not self.menu_button_pressed and (buttons_state & cwiid.BTN_A): # User wants to select a menu item self.menu_item_selected() elif not self.menu_button_pressed and (buttons_state & cwiid.BTN_UP): # Decrement menu index self.menu_state = self.menu_state - 1 if self.menu_state < 0: # Loop back to end of list self.menu_state = len(self.menu)-1 logging.info("Menu item: {0}".format(self.menu[self.menu_state])) elif not self.menu_button_pressed and (buttons_state & cwiid.BTN_DOWN): # Increment menu index self.menu_state = self.menu_state + 1 if self.menu_state >= len(self.menu): # Loop back to start of list self.menu_state = 0 logging.info("Menu item: {0}".format(self.menu[self.menu_state])) # Only change button state AFTER we have used it self.menu_button_pressed = True else: # No menu buttons pressed self.menu_button_pressed = False time.sleep(0.05)
class HashTagDisplay(): def __init__(self, cols, rows, delay, debug=False): # number of columns on the character LCD (min: 16, max: 20) self.cols = cols # number of rows on the character LCD (min: 1, max: 4) self.rows = rows # duration in seconds to allow human to read LCD lines self.delay = delay # print messages to shell for debugging self.debug = debug if debug == True: print " cols = {0}".format(cols) print " rows = {0}".format(rows) print "delay = {0}".format(delay) self.lcd = Adafruit_CharLCD() self.lcd.begin(cols, rows) def search(self, hashtag): """ search for tweets with specified hashtag """ twitter_search = Twitter(domain="search.twitter.com") return twitter_search.search(q=hashtag) def display(self, results): """ Display each tweet in the twitter search results """ for tweet in results.get('results'): msg = "@" + tweet.get('from_user') + ": " + tweet.get('text') if self.debug == True: print "msg: " + msg # break tweet into lines the width of LCD lines = textwrap.wrap(msg, self.cols) self.printLines(lines) def printLines(self, lines): """ display each line of the tweet """ i = 0 while i < lines.__len__(): self.lcd.clear() # print line to each LCD row for row in range(self.rows): # display line on current LCD row self.lcd.setCursor(0,row) self.lcd.message(lines[i]) i=i+1 # 200ms delay is now only for visual effect # initially added the delay to avoid issue # where garbage characters were displayed: # https://github.com/adafruit/Adafruit-Raspberry-Pi-Python-Code/pull/13 sleep(0.2) # no more lines remaining for this tweet if i >= lines.__len__(): # sleep according to the number of rows displayed row_delay = self.delay / float(self.rows) delay = row_delay * (row+1) if(delay < 1): delay = 1 sleep(delay) break # pause to allow human to read displayed rows if(row+1 >= self.rows): sleep(self.delay)
def mess(): lcd = Adafruit_CharLCD() lcd.begin(16, 2) lcd.clear() lcd.message("I am Lost. Contact 9986521450")
#lcdPingometer.py #################### from Adafruit_CharLCD import Adafruit_CharLCD from subprocess import * from time import sleep, strftime from datetime import datetime lcd = Adafruit_CharLCD() #make an object called lcd #the script to be executed #this will ping google.com (8.8.8.8) take the response time from the output cmd = "sudo ping -c 1 8.8.8.8 | grep time= | awk '{print $7}'" #start up the lcd screen lcd.begin(16, 1) #the function that will take the cmd string and execute it as a command def run_cmd(cmd): p = Popen(cmd, shell=True, stdout=PIPE) output = p.communicate()[0] return output while 1: pingCmd = run_cmd(cmd) #execute cmd and assign output to pingcmd strLength = len(pingCmd) #get the amount of characters in pingcmd print strLength print pingCmd
# 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 # RS, E, [Data] lcd = Adafruit_CharLCD(14, 15, [17,18,27,22]) btn = Buttons("lcdmenu", "/home/pi/.lircrc") # 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) # commands def DoQuit(): lcd.clear() lcd.message('Are you sure?\nPress Sel for Y') while 1: nb = btn.readButton() if nb == 'left': break; if nb == 'sel': lcd.clear() quit() sleep(0.25) def DoShutdown():
#!/usr/bin/python import time from Adafruit_CharLCD import Adafruit_CharLCD from time import sleep, strftime from datetime import datetime lcd = Adafruit_CharLCD() lcd.clear() lcd.backlightOn() lcd.begin(16, 4) lcd.setCursor(0, 0) lcd.message(datetime.now().strftime('%b %d %H:%M\n')) lcd.setCursor(0, 1) lcd.message('hello')
class SkyPi: def __init__(self): self.FSM = SkyPi_FSM() # flags self.redraw_flag = True self.wifi_mode_adhoc_flag = False # setup LCD screen self.lcd = Adafruit_CharLCD() self.lcd.begin(16, 2) self.lcd.clear() self.lcd.message("Start SkyPi_LCDd\n") # setup datetime self.time_state = True self.time_str_fmt = ' %m/%d %H:%M' self.datetime_str=datetime.now().strftime(self.time_str_fmt) # gps self.gps = SkyPi_GPS(SP_CFG.DT_GPS_CHECK) # net self.net = SkyPi_NET() # setup GPIOs GPIO.setmode(GPIO.BCM) GPIO.setup(SP_CFG.PIN_BUTTON_HC_SETUP, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.setup(SP_CFG.PIN_SWITCH_ADHOC_MODE, GPIO.IN, pull_up_down=GPIO.PUD_UP) def Show_GPS_IP(self): # gps status self._show_gps_status() # time self._show_time() # ip self._show_ip() # reset redraw_flag self.redraw_flag = False # monitor button self.check_buttons() def Change_WiFi_Mode(self,mode): if mode == 'A': self.net.switch_to_AdHoc() elif mode == 'M': self.net.switch_to_Managed() def Setup_HC(self): self.lcd.clear() self.lcd.setCursor(0,0) self.lcd.message('Button pressed\n') sleep(1) self.lcd.clear() self.lcd.setCursor(0,0) lat,lon,status = self.gps.get_location() self.lcd.message('S:%2d lat:%g' % (status,lat)) self.lcd.setCursor(0,1) self.lcd.message(' lon:%g' % lon) self.redraw_flag = True sleep(2) self.lcd.clear() def check_buttons(self): if GPIO.input(SP_CFG.PIN_BUTTON_HC_SETUP) == False: self.Setup_HC() if GPIO.input(SP_CFG.PIN_SWITCH_ADHOC_MODE) == False: if not self.wifi_mode_adhoc_flag: self.Change_WiFi_Mode('A') self.wifi_mode_adhoc_flag = True else: if self.wifi_mode_adhoc_flag: self.Change_WiFi_Mode('M') self.wifi_mode_adhoc_flag = False def _show_gps_status(self): """ show GPS status """ if ( self.gps.check_gps() or self.redraw_flag ): # show GPS info on LCD self.lcd.setCursor(0,0) self.lcd.message(self.gps.gps_status_str()) def _show_ip(self): local_redraw_flag = False # if address has changed if ( self.net.check_net() or self.redraw_flag ): # clear previous IP self.lcd.setCursor(0,1) self.lcd.message(16*' ') # new IP self.lcd.setCursor(0,1) self.lcd.message(self.net.net_status_str()) def _show_time(self): current_datetime_str=datetime.now().strftime(self.time_str_fmt) if ( current_datetime_str != self.datetime_str or self.redraw_flag ): self.datetime_str = current_datetime_str self.lcd.setCursor(3,0) self.lcd.message(self.datetime_str) # blinking ":" self.time_state = not self.time_state self.lcd.setCursor(15,0) if self.time_state: self.lcd.message(':') else: self.lcd.message(' ')
# COSM variables. API_KEY = '5o99TlXGJ02f0kPWzS1Erb822VNiYYvleurjm2PwHXFyyAsR' FEED = 984389260 API_URL = '/v2/feeds/{feednum}.xml'.format(feednum=FEED) GLOBAL_TMP = 0.0 GLOBAL_LIGHT = 0.0 GLOBAL_PRESSURE = 0.0 GLOBAL_ALTITUDE = 0.0 #XIVELY_DATA_BUFFER = [] BufferCount = 0 lcd = Adafruit_CharLCD() lcd.begin(20, 4) if __name__ == '__main__': print "\n" print "Welcome to Matt's SensorNet" print "---------------------------------------------------------" print "....monitoring..." while True: GLOBAL_TMP = TMP_SCRIPT.sensorFunc() GLOBAL_LIGHT = LIGHT_SCRIPT.sensorFunc() GLOBAL_PRESSURE = PRESSURE_SCRIPT.sensorFunc() lcd.clear() lcd.message(
#!/usr/bin/python from Adafruit_CharLCD import Adafruit_CharLCD from subprocess import Popen, PIPE from time import sleep from datetime import datetime lcd = Adafruit_CharLCD() cmd = "ip addr show eth0 | grep inet | awk '{print $2}' | cut -d/ -f1" lcd.begin(16, 4) def run_cmd(cmd): p = Popen(cmd, shell=True, stdout=PIPE) output = p.communicate()[0] return output while 1: lcd.home() ipaddr = run_cmd(cmd) lcd.message(datetime.now().strftime('%b %d %H:%M:%S\n')) lcd.message('IP %s\n' % (ipaddr)) sleep(1)
class launcher: def __init__(self): # Need a state set for this launcher. self.menu = ["Remote Control"] self.menu += ["Three Point Turn"] self.menu += ["Straight Line Speed"] self.menu += ["Line Following"] self.menu += ["Proximity"] self.menu += ["Quit Challenge"] self.menu += ["Power Off Pi"] self.menu_quit_challenge = 3 # default menu item is remote control self.menu_state = 0 self.menu_button_pressed = False self.drive = None self.wiimote = None # Current Challenge self.challenge = None self.challenge_name = "" GPIO.setwarnings(False) self.GPIO = GPIO # LCD Display self.lcd = Adafruit_CharLCD(pin_rs=25, pin_e=24, pins_db=[23, 17, 27, 22], GPIO=self.GPIO) self.lcd.begin(16, 1) self.lcd.clear() self.lcd.message('Initiating...') self.lcd_loop_skip = 5 # Shutting down status self.shutting_down = False def menu_item_selected(self): """Select the current menu item""" # If ANYTHING selected, we gracefully # kill any challenge threads open self.stop_threads() if self.menu[self.menu_state] == "Remote Control": # Start the remote control logging.info("Entering into Remote Control Mode") self.challenge = rc.rc(self.drive, self.wiimote) # Create and start a new thread running the remote control script self.challenge_thread = threading.Thread(target=self.challenge.run) self.challenge_thread.start() # Ensure we know what challenge is running if self.challenge: self.challenge_name = self.menu[self.menu_state] # Move menu index to quit challenge by default self.menu_state = self.menu_quit_challenge elif self.menu[self.menu_state] == "Three Point Turn": # Start the three point turn challenge logging.info("Starting Three Point Turn Challenge") self.challenge = ThreePointTurn(self.drive) # Create and start a new thread running the remote control script self.challenge_thread = threading.Thread(target=self.challenge.run) self.challenge_thread.start() # Ensure we know what challenge is running if self.challenge: self.challenge_name = self.menu[self.menu_state] # Move menu index to quit challenge by default self.menu_state = self.menu_quit_challenge elif self.menu[self.menu_state] == "Straight Line Speed": # Start the straight line speed challenge logging.info("Starting Straight Line Speed Challenge") self.challenge = StraightLineSpeed(self.drive) # Ensure we know what challenge is running if self.challenge: self.challenge_name = self.menu[self.menu_state] # Move menu index to quit challenge by default self.menu_state = self.menu_quit_challenge elif self.menu[self.menu_state] == "Line Following": # Start the Line Following challenge logging.info("Starting Line Following Challenge") self.challenge = LineFollowing(self.drive) # Ensure we know what challenge is running if self.challenge: self.challenge_name = self.menu[self.menu_state] # Move menu index to quit challenge by default self.menu_state = self.menu_quit_challenge elif self.menu[self.menu_state] == "Proximity": # Start the Proximity challenge logging.info("Starting Proximity Challenge") self.challenge = Proximity(self.drive) # Ensure we know what challenge is running if self.challenge: self.challenge_name = self.menu[self.menu_state] # Move menu index to quit challenge by default self.menu_state = self.menu_quit_challenge elif self.menu[self.menu_state] == "Quit Challenge": # Reset menu item back to top of list self.menu_state = 0 logging.info("No Challenge Challenge Thread") elif self.menu[self.menu_state] == "Power Off Pi": # Power off the raspberry pi safely # by sending shutdown command to terminal logging.info("Shutting Down Pi") os.system("sudo shutdown -h now") self.shutting_down = True def set_neutral(self, drive, wiimote): """Simple method to ensure motors are disabled""" if drive: drive.set_neutral() drive.disable_drive() if wiimote is not None: # turn on leds on wii remote wiimote.led = 2 def set_drive(self, drive, wiimote): """Simple method to highlight that motors are enabled""" if wiimote is not None: # turn on leds on wii remote #turn on led to show connected drive.enable_drive() wiimote.led = 1 def stop_threads(self): """Method neatly closes any open threads started by this class""" if self.challenge: self.challenge.stop() self.challenge = None self.challenge_thread = None logging.info("Stopping Challenge Thread") else: logging.info("No Challenge Challenge Thread") # Safety setting self.set_neutral(self.drive, self.wiimote) def run(self): """ Main Running loop controling bot mode and menu state """ # Tell user how to connect wiimote self.lcd.clear() self.lcd.message('Press 1+2 \n') self.lcd.message('On Wiimote') # Initiate the drivetrain self.drive = drivetrain.DriveTrain(pwm_i2c=0x40) self.wiimote = None try: self.wiimote = Wiimote() except WiimoteException: logging.error("Could not connect to wiimote. please try again") if not self.wiimote: # Tell user how to connect wiimote self.lcd.clear() self.lcd.message('Wiimote \n') self.lcd.message('Not Found' + '\n') # Constantly check wiimote for button presses loop_count = 0 while self.wiimote: buttons_state = self.wiimote.get_buttons() nunchuk_buttons_state = self.wiimote.get_nunchuk_buttons() joystick_state = self.wiimote.get_joystick_state() # logging.info("joystick_state: {0}".format(joystick_state)) # logging.info("button state {0}".format(buttons_state)) # Always show current menu item # logging.info("Menu: " + self.menu[self.menu_state]) if loop_count >= self.lcd_loop_skip: # Reset loop count if over loop_count = 0 self.lcd.clear() if self.shutting_down: # How current menu item on LCD self.lcd.message('Shutting Down Pi' + '\n') else: # How current menu item on LCD self.lcd.message(self.menu[self.menu_state] + '\n') # If challenge is running, show it on line 2 if self.challenge: self.lcd.message('[' + self.challenge_name + ']') # Increment Loop Count loop_count = loop_count + 1 # Test if B button is pressed if joystick_state is None or (buttons_state & cwiid.BTN_B) or ( nunchuk_buttons_state & cwiid.NUNCHUK_BTN_Z): # No nunchuk joystick detected or B or Z button # pressed, must go into neutral for safety logging.info("Neutral") self.set_neutral(self.drive, self.wiimote) else: # Enable motors self.set_drive(self.drive, self.wiimote) if ((buttons_state & cwiid.BTN_A) or (buttons_state & cwiid.BTN_UP) or (buttons_state & cwiid.BTN_DOWN)): # Looking for state change only if not self.menu_button_pressed and (buttons_state & cwiid.BTN_A): # User wants to select a menu item self.menu_item_selected() elif not self.menu_button_pressed and (buttons_state & cwiid.BTN_UP): # Decrement menu index self.menu_state = self.menu_state - 1 if self.menu_state < 0: # Loop back to end of list self.menu_state = len(self.menu) - 1 logging.info("Menu item: {0}".format( self.menu[self.menu_state])) elif not self.menu_button_pressed and (buttons_state & cwiid.BTN_DOWN): # Increment menu index self.menu_state = self.menu_state + 1 if self.menu_state >= len(self.menu): # Loop back to start of list self.menu_state = 0 logging.info("Menu item: {0}".format( self.menu[self.menu_state])) # Only change button state AFTER we have used it self.menu_button_pressed = True else: # No menu buttons pressed self.menu_button_pressed = False time.sleep(0.05)
from Adafruit_CharLCD import Adafruit_CharLCD import time import RPi.GPIO as GPIO import pygame.mixer pygame.mixer.init() Music= pygame.mixer.Sound("") MusicList = ["Ylvis- What The Fox Say- Lyrics.wav", "David Bowie Starman Lyrics.wav", "Queen - 'Bohemian Rhapsody'.wav"] AlarmMusicList= [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] lcd = Adafruit_CharLCD() lcd.begin(20, 4) buttonUp = 11 buttonDown = 13 buttonEnter = 15 buttonBack = 37 GPIO.setmode(GPIO.BOARD) Button = [11, 13, 15, 37] for x in Button: GPIO.setup(x, GPIO.IN, GPIO.PUD_UP) time_stamp_0 = time.time() time_stamp_1 = time.time() time_stamp_2 = time.time() time_stamp_3 = time.time() screen = 0
from Adafruit_CharLCD import Adafruit_CharLCD as CharLCD DURATION = 30 START_POSITION = 14 # Have the text scroll left. Adjust for LCD size current_time = lambda: int(round(time.time())) start_time = current_time() msg = 'CODERDOJO\nMINHO' split = msg.split('\n') position = START_POSITION max_len = max(len(split[0]), len(split[1])) lcd = CharLCD(pin_rs=2, pin_e=4, pins_db=[3, 14, 25, 24]) lcd.clear() lcd.begin(16, 2) lcd.setCursor(14, 0) lcd.message(split[0]) lcd.setCursor(14, 1) lcd.message(split[1]) while current_time() < start_time + DURATION: lcd.DisplayLeft() position = (position + 1) % max_len time.sleep(.3) for x in range(position, START_POSITION + max_len): lcd.DisplayLeft() time.sleep(.3) lcd.clear()
class HashTagDisplay(): def __init__(self, cols, rows, delay, debug=False): # number of columns on the character LCD (min: 16, max: 20) self.cols = cols # number of rows on the character LCD (min: 1, max: 4) self.rows = rows # duration in seconds to allow human to read LCD lines self.delay = delay # print messages to shell for debugging self.debug = debug if debug == True: print " cols = {0}".format(cols) print " rows = {0}".format(rows) print "delay = {0}".format(delay) self.lcd = Adafruit_CharLCD() self.lcd.begin(cols, rows) def search(self, hashtag): """ search for tweets with specified hashtag """ twitter_search = Twitter(domain="search.twitter.com") return twitter_search.search(q=hashtag) def display(self, results): """ Display each tweet in the twitter search results """ for tweet in results.get('results'): msg = "@" + tweet.get('from_user') + ": " + tweet.get('text') if self.debug == True: print "msg: " + msg # break tweet into lines the width of LCD lines = textwrap.wrap(msg, self.cols) self.printLines(lines) def printLines(self, lines): """ display each line of the tweet """ i = 0 while i < lines.__len__(): self.lcd.clear() # print line to each LCD row for row in range(self.rows): # display line on current LCD row self.lcd.setCursor(0, row) self.lcd.message(lines[i]) i = i + 1 # 200ms delay is now only for visual effect # initially added the delay to avoid issue # where garbage characters were displayed: # https://github.com/adafruit/Adafruit-Raspberry-Pi-Python-Code/pull/13 sleep(0.2) # no more lines remaining for this tweet if i >= lines.__len__(): # sleep according to the number of rows displayed row_delay = self.delay / float(self.rows) delay = row_delay * (row + 1) if (delay < 1): delay = 1 sleep(delay) break # pause to allow human to read displayed rows if (row + 1 >= self.rows): sleep(self.delay)
# 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 # RS, E, [Data] lcd = Adafruit_CharLCD(14, 15, [17, 18, 27, 22]) btn = Buttons("lcdmenu", "/home/pi/.lircrc") # 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) # commands def DoQuit(): lcd.clear() lcd.message('Are you sure?\nPress Sel for Y') while 1: nb = btn.readButton() if nb == 'left': break if nb == 'sel': lcd.clear() quit() sleep(0.25)
timeoutdisplayblocks = 0 for control in config['interface']['controls']: ctrlid = control['id'] controldefs[ctrlid] = control sortedlist = [ctrlid for ctrlid in config['local']['controls']] sortedlist.sort() for ctrlid in sortedlist: dispdef = config['local']['controls'][ctrlid]['display'] if dispdef['type'] == 'hd44780': newlcd = Adafruit_CharLCD() newlcd.pin_e = dispdef['pin'] GPIO.setup(newlcd.pin_e, GPIO.OUT) GPIO.output(newlcd.pin_e, GPIO.LOW) newlcd.begin(dispdef['width'], dispdef['height']) lcd[ctrlid]=newlcd print("Control " + ctrlid + " is hd44780 on pin " + newlcd.pin_e) else: newlcd = NokiaLCD(pin_SCE=dispdef['pin']) lcd[ctrlid]=newlcd print("Control " + ctrlid + " is nokia on pin " + dispdef['pin']) hardwaretype = config['local']['controls'][ctrlid]['hardware'] if hardwaretype != 'instructions': pins = config['local']['controls'][ctrlid]['pins'] if hardwaretype == 'phonestylemenu': # 2 buttons, RGB LED GPIO.setup(pins['BTN_1'], GPIO.IN, GPIO.PUD_DOWN) GPIO.setup(pins['BTN_2'], GPIO.IN, GPIO.PUD_DOWN) PWM.start(pins['RGB_R'], 0.0) PWM.start(pins['RGB_G'], 0.0) PWM.start(pins['RGB_B'], 0.0)
lines = read_temp_raw() # this is actual process of reading temperature from sensor, and processing it, while lines[0].strip()[-3:] != 'YES': time.sleep(0.2) lines = read_temp_raw() equals_pos = lines[1].find('t=') if equals_pos != -1: temp_string = lines[1][equals_pos+2:] temp_c = float(temp_string) / 1000.0 temp_f = temp_c * 9.0 / 5.0 + 32.0 return temp_c, temp_f ########################################################################### sensor = Adafruit_DHT.DHT22 pin = 22 lcd = Adafruit_CharLCD() lcd.begin(16, 2) lcd.clear() # Define some constants from the datasheet DEVICE = 0x23 # Default device I2C address POWER_DOWN = 0x00 # No active state POWER_ON = 0x01 # Power on RESET = 0x07 # Reset data register value # Start measurement at 1lx resolution. Time typically 120ms # Device is automatically set to Power Down after measurement. ONE_TIME_HIGH_RES_MODE_1 = 0x20 bus = smbus.SMBus(1) # Rev 2 Pi uses 1
#!/usr/bin/env python from Adafruit_CharLCD import Adafruit_CharLCD from time import sleep, strftime from datetime import datetime lcd = Adafruit_CharLCD() lcd.begin(20, 1) while 1: lcd.clear() lcd.message(datetime.now().strftime('%Y-%m-%d %p %I:%M\n')) sleep(60)
#!/usr/bin/python # -*- coding: utf-8 -*- from Adafruit_CharLCD import Adafruit_CharLCD from subprocess import * from time import sleep, strftime from datetime import datetime lcd = Adafruit_CharLCD() file = "/sys/bus/w1/devices/123-123456789/w1_slave" lcd.begin(16,1) def get_temp(file): #Open file written to by temp sensor tfile = open(file) #read all text in file text = tfile.read() #Close file once text is read tfile.close() #pull out the temperature value temperaturedata = text.split("\n")[1].split(" ")[9] # The first two characters are "t=", so get rid of those and convert the temperature from a string to a number. temperature = float(temperaturedata[2:]) # Put the decimal point in the right place and display it.
def Init() : lcd = Adafruit_CharLCD() lcd.begin( 16, 2 ) return lcd