Beispiel #1
0
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 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)
Beispiel #3
0
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()
Beispiel #4
0
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)
Beispiel #5
0
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)
Beispiel #6
0
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()
Beispiel #7
0
    def __init__(self):
        """Initialize the nRF24 radio and the Raspberry Pi"""

        self.state = IDLE                            # current state
        self.lcd = None                              # LCD
        self.radio = None                            # nRF24 radio
        self.address = None                          # address of Cherry keyboard (CAUTION: Reversed byte order compared to sniffer tools!)
        self.channel = 6                             # used ShockBurst channel (was 6 for all tested Cherry keyboards)
        self.payloads = []                           # list of sniffed payloads
        self.kbd = None                              # keyboard for keystroke injection attacks

        try:
            # disable GPIO warnings
            GPIO.setwarnings(False)

            # initialize LCD
            self.lcd = CharLCD(cols=16, rows=2, pin_rs=15, pin_rw=18, pin_e=16, pins_data=[21, 22, 23, 24])
            self.lcd.clear()
            self.lcd.home()
            self.lcd.write_string(APP_NAME)
            self.lcd.cursor_pos = (1, 0)
            self.lcd.write_string(SYSS_BANNER)

            # use Raspberry Pi board pin numbers
            GPIO.setmode(GPIO.BOARD)

            # set up the GPIO pins
            GPIO.setup(RED_LED, GPIO.OUT, initial = GPIO.LOW)
            GPIO.setup(GREEN_LED, GPIO.OUT, initial = GPIO.LOW)
            GPIO.setup(BLUE_LED, GPIO.OUT, initial = GPIO.LOW)
            GPIO.setup(RECORD_BUTTON, GPIO.IN, pull_up_down = GPIO.PUD_DOWN)
            GPIO.setup(REPLAY_BUTTON, GPIO.IN, pull_up_down = GPIO.PUD_DOWN)
            GPIO.setup(ATTACK_BUTTON, GPIO.IN, pull_up_down = GPIO.PUD_DOWN)
            GPIO.setup(SCAN_BUTTON, GPIO.IN, pull_up_down = GPIO.PUD_DOWN)

            # set callcack functions
            GPIO.add_event_detect(RECORD_BUTTON, GPIO.RISING, callback = self.buttonCallback, bouncetime = 250)
            GPIO.add_event_detect(REPLAY_BUTTON, GPIO.RISING, callback = self.buttonCallback, bouncetime = 250)
            GPIO.add_event_detect(ATTACK_BUTTON, GPIO.RISING, callback = self.buttonCallback, bouncetime = 250)
            GPIO.add_event_detect(SCAN_BUTTON, GPIO.RISING, callback = self.buttonCallback, bouncetime = 250)

            # initialize radio
            self.radio = nrf24.nrf24()

            # enable LNA
            self.radio.enable_lna()

            # show startup info for some time with blinkenlights
            self.blinkenlights()

            # start scanning mode
            self.setState(SCAN)
        except:
            # error when initializing Radio Hack Box
            self.lcd.clear()
            self.lcd.home()
            self.lcd.write_string(u"Error: 0xDEAD")
            self.lcd.cursor_pos = (1, 0)
            self.lcd.write_string(u"Please RTFM!")
Beispiel #8
0
    def __init__(self):

        if gv.SYSTEM_MODE == 1 and (gv.USE_HD44780_16x2_LCD or gv.USE_HD44780_20x4_LCD):

            # Timing constants
            self.E_PULSE = 0.0005
            self.E_DELAY = 0.0005

            self.display_called = False
            self.temp_display = False

            if gv.IS_DEBIAN:
                self.thread_sleep = 0.05
            else:
                self.thread_sleep = 0.1

            self.timeout_init = 2  # default timeout reset time
            self.timeout_length = self.timeout_init  # initial timeout length (timeout_custom will override)

            self.STRING_1 = ''
            self.STRING_2 = ''
            self.STRING_3 = ''
            self.STRING_4 = ''
            self.STRING_1_PRIORITY = ''
            self.STRING_2_PRIORITY = ''
            self.STRING_3_PRIORITY = ''
            self.STRING_4_PRIORITY = ''

            self.loop_alive = True

            if gv.IS_DEBIAN:
                import RPi.GPIO as GPIO
                from RPLCD import CursorMode
                from RPLCD import CharLCD

                self.lcd = CharLCD(pin_rs=gv.GPIO_LCD_RS, pin_rw=None, pin_e=gv.GPIO_LCD_E,
                                   pins_data=[gv.GPIO_LCD_D4, gv.GPIO_LCD_D5, gv.GPIO_LCD_D6, gv.GPIO_LCD_D7],
                                   numbering_mode=GPIO.BCM, cols=gv.LCD_COLS, rows=gv.LCD_ROWS, charmap='A00')

                self.lcd.clear()

                # Hide the cursor
                self.lcd._set_cursor_mode(CursorMode.hide)

                # Fill the display with blank spaces
                for i in xrange(1, gv.LCD_ROWS+1):
                    self.lcd_string(' ', i)

                # Write custom codes to the LCD
                self.lcd.create_char(1, lcdcc.block)
                self.lcd.create_char(2, lcdcc.pause)
                self.lcd.create_char(3, lcdcc.voice_button_on)
                self.lcd.create_char(4, lcdcc.voice_button_off)
                self.lcd.create_char(5, lcdcc.block2)
                self.lcd.create_char(6, lcdcc.loading_hour_glass)

        self.LCDThread = threading.Thread(target=self.lcd_main)
        self.LCDThread.daemon = True
        self.LCDThread.start()
