def print_to_lcd(): """ Print values to a 2x16 LCD display if it is provided with connections described """ lcd = Adafruit_CharLCD(rs=26, en=19, d4=13, d5=6, d6=5, d7=21, cols=16, lines=2) lcd.clear() lcd.set_cursor(0, 0) lcd.message("DHT22 Program") lcd.set_cursor(0, 1) lcd.message("Waiting...") sleep(2) try: while True: hum, temp = get_values() lcd.clear() lcd.set_cursor(0, 0) lcd.message("Temp: {0:.2f} C".format(temp)) lcd.set_cursor(0, 1) lcd.message("Humi: {0:.2f} %".format(hum)) sleep(5) except KeyboardInterrupt: print('Exiting...') lcd.clear() lcd.set_cursor(0, 0) lcd.message("OFFLINE")
class LcdManager(object): def __init__(self): logging.info('Create LcdManager instance') self.running = False self.line1 = '' self.line2 = '' self.screen = Adafruit_CharLCD() self.spinner_state = 0 return def get_process_spinner(self): if self.spinner_state == 0: self.spinner_state += 1 return '. ' elif self.spinner_state == 1: self.spinner_state += 1 return '.. ' else: self.spinner_state = 0 return '... ' def set_line1(self, text): self.line1 = text message = self.line1 message += ' ' * (16 - len(self.line1)) self.screen.message(message) last_line1 = self.line1 def set_line2(self, text): self.line2 = text message = self.line2 message += ' ' * (16 - len(self.line2)) self.screen.message("\n" + message) last_line2 = self.line2
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 GUI(object): def __init__(self, rPI = True): self.rPI = rPI self.PUSH_BUTTONS = (17, 27, 22, 23) self.RDY = 24 self.RST = 25 if self.rPI: import RPi.GPIO as GPIO from Adafruit_CharLCD import Adafruit_CharLCD self.GPIO = GPIO self.lcd = Adafruit_CharLCD() GPIO.setwarnings(False) GPIO.setmode(GPIO.BCM) GPIO.setup(self.RDY, GPIO.OUT) #self.setRDYstate(1) self.showIntro() #self.setRDYstate(0) GPIO.setup(self.RST, GPIO.OUT) self.sendRST() for i in self.PUSH_BUTTONS: GPIO.setup(i, GPIO.IN) def readPushButtons(self): #Wire pull-down resistors to each Push-Button state = [] for i in self.PUSH_BUTTONS: state.append(self.GPIO.input(i)) time.sleep(0.150) #Debouncing delay for i in range(len(self.PUSH_BUTTONS)): state[i] = self.GPIO.input(self.PUSH_BUTTONS[i]) and state[i] return state def setRDYstate(self, state): self.GPIO.output(self.RDY, state) def setRSTstate(self, state): self.GPIO.output(self.RST, state) def sendRST(self): self.setRSTstate(0) time.sleep(0.01) self.setRSTstate(1) def lcdClear(self): if self.rPI: self.lcd.clear() def lcdMessage(self, msg): if self.rPI: self.lcd.message(msg) def showIntro(self): msg = 'WSN Arquitectura' + '\n' + 'Inicializando...' self.lcdClear() self.lcdMessage(msg) time.sleep(4)
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()
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)
class ScreenComponent(JNTComponent): """ A Screen component for gpio """ def __init__(self, bus=None, addr=None, **kwargs): """ """ oid = kwargs.pop('oid', 'rpilcdchar.screen') name = kwargs.pop('name', "Screen") product_name = kwargs.pop('product_name', "Screen") product_type = kwargs.pop('product_type', "Screen") JNTComponent.__init__(self, oid=oid, bus=bus, addr=addr, name=name, product_name=product_name, product_type=product_type, **kwargs) logger.debug("[%s] - __init__ node uuid:%s", self.__class__.__name__, self.uuid) uuid = "message" self.values[uuid] = self.value_factory['action_string']( options=self.options, uuid=uuid, node_uuid=self.uuid, help='A message to print on the screen', label='Msg', default='Janitoo started', set_data_cb=self.set_message, is_writeonly=True, cmd_class=COMMAND_MOTOR, genre=0x01, ) poll_value = self.values[uuid].create_poll_value(default=300) self.values[poll_value.uuid] = poll_value self.pin_lcd_rs = 27 # Note this might need to be changed to 21 for older revision Pi's. self.pin_lcd_en = 22 self.pin_lcd_d4 = 25 self.pin_lcd_d5 = 24 self.pin_lcd_d6 = 23 self.pin_lcd_d7 = 18 self.pin_lcd_backlight = 4 self.lcd_columns = 20 self.lcd_rows = 4 self.lcd = Adafruit_CharLCD(self.pin_lcd_rs, self.pin_lcd_en, self.pin_lcd_d4, self.pin_lcd_d5, self.pin_lcd_d6, self.pin_lcd_d7, self.lcd_columns, self.lcd_rows, self.pin_lcd_backlight) def set_message(self, node_uuid, index, data): """Set the message on the screen """ try: self.lcd.clear() self.lcd.message(data) except Exception: logger.exception('Exception when displaying message')
class LCD: def __init__(self): self.lcd = Adafruit_CharLCD(25, 24, 23, 17, 21, 22, 16, 2) def data_print(self, msg, a, b): #self.lcd.clear() self.lcd.set_cursor(a, b) self.lcd.message(msg) def lcd_clear(self): self.lcd.clear()
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 print_on_display(message): lcd = Adafruit_CharLCD(rs=26, en=19, d4=13, d5=6, d6=5, d7=11, cols=16, lines=2) lcd.clear() lcd.message(message)
def main(): # now just write the code you would use in a real Raspberry Pi from Adafruit_CharLCD import Adafruit_CharLCD from gpiozero import Buzzer, LED, PWMLED, Button, DistanceSensor, LightSensor, MotionSensor from lirc import init, nextcode from py_irsend.irsend import send_once from time import sleep def show_sensor_values(): lcd.clear() lcd.message( "Distance: %.2fm\nLight: %d%%" % (distance_sensor.distance, light_sensor.value * 100) ) def send_infrared(): send_once("TV", ["KEY_4", "KEY_2", "KEY_OK"]) lcd = Adafruit_CharLCD(2, 3, 4, 5, 6, 7, 16, 2) buzzer = Buzzer(16) led1 = LED(21) led2 = LED(22) led3 = LED(23) led4 = LED(24) led5 = PWMLED(25) led5.pulse() button1 = Button(11) button2 = Button(12) button3 = Button(13) button4 = Button(14) button1.when_pressed = led1.toggle button2.when_pressed = buzzer.on button2.when_released = buzzer.off button3.when_pressed = show_sensor_values button4.when_pressed = send_infrared distance_sensor = DistanceSensor(trigger=17, echo=18) light_sensor = LightSensor(8) motion_sensor = MotionSensor(27) motion_sensor.when_motion = led2.on motion_sensor.when_no_motion = led2.off init("default") while True: code = nextcode() if code != []: key = code[0] lcd.clear() lcd.message(key + "\nwas pressed!") sleep(0.2)
def lcd_write(self, topic, payload): """ This method writes to the LCD """ print(payload['value']) print(type(payload['value'])) lcd = Adafruit_CharLCD(rs=26, en=19, d4=13, d5=6, d6=5, d7=11, cols=16, lines=2) lcd.clear() text = str(payload['value']) lcd.message(text)
class LCD: __line1 = "" __line2 = "" def __init__(self): self.lcd = Adafruit_CharLCD() self.lcd.clear() self.logger = LoggerModule.Logger("LCD Module") def hello(self): self.lcd.message(" Welcome to \n Kinderbox ") def turn_off(self): self.lcd.noDisplay() def display_pause(self): self.message("", "Pause") def display_ready(self): self.message("", "Ready") def display_volume(self, message): self.message("", message) def message(self, line1, line2): if self.__line1 == line1 and self.__line2 == line2: return try: n_line1 = normalization.remove_unicode(line1) except: n_line1 = "unkown" try: n_line2 = normalization.remove_unicode(line2) except: n_line2 = "unkown" self.lcd.clear() sleep(0.5) message = "%s\n%s" %(n_line1,n_line2) self.lcd.message(message) self.__line1 = line1 self.__line2 = line2 def scroll_to_left(self): #Check size message. If over 16 character --> move if len(self.__line1) > 16 or len(self.__line2) > 16: self.lcd.DisplayLeft()
class ScreenComponent(JNTComponent): """ A Screen component for gpio """ def __init__(self, bus=None, addr=None, **kwargs): """ """ oid = kwargs.pop('oid', 'rpilcdchar.screen') name = kwargs.pop('name', "Screen") product_name = kwargs.pop('product_name', "Screen") product_type = kwargs.pop('product_type', "Screen") JNTComponent.__init__(self, oid=oid, bus=bus, addr=addr, name=name, product_name=product_name, product_type=product_type, **kwargs) logger.debug("[%s] - __init__ node uuid:%s", self.__class__.__name__, self.uuid) uuid="message" self.values[uuid] = self.value_factory['action_string'](options=self.options, uuid=uuid, node_uuid=self.uuid, help='A message to print on the screen', label='Msg', default='Janitoo started', set_data_cb=self.set_message, is_writeonly = True, cmd_class=COMMAND_MOTOR, genre=0x01, ) poll_value = self.values[uuid].create_poll_value(default=300) self.values[poll_value.uuid] = poll_value self.pin_lcd_rs = 27 # Note this might need to be changed to 21 for older revision Pi's. self.pin_lcd_en = 22 self.pin_lcd_d4 = 25 self.pin_lcd_d5 = 24 self.pin_lcd_d6 = 23 self.pin_lcd_d7 = 18 self.pin_lcd_backlight = 4 self.lcd_columns = 20 self.lcd_rows = 4 self.lcd = Adafruit_CharLCD(self.pin_lcd_rs, self.pin_lcd_en, self.pin_lcd_d4, self.pin_lcd_d5, self.pin_lcd_d6, self.pin_lcd_d7, self.lcd_columns, self.lcd_rows, self.pin_lcd_backlight) def set_message(self, node_uuid, index, data): """Set the message on the screen """ try: self.lcd.clear() self.lcd.message(data) except Exception: logger.exception('Exception when displaying message')
class MCP23xxxDriver(object): def __init__(self, **kwargs): # Create MCP230xx GPIO adapter. mcp = MCP230XX_GPIO(CONF.lcd.bus, CONF.lcd.address, CONF.lcd.gpio_count) # Create LCD, passing in MCP GPIO adapter. self._lcd = Adafruit_CharLCD(pin_rs=1, pin_e=2, pins_db=[3,4,5,6], GPIO=mcp) self._lcd.clear() def write(self, msg): self.clear() self._lcd.message(msg) def clear(self): self._lcd.clear()
class LCD(object): """ A 16x2 LCD Display """ def __init__(self): """ LCD Constructor """ # Setup LCD self.lcd = Adafruit_CharLCD( rs=12, en=5, d4=6, # Pins are being hardcoded d5=13, d6=19, d7=26, # cols=16, lines=2) # (16x2 LCD) # Clear the LCD self.lcd.clear() def setText(self, message, displayTime=None): """ Set the LCD display text Parameters ---------- message : string The message to be displayed on the LCD displayTime : int,optional The amount of time the message will be displayed If omitted, the message will disappear once the LCD is cleared Returns ------- None """ # Clear the LCD self.lcd.clear() # Set the LCD text self.lcd.message(message) #If displayTime is provided, sleep for 'displayTime' seconds, then clear LCD if displayTime != None: time.sleep(displayTime) self.lcd.clear()
class ScreenWriter(object): """docstring for ScreenWriter.""" def __init__(self, rs, en, d4, d5, d6, d7): """Config.""" self.columns = 16 self.lines = 1 self.lcd = Adafruit_CharLCD(rs, en, d4, d5, d6, d7, self.columns, self.lines) def _direction_to_char(self, dir): return DIR_TO_CHAR[dir] def write_to_lcd(self, value, dir): """Write out to lcd.""" self.lcd.clear() self.lcd.message(str(value) + ' mg/dl\n') self.lcd.message(self._direction_to_char(dir))
class TwoLineLCD(object): def __init__(self, lcd_rs, lcd_en, lcd_d4, lcd_d5, lcd_d6, lcd_d7, lcd_columns, lcd_rows, lcd_backlight): self.lcd = LCD(lcd_rs, lcd_en, lcd_d4, lcd_d5, lcd_d6, lcd_d7, lcd_columns, lcd_rows, lcd_backlight, gpio=aGPIO.get_platform_gpio()) self.lcd.clear() self._columns = lcd_columns self._in_progress = None def clear(self): self.lcd.clear() def cancel(self): if self._in_progress and self._in_progress.active(): self._in_progress.cancel() self.clear() def message(self, line_1, line_2): self.cancel() if len(line_1) > self._columns: line_1 += " " # Padding when scrolling if len(line_2) > self._columns: line_2 += " " # Padding when scrolling self._in_progress = async .DelayedCall(0, self._message, line_1, line_2) def _message(self, line_1, line_2): self.lcd.home() self.lcd.message(line_1[:self._columns] + "\n" + line_2[:self._columns]) if len(line_1) > self._columns: line_1 = rotate(line_1) if len(line_2) > self._columns: line_2 = rotate(line_2) self._in_progress = async .DelayedCall(0.5, self._message, line_1, line_2)
class MCP23xxxDriver(object): def __init__(self, **kwargs): # Create MCP230xx GPIO adapter. mcp = MCP230XX_GPIO(CONF.lcd.bus, CONF.lcd.address, CONF.lcd.gpio_count) # Create LCD, passing in MCP GPIO adapter. self._lcd = Adafruit_CharLCD(pin_rs=1, pin_e=2, pins_db=[3, 4, 5, 6], GPIO=mcp) self._lcd.clear() def write(self, msg): self.clear() self._lcd.message(msg) def clear(self): self._lcd.clear()
class DisplayManager(object): def __init__(self): self.s=Adafruit_CharLCD() self.s.clear() self.__displayText("Welcome") time.sleep(1) self.s.clear() def __displayText(self, strText): self.s.message(strText) def displayText(self, strText): print("Displaying " + strText) if 'none' not in strText.lower(): self.__displayText(strText) elif 'none' in strText.lower(): self.s.clear() else: self.__displayText("Unknown!") self.s.clear()
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
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
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 LCD(text): # instantiate lcd and specify pins lcd = Adafruit_CharLCD(rs=26, en=19, d4=13, d5=6, d6=5, d7=11, cols=16, lines=2) lcd.clear() # display text on LCD display \n = new line lcd.message(text) sleep(3) # scroll text off display for x in range(0, 16): lcd.move_right() sleep(.1) sleep(3) # scroll text on display for x in range(0, 16): lcd.move_left() sleep(.1)
def displayresult(prediction): lcd = Adafruit_CharLCD(rs=26, en=19, d4=13, d5=6, d6=5, d7=11, cols=16, lines=2) lcd.clear() # display text on LCD display \n = new line lcd.message(prediction) sleep(.3) # scroll text off display '''for x in range(0, 16): lcd.move_right() sleep(.1) sleep(3) # scroll text on display for x in range(0, 16): lcd.move_left() sleep(.1)''' sleep(.3)
def dumpLCD(): lcd = Adafruit_CharLCD() lcd.begin(20,4) lcd.clear() lcd.setCursor(0,0) lcd.message("Yay! Treats!") lcd.setCursor(0,1) lcd.message(" ") lcd.setCursor(0,3) lcd.message("Thank you!")
def homescreen(): lcd = Adafruit_CharLCD() lcd.begin(20,4) lcd.clear() lcd.setCursor(0,0) lcd.message("Judd Treat Machine!") lcd.setCursor(0,1) lcd.message("Awaiting Emails!") lcd.setCursor(0,3) lcd.message("Hurry up!")
def run(self): # LCD object lcd = AdaLcd(**params['_lcd_pins']) lcd.clear() URL = params['_url'] client = requests.session() # Retrieve the CSRF token first get = client.get(URL + '/login') # sets cookie login_data = { 'id': params['_permit'], 'password': params['_password'], '_token': re.compile('\"_token\".*value=\"(?P<Value>\w*)\"\>').search( get.text).group('Value') # get the token from text } client.post(URL + '/login', data=login_data, cookies=client.cookies) payment_count = 0 lcd_str = 'Paid:%d. Rem:%d\n%s.' lcd.message( lcd_str % (payment_count, params['_mas_passengers'] - payment_count, '....')) reader = Serial(port=params['_port']) """ TheLoop """ while True: read_val = reader.read(params['_size']) lcd.clear() lcd.message(lcd_str % (payment_count, params['_mas_passengers'] - payment_count, '....')) uid_val = json.loads(read_val[:-2].decode())['UID'] ret = json.loads( client.get(URL + '/transfer/%s/%s/%s' % (uid_val, params['_permit'], params['_cost']), cookies=client.cookies).text) if ret['_status'] == 200: payment_count += 1 lcd.clear() lcd.message(lcd_str % (payment_count, params['_mas_passengers'] - payment_count, ret['_description']))
def run(self): # LCD object lcd = AdaLcd(**params['_lcd_pins']) lcd.clear() URL = params['_url'] client = requests.session() # Retrieve the CSRF token first get = client.get(URL + '/login') # sets cookie login_data = { 'id' : params['_permit'], 'password' : params['_password'], '_token' : re.compile('\"_token\".*value=\"(?P<Value>\w*)\"\>') .search(get.text).group('Value') # get the token from text } client.post(URL+'/login', data=login_data, cookies=client.cookies) payment_count = 0 lcd_str = 'Paid:%d. Rem:%d\n%s.' lcd.message(lcd_str%(payment_count, params['_mas_passengers'] - payment_count, '....')) reader = Serial(port=params['_port']) """ TheLoop """ while True: read_val = reader.read(params['_size']) lcd.clear() lcd.message(lcd_str%(payment_count, params['_mas_passengers'] - payment_count, '....')) uid_val = json.loads(read_val[:-2].decode())['UID'] ret = json.loads(client.get(URL+'/transfer/%s/%s/%s'%(uid_val, params['_permit'], params['_cost']), cookies=client.cookies).text) if ret['_status'] == 200: payment_count += 1 lcd.clear() lcd.message(lcd_str%(payment_count, params['_mas_passengers'] - payment_count, ret['_description']))
# Instantiate LCD Display lcd = Adafruit_CharLCD(lcd_rs, lcd_en, d4, d5, d6, d7, cols, lines, lcd_backlight, invert_polarity=False, gpio=gpio) lcd.clear() lcd.message('Humidity and\nTemperature') lcd.set_backlight(1) while (True): # Try to grab a sensor reading. Use the read_retry method which will retry up # to 15 times to get a sensor reading (waiting 2 seconds between each retry). humidity, temperature = Adafruit_DHT.read_retry(dht_type, dht_pin) # Note that sometimes you won't get a reading and # the results will be null (because Linux can't # guarantee the timing of calls to read the sensor). # If this happens try again! if humidity is not None and temperature is not None: print('Temp={0:0.1f}C Humidity={1:0.1f}%'.format( temperature, humidity)) lcd.clear()
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, '')
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)
import os, time, urllib2, httplib, csv, sys import RPi.GPIO as GPIO from Adafruit_CharLCD import Adafruit_CharLCD lcd = Adafruit_CharLCD() lcd.clear() lcd.message(" EUPRY\n MONITOR") os.system('sudo modprobe w1-gpio') os.system('sudo modprobe w1-therm') time.sleep(10) # wait to give the 1-wire software time to find the connected sensors GPIO.setmode(GPIO.BCM) # Set led pin as out, and turn it of. GPIO.setup(14, GPIO.OUT) # Pin for alarm-LED GPIO.setup(14, GPIO.LOW) GPIO.setup(11, GPIO.OUT) # Pin for Door alarm LED GPIO.setup(11, GPIO.LOW) GPIO.setup(9, GPIO.OUT) # Pin for Power alarm LED GPIO.setup(9, GPIO.LOW) GPIO.setup(10, GPIO.OUT) # Pin for Network-LED GPIO.setup(10, GPIO.LOW) #GPIO.setup(15, GPIO.OUT) # Pin for SCREEN-LED #GPIO.setup(15, GPIO.HIGH) GPIO.setup(18, GPIO.OUT) # Pin for Piezo # Set optocoupler pin as in, where high readings means that a external power source is available. GPIO.setup(8, GPIO.IN) # Pin for Opto-coupler reading GPIO.setup(7, GPIO.IN) # Pin for door sensor reading
#!/usr/bin/python from Adafruit_CharLCD import Adafruit_CharLCD from subprocess import * from time import sleep, strftime from datetime import datetime lcd = Adafruit_CharLCD() cmd = "ip addr show eth0 | grep inet | awk '{print $2}' | cut -d/ -f1" lcd.begin(16,1) def run_cmd(cmd): p = Popen(cmd, shell=True, stdout=PIPE) output = p.communicate()[0] return output try: while 1: lcd.clear() ipaddr = run_cmd(cmd) lcd.message(datetime.now().strftime('%b %d %H:%M:%S\n')) lcd.message('IP %s' % ( ipaddr ) ) sleep(2) except KeyboardInterrupt: lcd.exit()
lcd = Adafruit_CharLCD() cmd = "ip addr show eth0 | grep inet | awk '{print $2}' | cut -d/ -f1" lcd.begin(16, 1) def run_cmd(cmd): p = Popen(cmd, shell=True, stdout=PIPE) output = p.communicate()[0] return output while True: lcd.clear() ipaddr = run_cmd(cmd) lcd.message(' Banpo Bridge \n') lcd.message(' By Jay and Jake') time.sleep(3) #------------------# # Red -> Green #------------------# r_start = 0xFF g_start = 0x00 b_start = 0x00 for s in range(0x00,0xFF): r = r_start - s g = g_start + s
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()
result = updates['result'] for r in result: mensagem = r["message"] if ("text" in mensagem): texto = mensagem['text'] if texto == 'Abrir': led1.on() elif texto == 'Soar alarme': buzzer.beep(n=5, on_time=0.05, off_time=0.1) elif texto == 'Ignorar': pass else: buzzer.beep(n=2, on_time=0.5, off_time=0.5) lcd.clear() lcd.message("Mensagem\nrecebida!") sleep(0.4) lcd.clear() sleep(0.4) lcd.message("Mensagem\nrecebida!") sleep(0.4) lcd.clear() sleep(0.4) texto = tirar_acentos(texto) lcd.message(texto[:16]) sleep(0.5) for i in range(len(texto)-15): lcd.clear() lcd.message(texto[i:16+i]) sleep(0.2)
#!/usr/bin/python from Adafruit_CharLCD import Adafruit_CharLCD from subprocess import * from time import sleep, strftime from datetime import datetime from w1thermsensor import W1ThermSensor lcd = Adafruit_CharLCD() lcd.begin(16, 1) sensor = W1ThermSensor() #temp_k = sensor.get_temperature(W1ThermSensor.KELVIN) #temp_f = sensor.get_temperature(W1ThermSensor.DEGREES_F) #temp_c = sensor.get_temperature(W1ThermSensor.DEGREES_C) lcd.clear() while 1: temp_all = sensor.get_temperatures([W1ThermSensor.DEGREES_C, W1ThermSensor.DEGREES_F]) lcd.message(datetime.now().strftime('%b %d %l:%M %p\n')) lcd.message(' %.1fF %.1fC' % (round(temp_all[1], 1),round(temp_all[0],1))) lcd.home() sleep(0)
#GPIO.setup(25, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) GPIO.output(4,0) GPIO.output(17,0) GPIO.output(18,0) #GPIO.output(24,0) try: while True: GPIO.output(4, GPIO.input(27) ) GPIO.output(17, GPIO.input(22) ) GPIO.output(18, GPIO.input(23) ) #GPIO.output(24, GPIO.input(25) ) if(GPIO.input(27) == 1): lcd.message('Ljubljana ima\n287.347 preb.') sleep(3) lcd.clear() if(GPIO.input(22) == 1): lcd.message('Celje ima 48.901\nprebivalcev') sleep(3) lcd.clear() if(GPIO.input(23) == 1): lcd.message('Maribor ima\n111.735 preb.') sleep(3) lcd.clear() except KeyboardInterrupt: GPIO.cleanup()
#!/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")
try: dewPoint = sht1x.calculate_dew_point(temperature, humidity) except ValueError, msg: print("Error calculating dew point: %s" % msg) # Format time curtime = strftime("%H:%M", localtime()) curdate = strftime("%Y-%m-%d", localtime()) # Setup LCD lcd = Adafruit_CharLCD() lcd.clear() # \xDF = degree symbol for LCD display # Show the data lcd.message("T: {:2.2f}\xDFC H: {:2.2f}%\nD: {:2.2f}\xDFC T: {}".format(temperature, humidity, dewPoint, curtime)) # print("T: {:2.2f}\xC2\xB0C H: {:2.2f}%\nD: {:2.2f}\xB0C T: {}".format(temperature, humidity, dewPoint, curtime)) print("Date: {} Time: {} Temperature: {:2.2f}\xC2\xB0C Humiditiy: {:2.2f}% Dew Point: {:2.2f}\xC2\xB0C".format(curdate, curtime, temperature, humidity, dewPoint)) # Flush output, needed to get output if ran with nohup sys.stdout.flush() if count < totalcount: count += 1 else: count = 0 try: conn = mysql.connector.connect(user=dbuser, password=dbpass, host=dbhost, database=dbname) except mysql.connector.Error as err: if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
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. temperature = temperature / 1000 return temperature while 1: lcd.clear() tempVal = get_temp(file) lcd.message(datetime.now().strftime('%b %d %H:%M:%S\n')) lcd.message('Temp %s C' % ( tempVal ) ) sleep(60)
class Humsie_DisplayThread (threading.Thread): intCurIndex = -1; arrPages = { }; bRunning = False; LCD = False; intTimePerPage = 3; bUpdatingDisplay = False; intColor = -1; arrColors = []; def __init__(self, threadID, name, counter, GPIO=False): threading.Thread.__init__(self) self.threadID = threadID self.name = name self.counter = counter if GPIO == False: self.LCD = Adafruit_CharLCDPlate(); self.arrColors = [self.LCD.RED,self.LCD.GREEN,self.LCD.BLUE,self.LCD.YELLOW,self.LCD.TEAL,self.LCD.VIOLET,self.LCD.WHITE,self.LCD.ON ] self.intColor = 0; else: self.LCD = Adafruit_CharLCD(25, 24, [23, 17, 27, 22], GPIO); def start(self): self.bRunning = True; threading.Thread.start(self) def run(self): while self.bRunning == True: self.intCurIndex += 1; if self.arrPages.has_key(self.intCurIndex) == False: self.intCurIndex = 0; self.displayPage(self.intCurIndex); sleep(self.intTimePerPage); if self.intColor >= 0: self.intColor += 1; if self.intColor >= len(self.arrColors): self.intColor = 0; self.LCD.backlight(self.arrColors[self.intColor]); return def gotoPage(self, index): self.intCurIndex = index; if self.arrPages.has_key(self.intCurIndex) == False: self.intCurIndex = 0; self.displayPage(index) def displayPage(self, index): if self.bUpdatingDisplay == False: if self.arrPages.has_key(index) != False: self.bUpdatingDisplay = True self.LCD.clear() self.LCD.message(self.arrPages[index]) self.bUpdatingDisplay = False return; def setTimePerPage(self, seconds=3): self.intTimePerPage = seconds return self.intTimePerPage def stop(self): self.LCD.clear(); self.bRunning = False return def stopped(self): return self.bRunning def setPage(self, index, line): if self.arrPages[index] != line: self.arrPages[index] = line; if self.intCurIndex == index: self.displayPage(self.intCurIndex); return; def registerPage(self, content = ''): length = len(self.arrPages); self.arrPages[length] = content; return length;
relay2=6 gas = 8 GPIO.setmode(GPIO.BCM) GPIO.setup(5,GPIO.OUT) GPIO.setup(6,GPIO.OUT) GPIO.setup(pir,GPIO.IN) GPIO.setup(gas,GPIO.IN) ############################################################################################ while True: degC,degf=read_temp() degC = round(degC,1) print degC lcd.setCursor(10,1) lcd.message("T:"+str(degC)) lux = readLight() lux = round(lux,2) print "light Level is " + str(lux) + " lx" lcd.setCursor(0,1) lux = round(lux,1) lcd.message("L:"+str(lux)) humidity, temperature = Adafruit_DHT.read_retry(sensor, pin) if humidity is not None and temperature is not None: humidity = round(humidity,2) print "humidity is " + str(humidity) lcd.setCursor(0,0) lcd.message("H:" + str(humidity)) else: print 'Failed to get reading. Try again!' time.sleep(2)
#!/usr/local/bin/python # -*- coding: utf-8 -*- import sys sys.path.append('/home/pi/Adafruit-Raspberry-Pi-Python-Code-legacy/Adafruit_CharLCD') from Adafruit_CharLCD import Adafruit_CharLCD text1 = u'コンニチワ!' text2 = u'RasberryPi デス' text1 = text1.encode('shift-jis') text2 = text2.encode('shift-jis') try: lcd = Adafruit_CharLCD() lcd.clear() lcd.message(text1) lcd.message('\n') lcd.message(text2) finally: print 'cleanup' lcd.GPIO.cleanup()
if (timecomp(starttime, stoptime) == False): GPIO.output(relay, GPIO.HIGH) else: GPIO.output(relay, GPIO.LOW) elif (powerval == 1 and timerswitch == 0): GPIO.output(relay, GPIO.HIGH) else: GPIO.output(relay, GPIO.LOW) lcd.clear() if (co_val > 9.00): lcd.clear() lcd.message("Warning!!!\nC0 > 9 ppm") GPIO.output(buzzer, GPIO.HIGH) time.sleep(2) lcd.clear() lcd.message(fin_message_line1 + "\n" + fin_message_line2) else: lcd.message(fin_message_line1 + "\n" + fin_message_line2) if (aqi >= 900): lcd.clear() lcd.message("Warning!!!\nC02 > 900 ppm") GPIO.output(buzzer, GPIO.HIGH) time.sleep(2) lcd.clear() lcd.message(fin_message_line1 + "\n" + fin_message_line2)
from Adafruit_CharLCD import Adafruit_CharLCD #Getting the instance of the lib lcd = Adafruit_CharLCD() #Input from user msg = raw_input("Enter message to display\n") #Display it on the LCD lcd.message(str(msg)) #You can use other functions in the library #Clearing the display #lcd.clear() #Toggle the text visibility on the LCD #lcd.noDisplay() #Make the text invisible #lcd.display() #Make the text visible #Toggle cursor visibility #lcd.noCursor() #Make the cursor invisible #lcd.cursor() #Make the cursor visible #Blink the cursor #lcd.noBlink() #Disable the cursor blink #lcd.blink() #Make the cursor blink #Position the cursor to the start of the display #lcd.home()
#!/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() while 1: lcd.clear() lcd.message(datetime.now().strftime('%b %d %H:%M:%S\n')) sleep(2)
#!/usr/bin/python from Adafruit_CharLCD import Adafruit_CharLCD lcd = Adafruit_CharLCD() lcd.begin(16, 2) lcd.clear() lcd.message("STOP SkyPi_LCDd\n") sleep(2)
lcd.message("\n~~~~~~~~~~~~~~~~") FPS.delay(0.5) digit = kp.getKey() if digit == 0: lcd.clear() lcd.message("POWER OPTIONS\nOFF=1 | RSET=2") FPS.delay(0.5) digit = kp.getKey() POWERFUNC(digit) else: lcd.clear() lcd.message("Invalid Input\nTry Again") time.sleep(1.5) print digit # return digit fps.SetLED(False) FPS.delay(1) fps.Close() lcd.clear() lcd.message(datetime.now().strftime("%b %d %H:%M:%S\n")) lcd.message("Press * to Start") keypay = keypad() diggity = None while diggity != "*": diggity = keypay.getKey() while 1: main()
if received is not None: # Received data, print it out. print('Received: {0}'.format(received)) else: # Timeout waiting for data, None is returned. print('Received no data!') finally: # Make sure device is disconnected on exit. device.disconnect() ## lcd_green() lcd.clear() lcd.message("Starting Up") #RMotor.run(Adafruit_MotorHAT.FORWARD) #LMotor.run(Adafruit_MotorHAT.FORWARD) panel() #climate() ble.initialize() ble.run_mainloop_with(main) lcd.message(received) #while (True): # pwr() # panel() # display_default() # #if t_climate <= time.time() - t0_climate: # # climate() # t0_climate=time.time()
#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 if strLength < 1: #if pingcmd contains no characters => there is no connection lcd.clear() lcd.message('Pingometer\n') lcd.message('No Connection') else: #otherwise there is a connection and it will print the ping lcd.clear() lcd.message('Pingometer\n') lcd.message('Ping %s' % (pingCmd)) sleep(2)
running = True while running == True: try: while not lcdQueue.empty(): msg = lcdQueue.get() if (msg == "CLEAR"): lcd.clear() else: lcd.message(msg) sleep(0.3) # Refresh the display in case something went wrong if (debug): print 'REFRESH ==> %s ' % menuCurrent.name #lcd.noDisplay() #lcd.display() #menuCurrent.refreshDisplay() except KeyboardInterrupt: running = False if __name__=="__main__": try: main(sys.argv[1:]) finally: lcd.clear() lcd.message('GOING DOWN...\n') shifter.clear() lcd.message('Daemon killed') GPIO.cleanup()
def programa(): # importação de bibliotecas from time import sleep from mplayer import Player from gpiozero import LED from gpiozero import Button from Adafruit_CharLCD import Adafruit_CharLCD # definição de funções #player.loadfile("musica.mp3") #player.loadlist("lista.txt") def TocarEPausar(): player.pause() if (player.paused): led.blink() else: led.on() def ProximaFaixa(): player.pt_step(1) return def FaixaAnterior(): if (player.time_pos > 2.00): player.time_pos = 0.00 return player.pt_step(-1) return # criação de componentes player = Player() player.loadlist("playlist.txt") led = LED(21) lcd = Adafruit_CharLCD(2,3,4,5,6,7,16,2) button1 = Button(11) button2 = Button(12) button3 = Button(13) button1.when_pressed = FaixaAnterior button2.when_pressed = TocarEPausar button3.when_pressed = ProximaFaixa led.on() # loop infinito while True: metadados = player.metadata if metadados != None: nome = player.metadata["Title"] lcd.clear() lcd.message(nome) sleep(0.2)