class LCD: lcd = None def __init__(self): self.lcd = CharLCD() def print(self, row, message): """ Writes a message to the given row :param row: Row number to print on (0-3) :param message: Message to print. If over 20 characters it wraps to the next line """ self.lcd.cursor_pos = (row, 0) self.lcd.write_string(message) def clear_row(self, row): """ Clear a single row :param row: Row number to clear (0-3) """ self.print(row, " ") def clear_rows(self, rows): """ Clear multiple rows :param rows: List of rows to clear """ for row in rows: self.clear_row(row)
class LCDProvider(object): def __init__(self): self.line1 = 'Hello World!' self.line2 = '' GPIO.setwarnings(False) self.lcd = CharLCD(pin_rs=32, pin_e=40, pins_data=[29, 31, 11, 12], cols=16, rows=2, dotsize=8, numbering_mode = GPIO.BOARD, auto_linebreaks = False, pin_backlight = None, backlight_enabled = True) self._update_display() def _update_display(self): with cleared(self.lcd): self.lcd.write_string(self.line1) with cursor(self.lcd, 1, 0): self.lcd.write_string(self.line2) def show_text(self, msg): self.line1 = self.line2 self.line2 = msg self._update_display()
class PiLcdDisplay(ScreenDisplay): def __init__(self, lines=1, line_length=5, update_interval=1): super(PiLcdDisplay, self).__init__(lines, line_length, update_interval) self.timer = None def start(self): ''' Start the LCD display update loop ''' self.lcd = CharLCD(pin_rs=26, pin_e=24, pins_data=[22, 18, 16, 12]) self.lcd.clear() self.next_call = time.time() self.update() def update(self): ''' LCD display update loop ''' super(PiLcdDisplay, self).update() self.update_lcd() self.next_call = self.next_call + self.update_interval self.timer = threading.Timer(self.next_call - time.time(), self.update) self.timer.start() def update_lcd(self): ''' Update the LCD display ''' for i in range(self.lines): self.lcd.cursor_pos = (i, 0) self.lcd.write_string(self.displayed_info[i]) def close(self): ''' Close the LCD display ''' if self.timer != None: self.timer.cancel()
class PiLcdDisplay(ScreenDisplay): def __init__(self, lines=1, line_length=5, update_interval=1): super(PiLcdDisplay, self).__init__(lines, line_length, update_interval) self.timer = None def start(self): ''' Start the LCD display update loop ''' self.lcd = CharLCD(pin_rs=26, pin_e=24, pins_data=[22,18,16,12]) self.lcd.clear() self.next_call = time.time() self.update() def update(self): ''' LCD display update loop ''' super(PiLcdDisplay, self).update() self.update_lcd() self.next_call = self.next_call + self.update_interval self.timer = threading.Timer(self.next_call - time.time(), self.update) self.timer.start() def update_lcd(self): ''' Update the LCD display ''' for i in range(self.lines): self.lcd.cursor_pos = (i, 0) self.lcd.write_string(self.displayed_info[i]) def close(self): ''' Close the LCD display ''' if self.timer != None: self.timer.cancel()
class LCD_Display(object): """docstring for LCD_Display This class is for the 16 x 2 LCD component """ def __init__(self, cols=16, rows=2, rs=37, e=35, data_pins=[33, 31, 29, 23], mode='BOARD'): GPIO.setwarnings(False) if mode == 'BCM': self.lcd = CharLCD(cols=cols, rows=rows, pin_rs=rs, pin_e=e, pins_data=data_pins, numbering_mode=GPIO.BCM) else: self.lcd = CharLCD(cols=cols, rows=rows, pin_rs=rs, pin_e=e, pins_data=data_pins, numbering_mode=GPIO.BOARD) def display_string(self, string, clear='N', pos=(0, 0)): if clear == 'Y': self.lcd.clear() else: pass self.lcd.cursor_pos = pos self.lcd.write_string(string)
class LCD: def __init__(self): GPIO.setwarnings(False) self.lcd = CharLCD(numbering_mode=GPIO.BOARD, cols=16, rows=2, pin_rs=40, pin_e=38, pins_data=[36, 37, 35, 33]) self.lcd.cursor_mode = 'hide' self.lcd.create_char(0, full_square) def write(self, code, seconds_remaining): ''' Keyword arguments: code -- the code to be displayed seconds_remaining -- the seconds remaining (max 16) ''' self.clear() # Center code horizontally LCD_WIDTH = 16 lcd_y = (LCD_WIDTH - len(str(code))) // 2 self.lcd.cursor_pos = (0, lcd_y) self.lcd.write_string(code) self.lcd.cursor_pos = (1, 0) self.lcd.write_string(chr(0) * seconds_remaining) def clear(self): self.lcd.clear()
class LcdOutput(object): def __init__(self): self.lcd = CharLCD(pin_rs=3, pin_e=5, pins_data=[18, 22, 7, 13], pin_rw=None, numbering_mode=GPIO.BOARD, cols=16, rows=2, dotsize=8) self.chars = {} def update(self, *lines): with cleared(self.lcd): for i in range(0, len(lines)): self.lcd.cursor_pos = (i, 0) text = self.__replace_custom_chars(lines[i]) self.lcd.write_string(text) def __replace_custom_chars(self, text): for search, replace in self.chars.items(): text = text.replace(search, replace) return text def create(self, new_char): self.lcd.create_char(new_char.code, new_char.bitmap) self.chars[new_char.replacement] = chr(new_char.code) def close(self): self.lcd.close(clear=True)
def main(BUS_STOP_CODE): lcd = CharLCD(cols=16, rows=2, pin_rs=37, pin_e=35, pins_data=[33, 31, 29, 23], numbering_mode=GPIO.BOARD) bus_api = DatamallApiClient() while True: buses = bus_api.bus_at_busstop_code(BUS_STOP_CODE) for bus_num, bus_timings in buses.items(): display_string = '' if len(bus_timings) == 0: display_string = f"Bus {bus_num}: NOT\r\nAVAILABLE" if len(bus_timings) == 1: display_string = f"Bus {bus_num}: {bus_timings[0]}\r\nLAST BUS" if len(bus_timings) == 2: display_string = f"Bus {bus_num}: {bus_timings[0]}\r\n{bus_timings[1]}" if len(bus_timings) == 3: display_string = f"Bus {bus_num}: {bus_timings[0]}\r\n{bus_timings[1]}, {bus_timings[1]}" #print(display_string) lcd.clear() time.sleep(1) # to make change in info visible in screen lcd.write_string(display_string) time.sleep(5) time.sleep( 5 ) # in case of no items, do not send request in loop so fast to DatamallApi.
class Display(SensorListener, SwitchListener): sensor_names: List[str] switch_names: List[str] def __post_init__(self) -> None: self.logger = logging.getLogger(__name__) self.logger.info("Initiating LCD") # Use compatibility mode to avoid driver timing issues https://github.com/dbrgn/RPLCD/issues/70 self.lcd = CharLCD(compat_mode=True, numbering_mode=GPIO.BCM, cols=16, rows=2, pin_rs=22, pin_e=17, pins_data=[26, 19, 13, 6]) self.lcd.cursor_mode = 'hide' self.lcd.clear() self.write_lock = Lock() def handle_switch(self, name: str, on: bool) -> None: if name not in self.switch_names: self.logger.warning("'%s' is not configured to be printed to lcd", name) return x = floor(self.switch_names.index(name) / 2) y = self.switch_names.index(name) % 2 self.__write(14 + x, y, name[0].upper() if on else " ") def handle_temperature(self, name: str, temperature: float, avg_temperature: float) -> None: if name not in self.sensor_names: self.logger.warning( "Device '%s' is not configured to be printed to LCD", name) return y = floor(self.sensor_names.index(name) / 2) x = (self.sensor_names.index(name) - 2 * y) * 7 self.__write(x, y, "%s %s" % (name[0].upper(), round(temperature, 1))) def __write(self, x, y, text) -> None: self.logger.debug("Writing '%s' to LCD at (%s,%s)", text, x, y) with self.write_lock: self.lcd.cursor_pos = (y, x) self.lcd.write_string(text) def shutdown(self) -> None: self.logger.info("Shutting down LCD") self.lcd.close(clear=True)
class lcd: def __init__(self,cols=16,rows=2): self.cols,self.rows= cols,rows self.blink=False self.data=None self.data_name=None self.time_last_packet=0 self.recieve_timeout=None GPIO.setmode(GPIO.BCM) self.screen = CharLCD(numbering_mode=GPIO.BCM,cols=self.cols, rows=self.rows, pin_rs=16, pin_e=18, pins_data=[23, 24, 2, 3]) def prompt(self,text,text2=""): self.screen.clear() self.write(text) self.screen.cursor_pos = (1,0) self.write(text2) def write(self,text): print(self.screen.cursor_pos,text) self.screen.write_string(text[:self.cols]) def format_number(self,number,digits): output=digit(number,digits) if len(output)>digits: output="9" while(len(output)<digits): output+="9" return output def recieve_packets(self): self.screen.clear() self.write("R LP:"+self.format_number(time()-self.time_last_packet,2)+"s") if(self.recieve_timeout!=None): remaining_time=self.recieve_timeout-time() self.cursor_pos=(0,9) self.write("TO:"+self.format_number(remaining_time,3)+"s") if self.data_name!=None and self.data!=None: self.screen.cursor_pos = (1,0) self.write(self.data_name+": ") data_digits=self.cols-len(self.data_name) data=self.format_number(self.data,data_digits) self.screen.cursor_pos = (1,self.cols-data_digits) self.write(data) if self.blink: self.screen.cursor_pos = (0,1) self.write(".") self.blink=False else: self.blink=True
def LCD_screen(): while True: lcd = CharLCD(cols=16, rows=2, pin_rs=19, pin_e=26, numbering_mode=GPIO.BCM, pins_data=[17, 27, 22, 5, 12, 25, 24, 23]) string = (subprocess.check_output(["hostname", "-I"]).split()[1]).decode('ascii') lcd.write_string(f'{string}') time.sleep(30) lcd.clear()
class Display: def setup(self): GPIO.setmode(GPIO.BCM) self.lcd = CharLCD(cols=16, rows=2, pin_rs=6, pin_e=5, pins_data=[13, 19, 26, 1], numbering_mode=GPIO.BCM) self.lcd.cursor_mode = 'hide' print("Display setup finished") def clear(self): self.lcd.clear() return def show_text(self, text, line=1): if line == 1: self.lcd.cursor_pos = (0, 0) self.lcd.write_string(" ") self.lcd.cursor_pos = (0, 0) self.lcd.write_string(text) elif line == 2: self.lcd.cursor_pos = (1, 0) self.lcd.write_string(" ") self.lcd.cursor_pos = (1, 0) self.lcd.write_string(text)
class Lcd: def __init__(self, rs_pin, e_pin, data_pins): GPIO.setwarnings(False) self.lcd = CharLCD(cols=16, rows=2, pin_rs=rs_pin, pin_e=e_pin, \ pins_data=data_pins , numbering_mode=GPIO.BOARD) self.lcd.clear() self.lock = threading.Lock() def write(self, lines): with self.lock: self.lcd.clear() self.lcd.write_string(lines[0][:16].upper()) if len(lines) == 2: self.lcd.cursor_pos = (1, 0) self.lcd.write_string(lines[1][:16].upper())
def main(): # initialize lcd screen lcd = CharLCD(cols=16, rows=2, pin_rs=37, pin_e=35, pins_data=[33, 31, 29, 23]) # DHT22 sensor is only accurate to +/- 2% humidity and +/- 0.5 celsius # Poll 10 times and calculate median to get more accurate value templist = [] humidlist = [] lcd.cursor_pos = (0, 0) lcd.write_string("Polling...") lcd.cursor_pos = (1, 0) bar = "[----------]" lcd.write_string(bar) lcd.clear() for i in range(1, 11): data = poll() lcd.cursor_pos = (0, 0) lcd.write_string("Polling....") lcd.cursor_pos = (1, 0) bar = list(bar) bar[i] = '#' bar = ''.join(bar) lcd.write_string(bar) # Don't poll more often than every 2 seconds sleep(3) lcd.clear() temp = int(round(data[0])) humid = int(round(data[1])) templist.append(temp) humidlist.append(humid) lcd.clear() # Calculate median value temp = (sorted(templist))[5] humid = (sorted(humidlist))[5] # Display results to LCD display(lcd, temp, humid) # Write data to CSV file for later analysis write_data(temp, humid) # Clears the screen / resets cursor position and closes connection lcd.clear() lcd.close(clear=True)
def main(): iterations = 300 interval = 0.1 print("starting {} second collection".format(iterations * interval)) sensor1 = SonicSensor(trig_pin=18, echo_pin=24, numbering_mode=GPIO.BCM) sensor2 = SonicSensor(trig_pin=16, echo_pin=12, numbering_mode=GPIO.BCM) lcd = CharLCD(numbering_mode=GPIO.BCM, cols=16, rows=2, pin_rs=21, pin_e=20, pins_data=[5, 7, 8, 25, 26, 19, 13, 6]) results1 = [] results2 = [] try: for i in range(iterations): dist1 = sensor1.get_distance() dist2 = sensor2.get_distance() results1.append(dist1) results2.append(dist2) lcd.write_string(u'%.1f cm' % dist2) print(u'%.1f cm' % dist2) lcd.write_string(u'\n%.1f cm' % dist1) print(u'%.1f cm' % dist1) time.sleep(interval) lcd.clear() except KeyboardInterrupt: pass GPIO.cleanup() with open('results.pickle', 'wb') as file: pickle.dump((results1, results2), file)
def main(): lcd = CharLCD(numbering_mode=GPIO.BOARD, cols=16, rows=2, pin_rs=37, pin_e=35, pins_data=[33, 31, 29, 23]) lcd.clear() lcd.cursor_pos = (0, 0) lcd.write_string(u'Scannez un tube') code = '' GPIO.setup(3, GPIO.IN) GPIO.add_event_detect(3, GPIO.BOTH, callback=close) while (True): inkey = Getch() k = inkey() if ord(k) == 27: GPIO.cleanup() call(['shutdown', 'now']) #quit() elif k == '\r': lcd.clear() lcd.cursor_pos = (0, 0) lcd.write_string(code) sleep(5) code = '' lcd.cursor_pos = (0, 0) lcd.write_string(u'Scannez un tube') elif k != '': code += k
class Display(): def __init__(self, *args, **kwargs): self.lcd = CharLCD(*args, **kwargs) def displayCode(self, code): """ displays the code being typed. code is a list of numbers """ strCode = "" for num in code: strCode += str(num) self.clear() self.lcd.write_string(strCode) def writeMessage(self, msg): """ write a message to the LCD """ self.clear() self.lcd.write_string(msg) def clear(self): """ clears the LCD """ self.lcd.clear()
class LcdDisplayHardware: def __init__(self, width, height): GPIO.setwarnings(False) self.lcd = None self.width = width self.height = height def __initHardware(self): if (self.lcd is None): self.lcd = CharLCD(pin_rs=26, pin_e=24, pins_data=[22, 18, 16, 12], numbering_mode=GPIO.BOARD, cols=self.width, rows=self.height, dotsize=8) def defineCharacter(self, characterNumber, characterDefinition): self.__initHardware() self.lcd.create_char(characterNumber, characterDefinition) def drawLine(self, lineNumber, line): self.__initHardware() self.lcd.cursor_pos = (lineNumber, 0) self.lcd.write_string(line) def drawString(self, lineNumber, columnNumber, line): self.__initHardware() self.lcd.cursor_pos = (lineNumber, columnNumber) self.lcd.write_string(line) def turnDisplay(self, state): LED_ON = 32 GPIO.setup(LED_ON, GPIO.OUT) GPIO.output(LED_ON, state) def setupCharacters(self, characterDefinition): self.__initHardware() for characterNumber in range(0, len(characterDefinition.CustomCharacters)): self.defineCharacter(characterNumber, characterDefinition.CustomCharacters[characterNumber])
def main(): try: rotary = RotaryEncoder(dt_pin=3, clk_pin=4) rotary.start() button = Button(pin=2) lcd = CharLCD(numbering_mode=GPIO.BCM, cols=16, rows=2, pin_rs=21, pin_e=20, pins_data=[5, 7, 8, 25, 26, 19, 13, 6]) while True: if button.pressed(): break lcd.clear() lcd.write_string(u'{}'.format(rotary.get_count())) time.sleep(0.1) except KeyboardInterrupt: # Ctrl-C to terminate the program pass print("stopped at {}".format(rotary.get_count())) rotary.stop() GPIO.cleanup()
def write_to_lcd(ifname): lcd = CharLCD() lcd.clear() lcd.home() lcd.write_string(get_hostname()) lcd.cursor_pos = (1, 0) lcd.write_string(get_device_type()) lcd.cursor_pos = (2, 0) lcd.write_string(get_ip_address(ifname))
# Start air pressure stuff pressure_sensor = BMP085(0x77) pressure = pressure_sensor.readPressure() # Altitude correction for pressure at sea level. psea = pressure / pow(1.0 - altitude/44330.0, 5.255) psea_dec = psea / 100.0 pressure_relative = decimal.Decimal(psea_dec) rounded_pressure_relative = pressure_relative.quantize(decimal.Decimal('.01'), rounding=decimal.ROUND_HALF_UP) lcd = CharLCD() # Print the data onto the display. lcd.clear() lcd.write_string(time.strftime("%d.%m.%Y %H:%M")) lcd.cursor_pos = (1, 0) #lcd.write_string(str(City) + ' ') lcd.write_string('Innen: {0} Grad'.format(Temperature_In)) lcd.cursor_pos = (2, 0) lcd.write_string('Aussen: {0} Grad'.format(Temperature_Out)) lcd.cursor_pos = (3, 0) lcd.write_string(Weather_Text) # Write the data to a webpage on the local server # Get some weather icons that are compliant with Yahoo condition codes. # The ones by MerlinTheRed are nice and work well # <http://merlinthered.deviantart.com/art/plain-weather-icons-157162192> CC-BY-NC-SA with open('/var/www/aktuell.html','w') as index: index.write('<style type="text/css">' 'body {font-weight:lighter; font-family:Arial; font-size:100%; } '
## BLINKING TEXT ''' Combining lcd.clear() and time.sleep() in a while loop will produce a blinking text effect: ''' import time # This is the library which we will be using for the time function from RPLCD import CharLCD # This is the library which we will be using for LCD Display from RPi import GPIO # This is the library which we will be using for using the GPIO pins of Raspberry PI # Initializing the LCD Display lcd = CharLCD(numbering_mode=GPIO.BOARD, cols=16, rows=2, pin_rs=37, pin_e=35, pins_data=[33, 31, 29, 23]) while True: lcd.write_string(u"Hello world!") time.sleep(1) lcd.clear() time.sleep(1) # Press Ctrl+C to exit the program.
from RPLCD import CharLCD import RPi.GPIO as GPIO import time from pad4pi import rpi_gpio pins_data=[9, 10, 22, 21] pins_data2=[21,22,10,9] pin_e=11 pin_rs=7 GPIO.setmode(GPIO.BCM) GPIO.setup(pin_rs, GPIO.OUT) GPIO.setup(pin_e, GPIO.OUT) for pin in pins_data: GPIO.setup(pin, GPIO.OUT) GPIO.output(pin, True) lcd = CharLCD(cols=16, rows=2, pin_rs=7, pin_e=11, pins_data=[9, 10, 21, 22], numbering_mode=GPIO.BCM) lcd.cursor_pos = (0,0) lcd.write_string(u'Pinjam/Kembali?') lcd.cursor_pos = (1,0) lcd.write_string(u'1:P 2:K 3:Back') time.sleep(5) lcd.clear() GPIO.cleanup()
class Menu: """Menu class for managing a multi effects patch in Pd on Raspberry Pi. The Menu is operated via a rotary encoder with an integrated push button. Another button is added to navigate the Menu. Turning the rotary encoder selects menu options or changes effects parameters. Pushing the encoders internal push button increases the menu level and pushing the other button decreases the menu level. The menu levels are: 0. Level Metering 1. Effect Selection 2. Parameter Selection 3. Parameter Adjustment The Menu is displayed on a HD44780 compatible 2x16 character display. Pd and the Menu communicate via OSC messages and listen on different ports. This menu is designed to display true effects parameters values, even if these values are changed by a different source like a MIDI controller. Manuel Planton 2019 """ OSC_ADDRESS = "/menu" LEVEL_MIN = 0 LEVEL_MAX = 3 SUPERLINE = "#" * 16 def __init__(self, ip, port, pd_ip, pd_port, d_rs, d_rw, d_e, d_d4, d_d5, d_d6, d_d7, r_clk, r_d, r_sw, button): """Constructor IP addresses and port numbers for OSC connection are needed. Prefix 'd' is for HD44780 compatible display connections connected to the pins of the RPi. Prefix 'r' is for KY040 compatible rotary encoder connections connected to the pins of the RPi. Pin numbers are BCM numbers! (see GPIO.setmode(GPIO.BCM)) Args: ip: IP Address of the OSC server of this menu port: port number of the OSC server of this menu pd_ip: IP Address of the OSC server of the Pd effects patch pd_port: port number of the OSC server of the Pd effects patch d_rs: HD44780 register select pin number d_rw: HD44780 read/write pin number d_e: HD44780 enable pin number d_d4: HD44780 data channel 4 pin number d_d5: HD44780 data channel 5 pin number d_d6: HD44780 data channel 6 pin number d_d7: HD44780 data channel 7 pin number r_clk: rotary encoder clock pin number r_d: rotary encoder data pin number r_sw: rotary encoder internal switch button pin number button: push button pin number """ self.ip = ip self.port = port self.pd_ip = pd_ip self.pd_port = pd_port self.pd_is_connected = False self.rotary_increment = 1 # menu level entry state self.level = 1 # current effect self.fx_nr = 0 # current parameter of the effect self.param_nr = 0 # define effects main = Effect(name="main", params={ 'on': 1, 'in_vol': 127, 'out_vol': 127 }) reverb = Effect(name="reverb", params={ 'on': 0, 'dry': 64, 'wet': 120, 'rev_in_lvl': 100, 'liveness': 80, 'fc': 40, 'hf_damp': 7 }) delay = Effect( "delay", { 'on': 0, 'dry': 64, 'wet': 127, 'delay_time': 64, 'feedback': 100, 'fc_lop': 120, 'fc_hip': 25, 'detune': 10, 'mod_freq': 5 }) lop = Effect("lop", {'on': 0, 'fc': 64}) hip = Effect("hip", {'on': 0, 'fc': 30}) # effects list self.fx = [main, reverb, delay, lop, hip] GPIO.setmode(GPIO.BCM) self.button = Button.Button(button, "falling", self.buttonPressed) # callbacks for encoder and OSC handlers must be defined self.r_encoder = KY040.KY040(r_clk, r_d, r_sw, self.rotaryChange, self.switchPressed) print("DBG: initialize display") # Compat mode is true because slow displays show garbage sometimes. self.lcd = CharLCD(numbering_mode=GPIO.BCM, cols=16, rows=2, pin_rs=d_rs, pin_rw=d_rw, pin_e=d_e, pins_data=[d_d4, d_d5, d_d6, d_d7], compat_mode=True) print("DBG: initialize OSC Server") self.server = OSC3.OSCServer((ip, port)) print("DBG: initialize OSC Client") self.client = OSC3.OSCClient() # first appearance of the menu self.printMenu() def buttonPressed(self, pin): """Callback function for the single push button""" print("DBG: button pressed") if self.level > self.LEVEL_MIN: self.level = self.level - 1 self.printMenu() def switchPressed(self, pin): """Callback function for pressing the internal button of the rotary encoder Args: pin: BCM pin number of the button """ print("DBG: rotary button pressed") # try to connect to Pd if it has not been done successfully if (self.pd_is_connected == False): self.connectToPd() if self.level < self.LEVEL_MAX: self.level = self.level + 1 # update all parameters of the effect self.updateParameters() self.printMenu() elif self.level == self.LEVEL_MAX: # change rotary encoder increment if switch pressed on parameter adjustment level if self.rotary_increment == 1: self.rotary_increment = 5 elif self.rotary_increment == 5: self.rotary_increment = 10 elif self.rotary_increment == 10: self.rotary_increment = 25 elif self.rotary_increment == 25: self.rotary_increment = 1 def rotaryChange(self, direction): """Callback function for turning the rotary encoder Args: direction: 1 - clockwise, -1 - counterclockwise """ print("DBG: turned: ", str(direction)) # level 0 is metering -> do nothing if self.level <= 0: return if self.level == 1: # effect selection new_fx_nr = self.fx_nr + direction if new_fx_nr in range(0, len(self.fx)): self.fx_nr = new_fx_nr self.param_nr = 0 self.printMenu() elif self.level == 2: # parameter selection new_param_nr = self.param_nr + direction if new_param_nr in range(0, len(self.fx[self.fx_nr].params)): self.param_nr = new_param_nr self.printMenu() elif self.level == 3: # parameter adjustment current_fx = self.fx[self.fx_nr] keys = list(current_fx.params.keys()) key = keys[self.param_nr] new_val = current_fx.params[key] + (direction * self.rotary_increment) if new_val < current_fx.MIN_VAL: new_val = current_fx.MIN_VAL elif new_val > current_fx.MAX_VAL: new_val = current_fx.MAX_VAL # on is handled differently if key == 'on': current_fx.params[key] = int(not current_fx.params[key]) else: current_fx.params[key] = new_val self.setParameter() self.printMenu() else: print("ERROR: no such level!") def printMenu(self): print("DBG:", "lvl:", str(self.level)) print("DBG:", "fx_nr:", str(self.fx_nr)) print("DBG:", "param_nr:", str(self.param_nr)) # metering if self.level == 0: self.lcd.clear() self.lcd.cursor_pos = (0, 0) self.lcd.write_string("Menu lvl 0") self.lcd.cursor_pos = (1, 0) self.lcd.write_string("Metering: TBA") # effect selection elif self.level == 1: self.lcd.clear() if self.fx_nr == len(self.fx) - 1: # last entry on = self.fx[self.fx_nr].params['on'] self.lcd.cursor_pos = (0, 0) self.lcd.write_string("*" + self.fx[self.fx_nr].name + " " + str(on)) self.lcd.cursor_pos = (1, 0) self.lcd.write_string(self.SUPERLINE) else: self.lcd.cursor_pos = (0, 0) on_1 = self.fx[self.fx_nr].params['on'] self.lcd.write_string("*" + self.fx[self.fx_nr].name + " " + str(on_1)) self.lcd.cursor_pos = (1, 0) on_2 = self.fx[self.fx_nr + 1].params['on'] self.lcd.write_string(" " + self.fx[self.fx_nr + 1].name + " " + str(on_2)) # parameter selection and adjustment elif self.level == 2 or self.level == 3: params = self.fx[self.fx_nr].params keys = list(params.keys()) key1 = keys[self.param_nr] if self.level == 2: crsr = "*" else: crsr = ">" self.lcd.clear() # last entry if self.param_nr == len(params) - 1: self.lcd.cursor_pos = (0, 0) self.lcd.write_string(crsr + key1 + ": " + str(params[key1])) self.lcd.cursor_pos = (1, 0) self.lcd.write_string(self.SUPERLINE) else: key2 = keys[self.param_nr + 1] self.lcd.cursor_pos = (0, 0) self.lcd.write_string(crsr + key1 + ": " + str(params[key1])) self.lcd.cursor_pos = (1, 0) self.lcd.write_string(" " + key2 + ": " + str(params[key2])) else: print("ERROR: no such menu level") def setParameter(self): msg = OSC3.OSCMessage() keys = list(self.fx[self.fx_nr].params.keys() ) # TODO: this should be more efficient and convenient key = keys[self.param_nr] msg.setAddress("/pd/" + self.fx[self.fx_nr].name + "/set/" + key) msg.append(self.fx[self.fx_nr].params[key]) self.client.send(msg) def getParameter(self, key): msg = OSC3.OSCMessage() msg.setAddress("/pd/" + self.fx[self.fx_nr].name + "/get/" + key) msg.append("bang") self.client.send(msg) def updateParameters(self): params = self.fx[self.fx_nr].params for key in self.fx[self.fx_nr].params: self.getParameter(key) def connectToPd(self): # it is possible to tell Pd the ip and the port to connect to print("DBG: Try to let Pd connect to menu's server") self.oscSend("/pd/connect", "bang") def handleGetParameter(self, addr, tags, data, client_address): # Messages to menu should be exclusively from Pd or to what it should be connected if self.pd_is_connected == False: self.pd_is_connected = True # safer, but more expensive -> search name of effect according to data key = data[-2] value = data[-1] self.fx[self.fx_nr].params[key] = int(value) def oscSend(self, address, data): msg = OSC3.OSCMessage() msg.setAddress(address) msg.append(data) self.client.send(msg) def run(self): self.r_encoder.start() self.button.start() print("connect menu OSC client to", self.pd_ip, "at port", str(self.pd_port)) self.client.connect((self.pd_ip, self.pd_port)) self.server.addMsgHandler('/menu', self.handleGetParameter) print("running...") self.server.serve_forever() def stop(self): self.r_encoder.stop() self.button.stop() GPIO.cleanup()
lcd = CharLCD(cols=16, rows=2) # if you have a backlight circuit, initialize like this (substituting the # appropriate GPIO and BacklightMode for your backlight circuit): #lcd = CharLCD(cols=16, rows=2, pin_backlight=7, backlight_mode=BacklightMode.active_high) lcd.backlight = True input('Display should be blank. ') lcd.cursor_mode = CursorMode.blink input('The cursor should now blink. ') lcd.cursor_mode = CursorMode.line input('The cursor should now be a line. ') lcd.write_string('Hello world!') input('"Hello world!" should be on the LCD. ') assert lcd.cursor_pos == (0, 12), 'cursor_pos should now be (0, 12)' lcd.cursor_pos = (0, 15) lcd.write_string('1') lcd.cursor_pos = (1, 15) lcd.write_string('2') assert lcd.cursor_pos == (0, 0), 'cursor_pos should now be (0, 0)' input('Lines 1 and 2 should now be labelled with the right numbers on the right side. ') lcd.clear() input('Display should now be clear, cursor should be at initial position. ') lcd.cursor_pos = (0, 5)
import fcntl import struct import time lcd = CharLCD(cols=16, rows=2, pin_rs=37, pin_e=35, pins_data=[33, 31, 29, 23]) def get_ip_address(ifname): s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) return socket.inet_ntoa( fcntl.ioctl(s.fileno(), 0x8915, struct.pack('256s', ifname[:15]))[20:24]) lcd.cursor_pos = (0, 4) lcd.write_string(u"Hello :)") time.sleep(2) lcd.clear() lcd.write_string(socket.gethostname()) lcd.cursor_pos = (1, 0) def display_ip(): lcd.clear() lcd.write_string(socket.gethostname()) lcd.cursor_pos = (1, 0) try: lcd.write_string(get_ip_address('eth0')) except IOError: try:
from RPLCD import CharLCD lcd = CharLCD(cols=16, rows=2, pin_rs=37, pin_e=35, pins_data=[40, 38, 36, 32, 33, 31, 29, 23]) lcd.write_string(u'Hello world!')
pass RPIO.setwarnings(False) lcd = CharLCD(cols=16, rows=2) input('Display should be blank. ') lcd.cursor_mode = CursorMode.blink input('The cursor should now blink. ') lcd.cursor_mode = CursorMode.line input('The cursor should now be a line. ') lcd.write_string('Hello world!') input('"Hello world!" should be on the LCD. ') assert lcd.cursor_pos == (0, 12), 'cursor_pos should now be (0, 12)' lcd.cursor_pos = (0, 15) lcd.write_string('1') lcd.cursor_pos = (1, 15) lcd.write_string('2') assert lcd.cursor_pos == (0, 0), 'cursor_pos should now be (0, 0)' input('Lines 1 and 2 should now be labelled with the right numbers on the right side. ') lcd.clear() input('Display should now be clear, cursor should be at initial position. ') lcd.cursor_pos = (0, 5)
import struct import time from bluepy.btle import UUID, Peripheral GPIO.setwarnings(False) detection_UUID = UUID(0x180C) p = Peripheral('f0:24:d3:40:e2:00', 'random') lcd = CharLCD(numbering_mode=GPIO.BOARD, cols=16, rows=2, pin_rs=37, pin_e=35, pins_data=[33, 31, 29, 23]) try: p.connect('f0:24:d3:40:e2:00', 'random') ch = p.getCharacteristic(uuid=detection_UUID)[0] if (ch.supportsRead()): while 1: vesselPresence = binascii.b2a_hex(ch.read()) vesselPresence = binascii.unhexlify(vesselPresence) vesselPresence = struct.unpack('f', vesselPresence)[0] display = "Detected: " + str(vesselPresence) print(display) lcd.write_string(display) lcd.cursor_pos = (1, 3) finally: p.disconnect()
# create the aquila characters aquila0 = (0b01111,0b00011,0b00001,0b00000,0b00000,0b00000,0b00000,0b00000) lcd.create_char(0,aquila0) aquila1 = (0b11101,0b11000,0b11111,0b11111,0b01101,0b00001,0b00011,0b00010) lcd.create_char(1,aquila1) aquila2 = (0b01011,0b10001,0b11111,0b11111,0b11011,0b11000,0b11100,0b10100) lcd.create_char(2,aquila2) aquila3 = (0b11111,0b11100,0b11000,0b10000,0b00000,0b00000,0b00000,0b00000) lcd.create_char(3,aquila3) # prep the LCD lcd.clear() lcd.home() with cursor(lcd, 0, 2): lcd.write_string('AUSPEX 410014.M2') # test github editor for spaces # OK it worked # draw the aquila centred on line 2 with cursor(lcd, 1,8): lcd.write_string(unichr(0)) lcd.write_string(unichr(1)) lcd.write_string(unichr(2)) lcd.write_string(unichr(3)) with cursor(lcd,2,4): lcd.write_string('MET: 1:22:45') with cursor(lcd,3,2): lcd.write_string('VP:03 <T2< VP:01')
unichr = unichr except NameError: unichr = chr lcd = CharLCD() input('Display should be blank. ') lcd.cursor_mode = CursorMode.blink input('The cursor should now blink. ') lcd.cursor_mode = CursorMode.line input('The cursor should now be a line. ') lcd.write_string('Hello world!') input('"Hello world!" should be on the LCD. ') assert lcd.cursor_pos == (0, 12), 'cursor_pos should now be (0, 12)' lcd.cursor_pos = (1, 0) lcd.write_string('2') lcd.cursor_pos = (2, 0) lcd.write_string('3') lcd.cursor_pos = (3, 0) lcd.write_string('4') assert lcd.cursor_pos == (3, 1), 'cursor_pos should now be (3, 1)' input('Lines 2, 3 and 4 should now be labelled with the right numbers. ') lcd.clear() input('Display should now be clear, cursor should be at initial position. ')
global meeting_booking_id print "Starting " + self.name if threadLock.acquire(0) != 0: print 'Calling activate_room' activate_room(self.passcode) threadLock.release() else: print 'could not acquire lock' print "Exiting " + self.name meeting_booking_id = 0 # Reads motion sensor data continuously and takes action class MotionSensorThread(threading.Thread): def __init__(self): threading.Thread.__init__(self) def run(self): read_sensor() lcd.clear() lcd.write_string('Meeting room is available for booking') bookingMonitorThread = BookingMonitorThread('BookingMonitor Thread') bookingMonitorThread.start() motionSensorThread = MotionSensorThread() motionSensorThread.start()
# We call a RPi.GPIO built-in function GPIO.cleanup() to clean up all the ports we've used GPIO.cleanup() # Now setup LCD display pins (8-bit mode) lcd = CharLCD(numbering_mode=GPIO.BOARD, cols=16, rows=2, pin_rs=37, pin_e=35, pins_data=[40, 38, 36, 32, 33, 31, 29, 23]) # Get senosr readings and render them in a loop while True: # Get sensor's readings # IMPORTANT: 11 is sensor type (DHT11) and 18 is GPIO number (or physical pin 12) humidity, temperature = Adafruit_DHT.read_retry(11, 18) print('Temp: {0:0.1f} C Humidity: {1:0.1f} %'.format(temperature, humidity)) # Clear and set initial cursor position for LCD display lcd.clear() lcd.cursor_pos = (0, 0) # Render temperature readings lcd.write_string("Temp: %d C" % temperature) # Move cursor to second row lcd.cursor_pos = (1, 0) # Render humidity readings lcd.write_string("Humidity: %d %%" % humidity) # Pause execution for 5 seconds time.sleep(5)
lcd = CharLCD(pin_rs=26, pin_e=24, pins_data=[22, 18, 16, 12]) api=twitter.Api(consumer_key='YOUR_CONSUMER_KEY', consumer_secret='YOUR_CONSUMER_SECRET', access_token_key='YOUR_ACCESS_TOKEN_KEY', access_token_secret='YOUR_ACCESS_TOKEN_SECRET') htmlParser = HTMLParser.HTMLParser() try: while True: try: homeTimeline=api.GetHomeTimeline(count=1) except: lcd.clear() lcd.write_string(u'An Error occurred! Retrying') continue tweetUser = homeTimeline[0].user.screen_name tweetText = homeTimeline[0].text tweetText = htmlParser.unescape(tweetText) # convert HTML symbols like & tweetText = tweetText.replace('\n',' ') # replace newlines with space # Break the tweet into two parts as the LCD screen can display # only 80 characters at a time seg1_len = 80 - len(tweetUser) - 2 tweetText1 = tweetUser+": "+tweetText[:seg1_len] tweetText2 = tweetText[seg1_len:] lcd.clear() lcd.write_string(tweetText1) if tweetText2:
maxlen = arglen def formatvalue(value): width = len(value.split(".")[0]) if width < maxlen: pad = maxlen - width return "{}{}".format(" " * pad, value) return value def formatline(*args): line = "".join(args) linelen = len(line) if linelen < 20: pad = 20 - linelen return "{}{}{}".format(args[0], " " * pad, args[1]) gpio.setmode(gpio.BCM) # Pin Belegung festlegen lcd = CharLCD(pin_rs=7, pin_rw=4, pin_e=8, pins_data=[23, 18, 15, 14], numbering_mode=gpio.BCM, cols=20, rows=4, dotsize=8) lcd.write_string(sys.argv[2]) # Uhrzeit lcd.write_string(" ") # Freistelle lcd.write_string(sys.argv[1]) # Datum/ Ende mit Stelle 20 lcd.write_string(formatline("P: ", sys.argv[3])) lcd.write_string(formatline("D: ", sys.argv[4])) lcd.write_string(formatline("U: ", sys.argv[5])) #Display nicht loeschen nach Script stop mit false sonst nullt er das ! lcd.close(clear=false)
class Watering: def __init__(self): # Watering variables self.daysBetweenWatering = 3 # Number of days between one watering self.startTime = [23, 50] # [hh, mm] self.durationOfWatering = 40 # in minutes self.modeList = ['AUTO', 'MANU'] # List of available modes self.currentModeSelected = 0 self.lastWatering = None # Last date of watering self.ongoingWatering = False # Is the watering on going or not self.endWateringDate = None # Contains the datetime of the end of the current watering # Emergency self.emergency_on = False # Process self.watering_process = None self.emergency_process = None # Menu self.currentMenuSelected = 0 self.configMenuSelected = 0 self.HOME_MENU = 0 self.CONFIG_MENU = 1 self.CONFIG_DETAILS_MENU = 2 self.EMERGENCY_MENU = 3 self.mainMenu = { 0: self.display_menu_home, 1: self.display_config_menu, 2: self.display_config_details, 3: self.display_emergency } self.START_STOP_WATERING_CONFIG_MENU = 0 self.DAYS_OF_WATERING_CONFIG_MENU = 1 self.START_WATERING_AT_CONFIG_MENU = 2 self.DURATION_OF_WATERING_CONFIG_MENU = 3 self.MODE_SELECTION_CONFIG_MENU = 4 self.CHANGE_DAY_DATE_CONFIG_MENU = 5 self.CHANGE_MONTH_DATE_CONFIG_MENU = 6 self.CHANGE_YEAR_DATE_CONFIG_MENU = 7 self.CHANGE_HOUR_DATE_CONFIG_MENU = 8 self.CHANGE_MINUTE_DATE_CONFIG_MENU = 9 self.configMenu = { 0: (self.display_menu_start_stop_watering, "Demarrer/Arreter"), 1: (self.display_menu_watering_days, "Jours d'arro."), 2: (self.display_menu_start_time, "Heure de debut"), 3: (self.display_menu_duration, "Duree d'arro."), 4: (self.display_menu_mode, "Mode d'arro."), 5: (self.display_menu_change_day_date, 'Changer le jour'), 6: (self.display_menu_change_month_date, 'Changer le mois'), 7: (self.display_menu_change_year_date, 'Changer l\'annee'), 8: (self.display_menu_change_hour_date, 'Changer l\'heure'), 9: (self.display_menu_change_minute_date, 'Changer les min') } # LCD setup and startup self.last_activity = datetime.datetime.today() self.time_before_switch_off = 60 * 5 # In seconds self.lcd = CharLCD(pin_backlight=18, backlight_mode=BacklightMode.active_high, pin_rw=None) self.lcd.backlight = True self.lcd.cursor_pos = (0, 0) self.lcd.write_string('Demarrage en cours..') self.lcd.cursor_pos = (1, 0) self.lcd.write_string('Initialisation des') self.lcd.cursor_pos = (2, 0) self.lcd.write_string('parametres ') self.lcd.cursor_mode = CursorMode.blink # Setup the GPIOs self.setup_gpio(param.GPIO) # Test if all LEDs work self.test_setup() # Clean the lcd self.lcd.clear() self.lcd.cursor_mode = CursorMode.hide # Put the relay to the off position GPIO.output(param.GPIO['relay'][1], GPIO.LOW) self.start() # GPIO configuration def setup_gpio(self, array): GPIO.setwarnings(False) GPIO.setmode(GPIO.BOARD) # v[0] contains the key # v[1] contains the value for v in array.items(): if isinstance(v[1], dict): self.setup_gpio(v[1]) else: if v[1][0].upper() == "IN": GPIO.setup(v[1][1], GPIO.IN, pull_up_down=GPIO.PUD_UP) # Define callback method if v[0] in ['left', 'right']: GPIO.add_event_detect(v[1][1], GPIO.FALLING, callback=self.left_right_btn_pressed, bouncetime=500) elif v[0] in ['up', 'bottom']: GPIO.add_event_detect(v[1][1], GPIO.FALLING, callback=self.up_bottom_btn_pressed, bouncetime=500) elif v[0] == 'emergency': GPIO.add_event_detect(v[1][1], GPIO.FALLING, callback=self.emergency_btn_pressed, bouncetime=2000) else: GPIO.setup(v[1][1], GPIO.OUT) # Test if all LEDs work def test_setup(self): GPIO.output(param.GPIO['led']['green'][1], GPIO.HIGH) GPIO.output(param.GPIO['led']['red'][1], GPIO.HIGH) time.sleep(5) GPIO.output(param.GPIO['led']['green'][1], GPIO.LOW) GPIO.output(param.GPIO['led']['red'][1], GPIO.LOW) def start(self): while True: date_diff = datetime.datetime.today() - self.last_activity if self.lcd.display_enabled and date_diff.seconds > self.time_before_switch_off and self.currentMenuSelected != self.CONFIG_DETAILS_MENU: self.switch_off_lcd() self.currentMenuSelected = self.HOME_MENU elif not self.lcd.display_enabled and date_diff.seconds < self.time_before_switch_off: self.switch_on_lcd() self.display_menu() else: # Displays the menu only if the screen is on self.display_menu() # Calculates if it has to water or not # If mode AUTO if self.modeList[self.currentModeSelected] == "AUTO" and self.has_to_water() and not self.ongoingWatering: self.start_watering() # Stops the watering after duration specified elif self.ongoingWatering and self.endWateringDate < datetime.datetime.today(): self.stop_watering() time.sleep(.5) # Changes the currentMenuSelected def left_right_btn_pressed(self, channel): if not self.lcd.display_enabled: self.last_activity = datetime.datetime.today() return self.last_activity = datetime.datetime.today() if self.emergency_on: return if param.GPIO['btn']['right'][1] == channel: self.currentMenuSelected = self.currentMenuSelected + 1 if self.currentMenuSelected < len( self.mainMenu) - 2 else 0 elif param.GPIO['btn']['left'][1] == channel: self.currentMenuSelected = self.currentMenuSelected - 1 if self.currentMenuSelected > 0 else 0 # Changes the value of the corresponding currentMenuSelected def up_bottom_btn_pressed(self, channel): if not self.lcd.display_enabled: self.last_activity = datetime.datetime.today() return self.last_activity = datetime.datetime.today() # Change the current selected config menu if self.currentMenuSelected == self.CONFIG_MENU: if param.GPIO['btn']['up'][1] == channel: self.configMenuSelected = self.configMenuSelected - 1 if self.configMenuSelected > 0 else len( self.configMenu) - 1 if param.GPIO['btn']['bottom'][1] == channel: self.configMenuSelected = self.configMenuSelected + 1 if self.configMenuSelected < len( self.configMenu) - 1 else 0 # Adds or removes days between watering elif self.configMenuSelected == self.DAYS_OF_WATERING_CONFIG_MENU: if param.GPIO['btn']['up'][1] == channel: self.daysBetweenWatering = self.daysBetweenWatering + 1 if self.daysBetweenWatering < 7 else 1 if param.GPIO['btn']['bottom'][1] == channel: self.daysBetweenWatering = self.daysBetweenWatering - 1 if self.daysBetweenWatering > 1 else 7 # Defines the time when the watering must start elif self.configMenuSelected == self.START_WATERING_AT_CONFIG_MENU: if param.GPIO['btn']['up'][1] == channel: self.add_start_time() if param.GPIO['btn']['bottom'][1] == channel: self.remove_start_time() # Adds or removes the duration of watering elif self.configMenuSelected == self.DURATION_OF_WATERING_CONFIG_MENU: if param.GPIO['btn']['up'][1] == channel: self.durationOfWatering += 10 if param.GPIO['btn']['bottom'][1] == channel and self.durationOfWatering > 10: self.durationOfWatering -= 10 # Changes the current mode elif self.configMenuSelected == self.MODE_SELECTION_CONFIG_MENU: length = len(self.modeList) if param.GPIO['btn']['up'][1] == channel: self.currentModeSelected = self.currentModeSelected + 1 if self.currentModeSelected < length - 1 else 0 if param.GPIO['btn']['bottom'][1] == channel: self.currentModeSelected = self.currentModeSelected - 1 if self.currentModeSelected > 0 else length - 1 # Change the current datetime of the OS elif self.configMenuSelected == self.CHANGE_DAY_DATE_CONFIG_MENU: if param.GPIO['btn']['up'][1] == channel: subprocess.call(["sudo", "date", "-s", "+1 day"]) elif param.GPIO['btn']['bottom'][1] == channel: subprocess.call(["sudo", "date", "-s", "-1 day"]) subprocess.call(["sudo", "hwclock", "-w"]) elif self.configMenuSelected == self.CHANGE_MONTH_DATE_CONFIG_MENU: if param.GPIO['btn']['up'][1] == channel: subprocess.call(["sudo", "date", "-s", "+1 month"]) elif param.GPIO['btn']['bottom'][1] == channel: subprocess.call(["sudo", "date", "-s", "-1 month"]) subprocess.call(["sudo", "hwclock", "-w"]) elif self.configMenuSelected == self.CHANGE_YEAR_DATE_CONFIG_MENU: if param.GPIO['btn']['up'][1] == channel: subprocess.call(["sudo", "date", "-s", "+1 year"]) elif param.GPIO['btn']['bottom'][1] == channel: subprocess.call(["sudo", "date", "-s", "-1 year"]) subprocess.call(["sudo", "hwclock", "-w"]) elif self.configMenuSelected == self.CHANGE_HOUR_DATE_CONFIG_MENU: if param.GPIO['btn']['up'][1] == channel: subprocess.call(["sudo", "date", "-s", "+1 hour"]) elif param.GPIO['btn']['bottom'][1] == channel: subprocess.call(["sudo", "date", "-s", "-1 hour"]) subprocess.call(["sudo", "hwclock", "-w"]) elif self.configMenuSelected == self.CHANGE_MINUTE_DATE_CONFIG_MENU: if param.GPIO['btn']['up'][1] == channel: subprocess.call(["sudo", "date", "-s", "+1 minute"]) elif param.GPIO['btn']['bottom'][1] == channel: subprocess.call(["sudo", "date", "-s", "-1 minute"]) subprocess.call(["sudo", "hwclock", "-w"]) # Stops or start the emergency def emergency_btn_pressed(self, channel): return self.last_activity = datetime.datetime.today() # Stops if self.emergency_on: if self.emergency_process.is_alive(): self.emergency_process.terminate() self.emergency_on = False self.currentMenuSelected = self.HOME_MENU GPIO.output(param.GPIO['led']['red'][1], GPIO.LOW) # Starts else: self.emergency_on = True self.currentMenuSelected = self.EMERGENCY_MENU self.stop_watering() # If an old process exists -> terminate if self.emergency_process: if self.emergency_process.is_alive(): self.emergency_process.terminate() self.emergency_process = None # Creation of the new process self.emergency_process = multiprocessing.Process(target=self.start_emergency) self.emergency_process.start() # Adds 10 minutes to the start time def add_start_time(self): if self.startTime[0] == 23 and self.startTime[1] == 50: self.startTime = [0, 0] elif self.startTime[1] == 50: self.startTime[0] += 1 self.startTime[1] = 0 else: self.startTime[1] += 10 # Removes 10 minutes to the start time def remove_start_time(self): if self.startTime[0] == 0 and self.startTime[1] == 0: self.startTime = [23, 50] elif self.startTime[1] == 00: self.startTime[0] -= 1 self.startTime[1] = 50 else: self.startTime[1] -= 10 # Returns the time 23h30 def display_time(self): hours = str(self.startTime[0]) if self.startTime[0] > 9 else "0" + str(self.startTime[0]) minutes = str(self.startTime[1]) if self.startTime[1] > 9 else "0" + str(self.startTime[1]) return hours + "h" + minutes # Displays the main menu def display_menu(self): self.mainMenu.get(self.currentMenuSelected)() # Display the menu to the LCD def display_2_lcd(self, lines): self.lcd.cursor_mode = CursorMode.hide blank_line = '{:^20}'.format(' ') for key, value in enumerate(lines): self.lcd.cursor_pos = (key, 0) if value: self.lcd.write_string('{:20}'.format(value)) else: self.lcd.write_string(blank_line) # Displays the home menu def display_menu_home(self): self.configMenuSelected = 0 today = datetime.datetime.today() line1 = '{:^20}'.format(today.strftime("%d/%m/%Y %H:%M")) line2 = '{:^20}'.format('Mode ' + self.modeList[self.currentModeSelected]) line4 = None # If watering ongoing if self.ongoingWatering: line3 = 'Arrosage en cours ' line4 = '{:^20}'.format(self.end_watering_in()) # If mode MANU elif self.modeList[self.currentModeSelected] == "MANU": line3 = 'Pas d\'arro programme' # If mode AUTO else: line3 = 'Proch. arro. dans: ' line4 = '{:^20}'.format(self.next_watering_in()) self.display_2_lcd([line1, line2, line3, line4]) # Displays the details of the selected configuration def display_config_details(self): self.configMenu[self.configMenuSelected][0]() def display_menu_start_stop_watering(self): if self.ongoingWatering: # If the ON mode is selected -> cant stop the watering if self.modeList[self.currentModeSelected] == 'ON': self.display_2_lcd([ "Impossible d'arreter", "l'arrosage en cours", '{:^20}'.format("Mode ON active"), None ]) else: self.stop_watering() self.display_2_lcd([ None, '{:^20}'.format("Arret de l'arrosage"), '{:^20}'.format("en cours..."), None ]) else: # If the OFF mode is selected -> cant start the watering if self.modeList[self.currentModeSelected] == 'OFF': self.display_2_lcd([ "Impossible d'allumer", "l'arrosage", '{:^20}'.format("Mode OFF active"), None ]) else: self.start_watering() self.display_2_lcd([ None, '{:^20}'.format('Demarrage de'), '{:^20}'.format("l'arrosage en cours..."), None ]) time.sleep(3) self.currentMenuSelected = self.HOME_MENU def display_menu_watering_days(self): self.display_2_lcd([ 'Arrosage tous les ', '{:^20}'.format(str(self.daysBetweenWatering) + ' jours'), None, '<Retour Home>' ]) def display_menu_start_time(self): self.display_2_lcd([ 'Arrosage a partir de', '{:^20}'.format(self.display_time()), None, '<Retour Home>' ]) def display_menu_duration(self): self.display_2_lcd([ 'Arrosage pendant ', '{:^20}'.format(str(self.durationOfWatering) + ' min'), None, '<Retour Home>' ]) def display_menu_mode(self): mode = "" for key, val in enumerate(self.modeList): if key == self.currentModeSelected: mode += " >" + val + "< " else: mode += " " + val.lower() + " " self.display_2_lcd([ 'Mode d\'arrosage ', '{:^20}'.format(mode), None, '<Retour Home>' ]) def display_menu_change_day_date(self): today = datetime.datetime.today() day = today.strftime("%d") month = today.strftime("%m") year = today.strftime("%Y") hour = today.strftime("%H") minute = today.strftime("%M") self.display_2_lcd([ 'Changement du jour', '{:^20}'.format('>' + day + '<' + '/' + month + '/' + year), '{:^20}'.format(hour + ':' + minute), '<Retour Home>' ]) def display_menu_change_month_date(self): today = datetime.datetime.today() day = today.strftime("%d") month = today.strftime("%m") year = today.strftime("%Y") hour = today.strftime("%H") minute = today.strftime("%M") self.display_2_lcd([ 'Changement du mois', '{:^20}'.format(day + '/' + '>' + month + '<' + '/' + year), '{:^20}'.format(hour + ':' + minute), '<Retour Home>' ]) def display_menu_change_year_date(self): today = datetime.datetime.today() day = today.strftime("%d") month = today.strftime("%m") year = today.strftime("%Y") hour = today.strftime("%H") minute = today.strftime("%M") self.display_2_lcd([ 'Changement de l\'an', '{:^20}'.format(day + '/' + month + '/' + '>' + year + '<'), '{:^20}'.format(hour + ':' + minute), '<Retour Home>' ]) def display_menu_change_hour_date(self): today = datetime.datetime.today() day = today.strftime("%d") month = today.strftime("%m") year = today.strftime("%Y") hour = today.strftime("%H") minute = today.strftime("%M") self.display_2_lcd([ 'Changement de l\'heure', '{:^20}'.format(day + '/' + month + '/' + year), '{:^20}'.format('>' + hour + '<' + ':' + minute), '<Retour Home>' ]) def display_menu_change_minute_date(self): today = datetime.datetime.today() day = today.strftime("%d") month = today.strftime("%m") year = today.strftime("%Y") hour = today.strftime("%H") minute = today.strftime("%M") self.display_2_lcd([ 'Changement des min', '{:^20}'.format(day + '/' + month + '/' + year), '{:^20}'.format(hour + ':' + '>' + minute + '<'), '<Retour Home>' ]) def display_config_menu(self): if 1 <= self.configMenuSelected <= len(self.configMenu) - 2: config_menu = [self.configMenuSelected - 1, self.configMenuSelected, self.configMenuSelected + 1] elif self.configMenuSelected == len(self.configMenu) - 1: config_menu = [self.configMenuSelected - 2, self.configMenuSelected - 1, self.configMenuSelected] else: config_menu = [0, 1, 2] lines = [] for i in config_menu: if i == self.configMenuSelected: lines.append('{:-^20}'.format('>' + self.configMenu[i][1] + '<')) else: lines.append('{:^20}'.format(self.configMenu[i][1])) lines.append('<Home Select>') self.display_2_lcd(lines) def display_emergency(self): self.display_2_lcd([ '{:^20}'.format('Urgence activee !'), None, '{:^20}'.format('Systeme desactive'), None ]) # Returns True if it's necessary to watering # Returns False if not def has_to_water(self): time_dif = self.get_next_watering_date() - datetime.datetime.today() if math.ceil(time_dif.total_seconds() / 60) <= 0: return True return False # Returns the time before the next watering begin def next_watering_in(self): time_dif = self.get_next_watering_date() - datetime.datetime.today() return self.convert_time_dif_to_string(time_dif) # Returns the next datetime to be watered def get_next_watering_date(self): if self.lastWatering: next_watering_date = self.lastWatering + datetime.timedelta(days=self.daysBetweenWatering) else: next_watering_date = datetime.datetime.today() day = next_watering_date.strftime("%d") month = next_watering_date.strftime("%m") year = next_watering_date.strftime("%Y") hour = '{:02d}'.format(self.startTime[0]) minute = '{:02d}'.format(self.startTime[1]) return datetime.datetime.strptime(day + "/" + month + "/" + year + " " + hour + ":" + minute, "%d/%m/%Y %H:%M") # Returns the time until the watering is completed def end_watering_in(self): time_dif = self.endWateringDate - datetime.datetime.today() return self.convert_time_dif_to_string(time_dif) # Converts the time difference to a string def convert_time_dif_to_string(self, time_dif): seconds = time_dif.seconds minutes = math.floor(seconds / 60) hours = math.floor(minutes / 60) days = time_dif.days if days > 0: return str(days) + "j " + str(math.floor(seconds / 3600)) + "h" elif hours > 0: hours = math.floor(time_dif.seconds / 3600) return str(hours) + "h" + '%02d' % math.floor((seconds - hours * 3600) / 60) elif minutes > 0: return str(minutes) + " min" else: return str(seconds) + " sec" # Starts the watering def start_watering(self): # If the mode is OFF, cannot water if self.modeList[self.currentModeSelected] == "OFF": return # If the emergency is on if self.emergency_on: return GPIO.output(param.GPIO['relay'][1], GPIO.HIGH) self.ongoingWatering = True self.lastWatering = datetime.datetime.today() self.endWateringDate = self.lastWatering + datetime.timedelta(minutes=self.durationOfWatering) # Terminates an old process if exists if self.watering_process: if self.watering_process.is_alive: self.watering_process.terminate() self.watering_process = None self.watering_process = multiprocessing.Process(target=self.watering) self.watering_process.start() # Stops the watering def stop_watering(self): # If the current mode is ON, cannot stop the watering if self.modeList[self.currentModeSelected] == "ON" and not self.emergency_on: return if self.watering_process: if self.watering_process.is_alive(): self.watering_process.terminate() self.watering_process = None GPIO.output(param.GPIO['relay'][1], GPIO.LOW) self.ongoingWatering = False GPIO.output(param.GPIO['led']['green'][1], GPIO.LOW) # Blinks the LED during the watering def watering(self): green_led = param.GPIO['led']['green'][1] self.led_blink(green_led, 5, 0.1) while True: GPIO.output(green_led, GPIO.HIGH) time.sleep(1) GPIO.output(green_led, GPIO.LOW) time.sleep(1) # Blinks during 1 sec fast def led_blink(self, pin, how_much, how_fast): for i in range(how_much): GPIO.output(pin, GPIO.HIGH) time.sleep(how_fast) GPIO.output(pin, GPIO.LOW) time.sleep(how_fast) # Starts the emergency process def start_emergency(self): while True: GPIO.output(param.GPIO['led']['red'][1], GPIO.HIGH) time.sleep(1) GPIO.output(param.GPIO['led']['red'][1], GPIO.LOW) time.sleep(1) def switch_off_lcd(self): self.lcd.display_enabled = False self.lcd.backlight_enabled = False def switch_on_lcd(self): self.lcd.display_enabled = True self.lcd.backlight_enabled = True self.lcd.clear() self.lcd.cursor_pos = (0, 0) self.lcd.cursor_mode = CursorMode.hide
# callbacks def on_connect(client, userdata, flags, rc): print("Connected to broker with result code " + str(rc)) client.subscribe("arduino/pot0") # The callback for when a PUBLISH message is received from the server. def on_message(client, userdata, msg): print(msg.topic+" "+str(msg.payload)) lcd.cursor_pos = (1,0) # fill up the whole line with spaces to clear previous values. lcd.write_string(str(msg.payload).ljust(16)) lcd = CharLCD(pin_rs=25, pin_rw=None, pin_e=17, pins_data=[18, 22, 23, 24], numbering_mode=GPIO.BCM, cols=16, rows=2) lcd.clear() lcd.write_string('Messwert:') client = mqtt.Client() client.on_connect = on_connect client.on_message = on_message client.connect(HOSTNAME, PORT) try: client.loop_forever() except KeyboardInterrupt: print("^C received, shutting down subscriberLCD") lcd.close(clear=True)
lcd = CharLCD(cols=16, rows=2) # create custom chars :) and :(, block and ° happy = (0b00000, 0b01010, 0b01010, 0b00000, 0b10001, 0b10001, 0b01110, 0b00000) sad = (0b00000, 0b01010, 0b01010, 0b00000, 0b01110, 0b10001, 0b10001, 0b00000) block = (0b11111, 0b11111, 0b11111, 0b11111, 0b11111, 0b11111, 0b11111, 0b11111) degr = (0b01110, 0b01010, 0b01110, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000) lcd.create_char(0, sad) lcd.create_char(1, happy) lcd.create_char(2, block) lcd.create_char(3, degr) # endless loop while True: count = 0 lcd.clear() lcd.write_string(_get_time()) lcd.cursor_pos = (1, 0) # put smiley indicator if connected to the internet if _is_connected() == True: lcd.write_string(_get_ip()) lcd.cursor_pos = (1, 15) lcd.write_string(unichr(1)) else: lcd.write_string("Kein Internet!") lcd.cursor_pos = (1, 15) lcd.write_string(unichr(0)) # if button is hold, count hold time ############# if(GPIO.input(PIN_GPIO) == 0): # clear lcd
rows=2, pin_rs=37, pin_e=35, pins_data=[33, 31, 29, 23]) GPIO.setup(11, GPIO.IN) # MQ-9 Dout GPIO.add_event_detect(11, GPIO.FALLING, callback=onMQ9FallingEdge, bouncetime=2000) try: blinkState = True running = True while running: try: lcd.write_string(('R' if blinkState else ' ') + ' ' + ip_addr()) except OSError: lcd.clear() lcd.write_string(('E' if blinkState else ' ') + ' No IP Address') lcd.crlf() lcd.write_string('MQ-9:' + ('Safe' if GPIO.input(11) else 'Warn')) lcd.write_string(' FB:' + ('OK' if chat_thread.is_alive() else 'NO')) blinkState = not blinkState time.sleep(1) lcd.clear() except (KeyboardInterrupt, EOFError): running = False finally: lcd.clear() lcd.write_string('E ' + ip_addr() + '\n\rPy Not Running') GPIO.cleanup()
pass RPIO.setwarnings(False) lcd = CharLCD() input('Display should be blank. ') lcd.cursor_mode = CursorMode.blink input('The cursor should now blink. ') lcd.cursor_mode = CursorMode.line input('The cursor should now be a line. ') lcd.write_string('Hello world!') input('"Hello world!" should be on the LCD. ') assert lcd.cursor_pos == (0, 12), 'cursor_pos should now be (0, 12)' lcd.cursor_pos = (1, 0) lcd.write_string('2') lcd.cursor_pos = (2, 0) lcd.write_string('3') lcd.cursor_pos = (3, 0) lcd.write_string('4') assert lcd.cursor_pos == (3, 1), 'cursor_pos should now be (3, 1)' input('Lines 2, 3 and 4 should now be labelled with the right numbers. ') lcd.clear() input('Display should now be clear, cursor should be at initial position. ')
from RPLCD import CharLCD import time lcd = CharLCD(cols=16, rows=2, pin_rs=37, pin_e=35, pins_data=[33, 31, 29, 23]) while True: lcd.write_string("Time: %s" % time.strftime("%H:%M:%S")) lcd.cursor_pos = (1, 0) lcd.write_string("Date: %s" % time.strftime("%m/%d/%Y"))
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_f init_db() while True: date = datetime.now().strftime('%Y-%m-%d %H:%M:%S') temp = read_temp() #print("%s %s" % (date, temp)) insert(date, temp) door = 0; lcd.clear() ipaddr = run_cmd(cmd) lcd.cursor_pos = (0,0) lcd.write_string("%s" % date) lcd.cursor_pos = (1,0) lcd.write_string("IP: %s" % ipaddr) lcd.cursor_pos = (2,0) lcd.write_string("Temp: %sF" % temp) lcd.cursor_pos = (3,0) lcd.write_string("Opened Today: %s" % door) time.sleep(5)
GPIO.add_event_detect(21, GPIO.FALLING, callback=button_delete) GPIO.add_event_detect(19, GPIO.FALLING, callback=button_send) lcd= CharLCD(numbering_mode=GPIO.BOARD, cols=20, rows=4, pin_rs=37, pin_e=35, pins_data=[40,38,36,32,33,31,29,23], dotsize=8, auto_linebreaks=True) r= sr.Recognizer() mic=sr.Microphone() while True: with mic as source: try: audio=r.listen(source) hasil=r.recognize_google(audio, language='id-ID') print(hasil) lcd.clear() lcd.write_string(hasil) if(hasil=="menu"): lcd.clear() lcd.write_string("Selamat Mendengarkan Menu") os.system('aplay /home/pi/Downloads/menu.wav') else: record() except sr.UnknownValueError: print("coba ucapkan kembali") os.system('aplay /home/pi/Downloads/ulang.wav') GPIO.cleanup()
temp_c = str( round(temp_c, 1) ) # ROUND THE RESULT TO 1 PLACE AFTER THE DECIMAL, THEN CONVERT IT TO A STRING return temp_c #FAHRENHEIT CALCULATION def read_temp_f(): lines = read_temp_raw() 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_f = ( int(temp_string) / 1000.0 ) * 9.0 / 5.0 + 32.0 # TEMP_STRING IS THE SENSOR OUTPUT, MAKE SURE IT'S AN INTEGER TO DO THE MATH temp_f = str( round(temp_f, 1) ) # ROUND THE RESULT TO 1 PLACE AFTER THE DECIMAL, THEN CONVERT IT TO A STRING return temp_f while True: lcd.cursor_pos = (0, 0) lcd.write_string("Temp: " + read_temp_c() + unichr(223) + "C") lcd.cursor_pos = (1, 0) lcd.write_string("Temp: " + read_temp_f() + unichr(223) + "F")
from RPLCD import CharLCD # This is the library which we will be using for LCD Display from RPi import GPIO # This is the library which we will be using for using the GPIO pins of Raspberry PI import socket # This is the library which we will be using to check the socket and find IP import fcntl import struct # Initializing the LCD Display lcd = CharLCD(numbering_mode=GPIO.BOARD, cols=16, rows=2, pin_rs=37, pin_e=35, pins_data=[33, 31, 29, 23]) def get_ip_address(ifname): s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) return socket.inet_ntoa( fcntl.ioctl(s.fileno(), 0x8915, struct.pack('256s', ifname[:15]))[20:24]) lcd.write_string("IP Address:") lcd.cursor_pos = (1, 0) lcd.write_string(get_ip_address('eth0')) # Always Clean Up the GPIO after using the code GPIO.cleanup()
class Display(object): """ Represents a physical character dispaly """ COLUMNS = 16 """ configure the number of columns of the display """ ROWS = 2 """ configure the number of rows of the display """ SCROLL_STEP_DURATION = 0.3 # sec """ while scrolling text, how long to show one frame """ def __init__(self, pin_rs, pin_contrast, pin_rw, pin_e, pins_data): """ See the display manual for the meaning of the pins. :param pin_rs: the GPIO pin for RS :param pin_contrast: the GPIO pin for contrast :param pin_rw: the GPIO pin for RW :param pin_e: the GPIO pin for E :param pins_data: the GPIO data pins (array with 4 integers) :return: """ self.pins_data = pins_data self.pin_e = pin_e self.pin_rw = pin_rw self.pin_contrast = pin_contrast self.pin_rs = pin_rs self._queue = Queue() self.contrast = None self.lcd = None self.standby_function = None def start(self): """ start the worker thread to handle animation """ self.setup() worker_thread = threading.Thread(target=self._run) worker_thread.daemon = True worker_thread.start() LOG.debug("started display") def setup(self): """ setup GPIO pins and start GPIO PWM """ from RPLCD import CharLCD from RPi import GPIO as GPIO GPIO.setup(self.pin_contrast, GPIO.OUT) self.lcd = CharLCD( pin_rs=self.pin_rs, pin_rw=self.pin_rw, pin_e=self.pin_e, pins_data=self.pins_data, numbering_mode=GPIO.BOARD, cols=Display.COLUMNS, rows=Display.ROWS, dotsize=8, ) self.lcd.cursor_pos = (0, 0) # the contrast needs a curtain current, found value by try and error self.contrast = GPIO.PWM(self.pin_contrast, 1000) self.contrast.start(40) def _run(self): """ internal function that runs endless loop """ while True: # get message from the queue, wait if there is no message msg = self._queue.get(block=True) # set the cursor to row 0, column 0 self.lcd.home() start_time = time.time() while self._queue.empty() and (time.time() - start_time) < msg.duration: # the display is always filled with spaces. This avoids the requirement to call clear() and this # avoids flickering. self.lcd.write_string(msg.get_line1()) self.lcd.write_string(msg.get_line2()) # scroll the text one step msg.scroll() # sleep to keep the scrolling text for a moment (but stop if there is another message waiting) sleep_until(lambda: not self._queue.empty(), Display.SCROLL_STEP_DURATION) # if the queue is empty and there is a standby function: run it. if self._queue.empty(): if self.standby_function: self.standby_function() def set_standby_function(self, func): """ defines a function that should be run when there is nothing else to display. :param func: the function that will be called """ self.standby_function = func def show(self, sec, line1, line2="", scroll=True, centered=True): """ show the given text on the display. The request is queued until the previous request has finished. :param sec: how many seconds to display the text for :param line1: text for first line :param line2: text for second lind :param scroll: True to enable scrolling :param centered: True to center the text (looks nice!) """ msg = Display.Message( duration=sec, scroll=scroll, line1=Display.Line(line1, scroll=scroll, centered=centered), line2=Display.Line(line2, scroll=scroll, centered=centered), ) self._queue.put(msg) class Line(object): """ Represents one line on the display . It has its own scroll state. """ SCROLL_BREAK = " - " """ symbols to show between text when scrolling """ def __init__(self, text, scroll=False, centered=False): """ :param text: text to scroll :param scroll: True to enable scrolling :param centered: True to center the text (looks nice!) """ self.text = Display.Line._clean(text) if centered: spaces = Display.COLUMNS - len(self.text) if spaces > 0: leftspaces = int(spaces / 2) rightspaces = int(spaces - leftspaces) self.text = " " * leftspaces + self.text + " " * rightspaces # only scroll if the text is too long self.scroll_enabled = scroll and len(self.text) > Display.COLUMNS # current scroll position self.scroll_offset = 0 def get(self): """ the text that should be displayed in the current scrolling position """ if self.scroll_enabled: long_line = self.text + Display.Line.SCROLL_BREAK + self.text result = long_line[self.scroll_offset : Display.COLUMNS + self.scroll_offset] else: result = self.text[0 : Display.COLUMNS] return result.ljust(Display.COLUMNS) def scroll(self): """ scroll one step (if enabled) """ if self.scroll_enabled: self.scroll_offset += 1 if self.scroll_offset == len(self.text) + len(Display.Line.SCROLL_BREAK): self.scroll_offset = 0 @staticmethod def _clean(string): """ internal helper method to strip newlines from the string. Newlines are shown as empty character, which is not what we want. :param string: string to clean :return: cleaned string """ return string.replace("\n", "").strip() def __str__(self): """ :return: text representation for debugging """ return "%s" % self.text class Message: """ represents a message to display, may contain 2 lines. """ def __init__(self, duration, line1, line2, scroll=True): """ :param duration: how many seconds to display the text for :param line1: text for first line :param line2: text for second lind :param scroll: True to enable scrolling """ self.line1 = line1 self.line2 = line2 self.duration = duration def scroll(self): """ scroll one step (if enabled) """ self.line1.scroll() self.line2.scroll() def get_line1(self): """ :return: the text that should be displayed in line 1 in the current scrolling position """ return self.line1.get() def get_line2(self): """ :return: the text that should be displayed in line 2 in the current scrolling position """ return self.line2.get() def __str__(self): """ :return: text representation for debugging """ return "%s/%s(%s sec)" % (self.line1, self.line2, self.duration)
# draw a line from start to end i.e. the convex points (finger tips) # (can skip this part) cv2.line(crop_img, start, end, [0, 255, 0], 2) #cv2.circle(crop_img,far,5,[0,0,255],-1) # define actions required if count_defects == 2: str = "2 Forward" cv2.putText(img, str, (5, 50), cv2.FONT_HERSHEY_SIMPLEX, 1, 2) lcd = CharLCD(numbering_mode=GPIO.BOARD, cols=16, rows=2, pin_rs=37, pin_e=35, pins_data=[40, 38, 36, 32, 33, 31, 29, 23]) lcd.write_string("2 Forward") GPIO.cleanup() elif count_defects == 3: cv2.putText(img, "3 Backward", (50, 50), cv2.FONT_HERSHEY_SIMPLEX, 2, 2) lcd = CharLCD(numbering_mode=GPIO.BOARD, cols=16, rows=2, pin_rs=37, pin_e=35, pins_data=[40, 38, 36, 32, 33, 31, 29, 23]) lcd.write_string("3 Backward") GPIO.cleanup() elif count_defects == 4: cv2.putText(img, "4 Left", (50, 50), cv2.FONT_HERSHEY_SIMPLEX, 2, 2) lcd = CharLCD(numbering_mode=GPIO.BOARD,
lcd = CharLCD(cols=cols, rows=rows) print('This tool shows the character map of your LCD on the display.') print('Press ctrl+c at any time to abort.\n') page = 0 chars = rows * cols try: while True: offset = page * chars start = offset end = offset + chars lcd.clear() for i in range(offset, offset + chars): if i > 255: if i > start: print('Displaying page %d (characters %d-%d).\nDone.' % (page, start, i - 1)) else: print('Done.') sys.exit(0) lcd.write_string(unichr(i)) page += 1 safe_input('Displaying page %d (characters %d-%d). Press <ENTER> to continue.' % (page, start, end - 1)) except KeyboardInterrupt: print('Aborting.') lcd.clear()
def main(argv): # Get path to connections file connections_file_path = os.path.join(os.getcwd(), CONNECTIONS_FILE) # Wait for connections file while not os.path.exists(connections_file_path): time.sleep(1) # Holds extracted topics/broker ips topics = [] broker_ips = [] # Parse connections file with open(connections_file_path, "r") as file: # Read connections file line by line for line in file.readlines(): # Extract topic and ip address splits = line.split('=') ex_topic = splits[0].strip('\n').strip() ex_ip = splits[1].strip('\n').strip() # Update lists topics.append(ex_topic) broker_ips.append(ex_ip) # Choose hostname/publish topic for MQTT client hostname = broker_ips[0] topic_pub = topics[0] # Get id of the component that hosts this adapter component_id = topic_pub.split('/')[1] # Generate client id client_id = "id_%s" % (datetime.utcnow().strftime('%H_%M_%S')) # Generate action topic to subscribe to topic_sub = TOPIC_ACTION % component_id # Create and start MQTT client mqtt_client = MQTTClient(hostname, PORT, client_id) mqtt_client.start() mqtt_client.subscribe(topic_sub) # setup LCD lcd = CharLCD(pin_rs=7, pin_e=8, pins_data=[17, 18, 27, 22], numbering_mode=GPIO.BCM, cols=16, rows=2, dotsize=8) lcd.write_string('* TPL IoT Lab * > Press a button') initButtons() # Keep script running while True: v = checkSwitch() #print ("Button 1: ", v[0], " Button 2: ", v[1], " Button 3: ", v[2], " Button 4: ", v[3]) if (v[0] == True): os.system("espeak -ven+f5 -s130 \'" + TEXT_1 + "\' --stdout | aplay") elif (v[1] == True): TEXT_2 = os.popen("curl http://wttr.in/Stuttgart?format=\'Current+temperature+in+%l:+%t+%C\'").readline() os.system("espeak -ven+f5 -s130 \'" + TEXT_2 + "\' --stdout | aplay") elif (v[2] == True): response = os.popen('vcgencmd measure_temp').readline() TEXT_3 = (res.replace("temp=","The CPU temperature of this Raspberry Pi is ").replace("'C\n"," Celsius degrees")) os.system("espeak -ven+f5 -s130 \'" + TEXT_3 + "\' --stdout | aplay") elif (v[3] == True): os.system("espeak -ven+f5 -s130 \'" + TEXT_4 + "\' --stdout | aplay")
from sys import stdin import RPi.GPIO as GPIO from RPLCD import CharLCD,CursorMode,cursor,ShiftMode,cleared GPIO.setwarnings(False) lcd = CharLCD(cols=20, rows=4, pin_rw=None, pin_rs=21, pin_e=20, pins_data=[18,23,24,25], #d4, d5, d6, d7 numbering_mode=GPIO.BCM) lcd.cursor_mode = CursorMode.blink my_cmd = "" my_username = getpass.getuser() my_perl = "" lcd.write_string("Press ENTER for LCD terminal") print "\nPress ENTER for LCD terminal\n"; my_wait = subprocess.check_output("/etc/wait.pl ",shell=True) if my_wait == "Timeout": lcd.clear() my_name = subprocess.check_output("hostname -A",shell=True) lcd.cursor_pos = (0,0) lcd.write_string(my_name) my_ip = subprocess.check_output("hostname -I",shell=True) lcd.cursor_pos = (2,0) lcd.write_string(my_ip) lcd.cursor_mode = CursorMode.hide exit(0) while my_perl != "Success!": lcd.clear() my_name = subprocess.check_output("hostname -A",shell=True)
def formatline(*args): line = "".join(args) linelen = len(line) if linelen < 20: pad = 20 - linelen return "{}{}{}".format(args[0], " " * pad, args[1]) gpio.setmode(gpio.BCM) # Pin Belegung festlegen lcd = CharLCD(pin_rs=7, pin_rw=4, pin_e=8, pins_data=[23, 18, 15, 14], numbering_mode=gpio.BCM, cols=20, rows=4, dotsize=8) lcd.write_string(sys.argv[2]) # Uhrzeit lcd.write_string(" ") # Freistelle lcd.write_string(sys.argv[1]) # Datum/ Ende mit Stelle 20 lcd.write_string(formatline("P: ", sys.argv[3])) lcd.write_string(formatline("D: ", sys.argv[4])) lcd.write_string(formatline("U: ", sys.argv[5])) #Display nicht loeschen nach Script stop mit false sonst nullt er das ! lcd.close(clear=false)
def checkSwitch(): v0 = not GPIO.input(4) v1 = not GPIO.input(23) v2 = not GPIO.input(10) v3 = not GPIO.input(9) return v3, v0, v1, v2 #return v0, v1, v2, v3 #lcd = CharLCD(cols=16, rows=2) #lcd = CharLCD(pin_rs=15, pin_rw=18, pin_e=16, pins_data=[21, 22, 23, 24], numbering_mode=GPIO.BOARD, cols=20, rows=4, dotsize=8) lcd = CharLCD(pin_rs=7, pin_e=8, pins_data=[17, 18, 27, 22], numbering_mode=GPIO.BCM, cols=16, rows=2, dotsize=8) lcd.write_string('Hi :)') lcd.home() initButtons() while (True): #print(checkSwitch()) v = checkSwitch() time.sleep(0.5) lcd.home() lcd.clear() lcd.write_string(str(v))
req = requests.get(BVG_STATION_URL) data = req.json() departures = data[0]['departures'] last_update = datetime.datetime.now() if __name__ == '__main__': GPIO.add_event_detect(7, GPIO.FALLING) GPIO.add_event_detect(12, GPIO.FALLING) GPIO.add_event_callback(7, next_callback, bouncetime=250) GPIO.add_event_callback(12, previous_callback, bouncetime=250) while True: button_pressed = last_button_pressed \ and (datetime.datetime.now() - last_button_pressed).total_seconds() < 10 \ or False if button_pressed or datetime.datetime.now().second % 10 <= 5: try: update_departures() except Exception as e: lcd.clear() lcd.write_string('oups') lcd.cursor_pos = (1, 0) lcd.write_string(('%s' % (e))[:15]) traceback.print_exc() else: if departures: print_departure_info(departures[index]) else: print_time() time.sleep(1)
import netifaces import time from subprocess import Popen, PIPE from RPLCD import CharLCD def run_cmd(cmd): p = Popen(cmd, shell=True, stdout=PIPE) output = p.communicate()[0] return output if __name__ == '__main__': lcd = CharLCD(pin_rs=37, pin_e=40, pin_rw=None, pins_data=[38, 35, 36, 33], cols=16, rows=2) try: while True: for interface in netifaces.interfaces(): addresses = netifaces.ifaddresses(interface) if netifaces.AF_INET in addresses: family = addresses[netifaces.AF_INET] for idx, address_attrs in enumerate(family): lcd.clear() lcd.write_string('{}'.format(interface)) lcd.cursor_pos = (1, 0) lcd.write_string(address_attrs['addr']) time.sleep(4) finally: lcd.close(clear=True)
self.lcd.write_string(line[:LCD_COLS] + '\n\r') def redraw(self): self.load_menu(mainmenu) def run_action(self): item = self.menu[self.menu_pos] function = item[-1] function(self.lcd) if __name__ == '__main__': # Disable warnings RPIO.setwarnings(False) # Initialize LCD lcd = CharLCD(pin_rs=PIN_LCD_RS, pin_rw=PIN_LCD_RW, pin_e=PIN_LCD_E, pins_data=PIN_LCD_DATA, numbering_mode=NUMBERING_MODE) p = Player(lcd) r = RotaryEncoder(p) try: RPIO.wait_for_interrupts() except KeyboardInterrupt: print('Exiting...') lcd.clear() lcd.write_string('Goodbye!')
for j in range(0,disp_line): cur_str = disp_list[i+j] if len(cur_str) < disp_col: cur_str = cur_str + (" "*(disp_col-len(cur_str))) string_to_display += cur_str lcd_obj.clear() lcd_obj.write_string(string_to_display) time.sleep(sleep_time) while True: list_to_display = [] miner_ok = True try: lcd.clear() lcd.write_string("...REQUESTING... EXCHANGE DATA ") exchange_request = requests.get(exchange_url, verify=True, timeout=gen_timeout) exchange_json = exchange_request.json() error_status[0] = 0 except requests.exceptions.ConnectionError: error_status[0] = 1 except requests.exceptions.HTTPError: error_status[0] = 2 except requests.exceptions.Timeout: error_status[0] = 3 except requests.exceptions.SSLError: error_status[0] = 4 except requests.exceptions.RequestException: error_status[0] = 5 try: lcd.clear()