Beispiel #9
0
	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 __init__(self):

        self.code = None
        self.start_time = time.time()
        self.send_to_db = False
        self.delete_wait_time = 5

        # for BCM Mode
        # lcd_rs = 25
        # lcd_en = 24
        # lcd_d4 = 23
        # lcd_d5 = 17
        # lcd_d6 = 18
        # lcd_d7 = 22
        # lcd_backlight = 4

        # for Board Mode
        lcd_rs = 22
        lcd_en = 18
        lcd_d4 = 16
        lcd_d5 = 11
        lcd_d6 = 12
        lcd_d7 = 15
        lcd_backlight = 4

        # Define LCD column and row size for 16x2 LCD.
        lcd_columns = 16
        lcd_rows = 2

        self.lcd = CharLCD(cols=lcd_columns,
                           rows=lcd_rows,
                           pin_rs=lcd_rs,
                           pin_e=lcd_en,
                           pins_data=[lcd_d4, lcd_d5, lcd_d6, lcd_d7],
                           numbering_mode=GPIO.BOARD)
        self.lcd.clear()

        self.db = MongoDB()

        GPIO.setmode(GPIO.BOARD)
        self.red_light = 40
        self.green_light = 37
        self.buzzer = 38
        self.button_remove = 32

        GPIO.setup(10, GPIO.IN,
                   pull_up_down=GPIO.PUD_DOWN)  # button for delete
        GPIO.setup(self.green_light, GPIO.OUT)  # Green Light
        GPIO.setup(self.red_light, GPIO.OUT)  # Red Light
        GPIO.setup(self.buzzer, GPIO.OUT)  # Buzzer
        GPIO.setup(self.button_remove, GPIO.IN,
                   pull_up_down=GPIO.PUD_DOWN)  # button for remove

        GPIO.add_event_detect(10, GPIO.RISING, callback=self.button_callback)
        GPIO.add_event_detect(self.button_remove,
                              GPIO.RISING,
                              callback=self.remove_item)
Beispiel #11
0
 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")
Beispiel #12
0
def lcd_init():
    global lcd
    pin_rs = 21  # Board: 40
    pin_e = 20  # Board: 38
    pins_data = [16, 26, 19, 13]  # Board: 36, 37, 35, 33
    lcd = CharLCD(numbering_mode=GPIO.BCM,
                  cols=16,
                  rows=2,
                  pin_rs=pin_rs,
                  pin_rw=None,
                  pin_e=pin_e,
                  pins_data=pins_data)
    lcd.clear()
Beispiel #13
0
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()
Beispiel #14
0
    def __init__(self):

        if gv.IS_DEBIAN:
            self.thread_sleep = 0.1
        else:
            self.thread_sleep = 0.2

        self.timeout_init = 3  # 3 sec
        self.timeout_init /= self.thread_sleep  # Adjust according to while loop sleep time
        self.timeout = self.timeout_init
        self.display_called = False

        if (gv.USE_HD44780_16x2_LCD or gv.USE_HD44780_20x4_LCD
                or gv.USE_I2C_16X2DISPLAY) and gv.IS_DEBIAN:

            import lcdcustomchars as lcdcc
            import RPi.GPIO as GPIO
            from RPLCD import CharLCD

            if (gv.USE_HD44780_16x2_LCD or gv.USE_HD44780_20x4_LCD):
                self.lcd = CharLCD(pin_rs=gv.GPIO_LCD_RS,
                                   pin_rw=None,
                                   pin_e=gv.GPIO_LCD_E,
                                   pins_data=[
                                       gv.GPIO_LCD_D4, gv.GPIO_LCD_D5,
                                       gv.GPIO_LCD_D6, gv.GPIO_LCD_D7
                                   ],
                                   numbering_mode=GPIO.BCM,
                                   cols=gv.LCD_COLS,
                                   rows=gv.LCD_ROWS,
                                   charmap='A00')

            elif (gv.USE_I2C_16X2DISPLAY):
                self.lcd = CharLCD('PCF8574', gv.I2C_16x2DISPLAY_ADDR)

            self.lcd.create_char(1, lcdcc.block)
            self.lcd.create_char(2, lcdcc.arrow_right_01)
            self.lcd.create_char(3, lcdcc.voice_button_on)
            self.lcd.create_char(4, lcdcc.voice_button_off)

        if (gv.USE_HD44780_16x2_LCD
                or gv.USE_HD44780_20x4_LCD) and gv.SYSTEM_MODE == 2:

            self.STRING_1 = ''
            self.STRING_2 = ''

        self.LCDThread = threading.Thread(target=self.lcd_main)
        self.LCDThread.daemon = True
        self.LCDThread.start()
    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()
Beispiel #16
0
 def __init__(self):
     self.activated = False
     self.lcd = CharLCD(cols=16,
                        rows=2,
                        pin_rs=6,
                        pin_e=5,
                        pins_data=[13, 19, 26, 1],
                        numbering_mode=GPIO.BCM)
Beispiel #17
0
def initLCD():
    lcd = CharLCD(cols=24,
                  rows=2,
                  pin_rs=26,
                  pin_e=24,
                  pins_data=[16, 18, 22, 8],
                  numbering_mode=GPIO.BOARD)
    biglcd.createLcdCustomChar(lcd)
    return lcd
def getDefaultLCD():
    # Setup 16x2 LCD
    lcd = CharLCD(cols=16,
                  rows=2,
                  pin_rs=15,
                  pin_e=16,
                  pins_data=[36, 33, 31, 29],
                  numbering_mode=GPIO.BOARD,
                  auto_linebreaks=True,
                  charmap="A02")
    return lcd
Beispiel #19
0
    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()
Beispiel #20
0
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.
 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)
Beispiel #23
0
def refresh():
    lcd = CharLCD(pin_rs=37,
                  pin_rw=22,
                  pin_e=35,
                  pins_data=[33, 40, 38, 36],
                  numbering_mode=GPIO.BOARD,
                  cols=16,
                  rows=2,
                  dotsize=8,
                  auto_linebreaks=True,
                  pin_backlight=None,
                  backlight_enabled=True,
                  backlight_mode=BacklightMode.active_low)
Beispiel #24
0
    def __init__(self):
        # hardcoded PINOUT
        self.sensor_left 	= SonicSensor(trig_pin=16, echo_pin=12, numbering_mode=GPIO.BCM)
        self.sensor_right 	= SonicSensor(trig_pin=18, echo_pin=24, numbering_mode=GPIO.BCM)
        self.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])
        self.rotary 		= RotaryEncoder(dt_pin=3, clk_pin=4, lower_limit=0, upper_limit=40)
        self.button 		= Button(pin=2)

        # parameters for filtering and smoothing
        # self.interval	= ??	# 
        self.window 	= 30    # for filters and running smoother
        self.threshold 	= 3  	# for filters
        self.weight 	= .3    # for exponential smoother
        self.iterations = 3    # for exponential smoother
        self.lag        = 10 	# for peak detection. Probably not needed as using a simple peak detector
        
        # memory for both sensors
        self.raw_data_left  = deque([-1]*self.window, maxlen=self.window)
        self.raw_data_right = deque([-1]*self.window, maxlen=self.window)
        self.data_left  = deque([-1]*self.window, maxlen=self.window)
        self.data_right = deque([-1]*self.window, maxlen=self.window)


        # parameters and variables for tide
        self.initial_water_level        = -1    # mean measured from past hour
        self.initial_median_dist        = 0     # man measured distance from past readings
        self.current_median_dist        = 0     # 
        self.tide_window                = 1001
        self.points_for_median_dist     = deque(maxlen=self.tide_window)   # used for adding points to running average
        
        # parameters and variables for speed
        self.sensor_spacing     = 10    # cm 
        self.delay              = .3    # time to do one iteration
        self.left_peak          = False
        self.counter            = -1    # used as unit of time

        # misc
        self.calibration_delay = 0  # s   time used after setting water level to move sensor into place
        self.line2 = u'Wave: None'
Beispiel #25
0
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())
Beispiel #26
0
    def __init__(self,
                 rsPin,
                 enPin,
                 d4Pin,
                 d5Pin,
                 d6Pin,
                 d7Pin,
                 boardNum=GPIO.BCM,
                 rwPin=None,
                 cols=16,
                 rows=2,
                 warnings=False):

        if warnings is False:
            GPIO.setwarnings(False)

        self.cols = cols
        self.rows = rows

        self.firstRun = True

        self.lcd = CharLCD(cols=cols,
                           rows=rows,
                           pin_rw=rwPin,
                           pin_rs=rsPin,
                           pin_e=enPin,
                           pins_data=[d4Pin, d5Pin, d6Pin, d7Pin],
                           numbering_mode=boardNum)

        self.lcdmem = self._generate_lcd_memory()
        self.curpos = [0, 0]  # [row, column]

        self._warm_up_display()

        sleep(1)
        self.lcd.clear()
        sleep(1)
Beispiel #27
0
    def reboot_algorithm(self):
        CVProcessor.logger.info("Rebooting...")

        self.working_lock.acquire()

        self.car_names = {}
        self.tracker = Tracker()
        self.count = 0
        self.colors = {}
        self.times = {}
        self.car_detected_count = {}
        self.car_detected_names = {}
        self.last_reboot = time.time()
        self.working_lock.release()
        self.lcd = CharLCD(cols=16,
                           rows=2,
                           pin_rs=11,
                           pin_e=5,
                           pins_data=[6, 13, 19, 26],
                           numbering_mode=GPIO.BCM)
        self.lcd.clear()
        self.lcd.write_string(u'Running..')
        GPIO.output(CVProcessor.output_pin, GPIO.LOW)
        GPIO.output(CVProcessor.output_pin_puerta, GPIO.LOW)
Beispiel #28
0
    def stop(self):
        App.logger.info("Requesting stop")
        self.lcd = CharLCD(cols=16,
                           rows=2,
                           pin_rs=11,
                           pin_e=5,
                           pins_data=[6, 13, 19, 26],
                           numbering_mode=GPIO.BCM)
        self.isRunning = False

        if self.ocv:
            self.ocv.stop()

        if self.cvp:
            self.cvp.stop()

        App.logger.info("Stop requested")
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)
Beispiel #30
0
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
Beispiel #31
0
 def __init__(self, system, console=False):
     self.console = console
     if not on_rpi:
         self.console = True
     
     if self.console:
         lcd = None
     else:
         lcd = CharLCD(numbering_mode=GPIO.BCM,cols=16,rows=2,pin_rs=18,pin_e=23,pins_data=[24,25,12,16])
         
     self.display = LCDProxy(lcd=lcd)
     
     self.current_elem = build_menu(system.burner, system.temp, system.wifi_config)
     
     self.prev_menus = []
     
     self.update_display()
     self.event_queue = queue.Queue()
Beispiel #32
0
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()
Beispiel #33
0
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)
Beispiel #34
0
class HD44780Lcd(Lcd):

    _lines: list = ["", "", "", ""]
    _lcd = CharLCD(pin_rs=18,
                   pin_rw=23,
                   pin_e=24,
                   pins_data=[25, 8, 7, 12],
                   numbering_mode=GPIO.BCM,
                   cols=20,
                   rows=4,
                   dotsize=8)

    def write_line(self, num: int, value: str):
        self._lines[num] = value

    def flush(self):
        self._lcd.clear()
        for row, value in enumerate(self._lines):
            self._lcd.cursor_pos = (row, 0)
            self._lcd.write_string(value)
Beispiel #35
0
    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)
Beispiel #36
0
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])
Beispiel #37
0
	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)	
	GPIO.setup(10, GPIO.IN, pull_up_down=GPIO.PUD_UP)
	GPIO.setup(9, GPIO.IN, pull_up_down=GPIO.PUD_UP)

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))
Beispiel #39
0
import re
import string
import subprocess
import os
from os.path import expanduser
from getch import getch
import getpass
import time
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)
Beispiel #40
0
from __future__ import print_function, division, absolute_import, unicode_literals

import RPIO
from RPLCD import CharLCD
from RPLCD import Alignment, CursorMode, ShiftMode
from RPLCD import cursor, cleared

try:
    input = raw_input
except NameError:
    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)
default_cancel_pause_dur = 1.5 #minutes
kill_ui_thread=0
headers = {"Content-type": "application/x-www-form-urlencoded", "Accept": "text/plain"}
# ======================================================
h = httplib.HTTPConnection(server)

# ==========  Setup sensors ============================

# Set GPIO mode to BOARD (numbering by position)
#print GPIO.BCM
#print GPIO.getmode()
GPIO.setmode(GPIO.BCM)

# Setup LCD pins
lcd = CharLCD(pin_rs=7, pin_e=8,
              pins_data=[25, 24, 23, 18],
              numbering_mode=GPIO.BCM)
lcd.clear()

# Setup Keypad pins
MATRIX = [[1, 2, 3, 'A'],
          [4, 5, 6, 'B'],
          [7, 8, 9, 'C'],
          ['*', 0, '#', 'D']]
ROW = [10, 9, 11, 5]
COL = [6, 13, 19, 26]

for j in range(4):
    GPIO.setup(COL[j], GPIO.OUT)
    GPIO.output(COL[j], 1)
Beispiel #42
0
Second_Line_Out = Text_Out.split("\n")[1]
Temperature_Data_Out = Second_Line_Out.split(" ")[9]
Temperature_Out = float(Temperature_Data_Out[2:])
Temperature_Out = Temperature_Out / 1000
# print Temperature_Out

# 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. 
Beispiel #43
0
 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 = {}
Beispiel #44
0
from RPLCD import CharLCD
from RPLCD import Alignment, CursorMode, ShiftMode
from RPLCD import cursor, cleared

try:
    input = raw_input
except NameError:
    pass

try:
    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)
Beispiel #45
0
from RPLCD import Alignment, CursorMode, ShiftMode
from RPLCD import cursor, cleared
from RPLCD import BacklightMode

try:
    input = raw_input
except NameError:
    pass

try:
    unichr = unichr
except NameError:
    unichr = chr


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. ')
Beispiel #46
0
from __future__ import print_function, division, absolute_import, unicode_literals

import RPIO
from RPLCD import CharLCD
from RPLCD import Alignment, CursorMode, ShiftMode
from RPLCD import cursor, cleared

try:
    input = raw_input
except NameError:
    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)
Beispiel #47
0
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)
Beispiel #48
0
 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()
PORT = 1883

# 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")
Beispiel #50
0
		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)
Beispiel #51
0
import RPi.GPIO as GPIO
from RPLCD import CharLCD, cleared, cursor
from datetime import datetime
import time

LED_ON = 11

lcd = CharLCD(pin_rs=15, pin_e=13, pins_data=[22, 18, 16, 12],
              numbering_mode=GPIO.BOARD,
              cols=20, rows=4, dotsize=8)

smiley = (
     0b00000,
     0b01010,
     0b01010,
     0b00000,
     0b10001,
     0b10001,
     0b01110,
     0b00000,
)

a0 = (
  0b00000,
  0b00000,
  0b00000,
  0b00000,
  0b00011,
  0b01111,
  0b01111,
  0b11111
Beispiel #52
0
import time
import requests
import traceback
import re
from RPLCD import CharLCD
import RPi.GPIO as GPIO

OPEN_WEATHER_API_KEY = 'API KEY'
DEPARTURES_REFRESH_DELAY = 2
METEO_REFRESH_DELAY = 15
BVG_STATION_URL = 'https://realtime-bvg.herokuapp.com/station/9076101?realtime=true'  # Hetzbergplatz realtime
# BVG_STATION_URL = 'https://bvg-api.herokuapp.com/station/9076101'  # Hetzbergplatz
# BVG_STATION_URL = 'https://bvg-api.herokuapp.com/station/9013101'  # Moritzplatz
METEO_URL = 'http://api.openweathermap.org/data/2.5/weather?q=berlin,de&APPID=%s' % (OPEN_WEATHER_API_KEY)

lcd = CharLCD(cols=16, rows=2, auto_linebreaks=False)
GPIO.setmode(GPIO.BOARD)
GPIO.setup(7, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(12, GPIO.IN, pull_up_down=GPIO.PUD_UP)


index = 0
departures = []
last_update = None
last_button_pressed = None
temperature = None
last_meteo_update = None


def parse_bus_date(departure):
    date = list(reversed(departure['date'].split('.'))) + list(departure['time'].split(':'))
Beispiel #53
0
		ip_file = open('/media/ramdisk/log/my_ip.log','r')
		ip_add = ip_file.readline()
		ip_add = ip_add.rstrip(os.linesep)
	except:
		ip_add = "no IP yet..."
	#print ip_add
	return ip_add


# init gpio
GPIO.setmode(GPIO.BOARD)
GPIO.setwarnings(False)
GPIO.setup(PIN_GPIO, GPIO.IN, pull_up_down = GPIO.PUD_UP)

# init LCD
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())
Beispiel #54
0
except NameError:  # Python 3
    safe_input = input

try:
    unichr = unichr
except NameError:  # Python 3
    unichr = chr


if __name__ == '__main__':
    if len(sys.argv) != 3:
        print('Usage: %s <rows> <cols>' % sys.argv[0])
        sys.exit(1)

    rows, cols = int(sys.argv[1]), int(sys.argv[2])
    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:
Beispiel #55
0
            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!')
#!/usr/bin/python

import RPi.GPIO as GPIO
import time
import Adafruit_DHT

from RPLCD import CharLCD

# 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
Beispiel #57
0
index_1 = 0
menu_level = 0
playlists = []

#sleep(60) #wait for mopidy to start

client = MPDClient()   
client.timeout = 10 
client.idletimeout = None
print "Hello"
client.connect("localhost", 6600)


print(client.mpd_version)

lcd = CharLCD(cols=col, rows=row, pin_rs=10, pin_e=36, pins_data=[40, 15, 16, 18])

eintraege = ["play", "pause", "playlists", "test4", "test5"]

def list_down(channel):
    global index_0
    global index_1
    global menu_level
    if menu_level == 0:
        index_0 = (index_0 + 1) % 5
        menu_0(index_0)
    elif menu_level == 1:
        index_1 = (index_1 +1) % (len(playlists))
        menu_1(index_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)
Beispiel #59
0
#! /usr/bin/env python2.7

import RPi.GPIO as GPIO
from RPLCD import CharLCD, cleared, cursor
from time import sleep

# Auspex LCD for Warhammer 40,000 Victory Point and Turn Tracking

# wired as here: https://github.com/dbrgn/RPLCD

# Initialize display. All values have default values and are therefore optional.

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)

# 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')
Beispiel #60
0
username_length = len(username)
monitored_general_blocks = ["lastheight","lastblockheight"]
monitored_general_blocks_display = ["BLK HIGH ","LAST BLK "]
monitored_general_stats = ["currndiff","p_hashrate1hr","u_hashrate1hr"]
monitored_general_stats_display = ["CURR DIFF ","POOLHR 1H ", "USERHR 1H "]
monitored_addresses = ["1BitcoinEaterAddressDontSendf59kuE"] #as many as you want, or none.
monitored_addresses_processed = "|".join(monitored_addresses)
general_url = "https://kano.is/index.php?k=api&username="******"&api=" + api_key + "&json=y"
miner_url = "https://kano.is/index.php?k=api&username="******"&api=" + api_key + "&json=y&work=y"
exchange_url = "https://www.bitstamp.net/api/ticker/"
wallet_url = "https://blockchain.info/q/addressbalance/" + monitored_addresses_processed
error_status = [0,0,0,0]
error_names = ["EXCHANGE STATS","GENERAL STATS","MINER STATS","WALLET STATS"]
error_types = ["CONNECTION ERROR", "HTTP ERROR", "TIMEOUT", "TLS/CIPHER ERROR", "GENERAL ERROR"]

lcd = CharLCD(pin_rs=40, pin_rw=None, pin_e=38, pins_data=[36, 32, 22, 18], cols=16, rows=2) #set these pins

GPIO.setup(miner_pin, GPIO.OUT)
GPIO.output(miner_pin, GPIO.HIGH)

def number_to_readable(in_num,pad_to=6):
	in_num = float(in_num)
	if in_num <= 0:
		return "0" * pad_to
	prefix = [" ","k","M","G","T","P","E","Z","Y"]
	decimal_amount = math.ceil(math.log(in_num,10))
	prefix_to_use = (decimal_amount-1)//3
	number_to_use = str(in_num / (10**(prefix_to_use*3)))[:pad_to-1]
	while len(number_to_use) < (pad_to-1):
		number_to_use = "0" + number_to_use
	return number_to_use + prefix[prefix_to_use]