예제 #1
0
def print_to_LCDScreen (message):
    try:
        lcd = Adafruit_CharLCD()
        lcd.begin(16,2)
        for x in range(0, 16):
            for y in range(0, 2):
                lcd.setCursor(x, y)
                lcd.message('>')
                time.sleep(.025)
        lcd.noDisplay()
        lcd.clear()
        lcd.message(str(message))
        for x in range(0, 16):
            lcd.DisplayLeft()
        lcd.display()
        for x in range(0, 16):
            lcd.scrollDisplayRight()
            time.sleep(.05)
        # lcd.noDisplay()
        # lcd.display()
        # lcd.blink()
        # lcd.noCursor()
        # lcd.clear()
        # lcd.noBlink()
        # lcd.begin(16, 2)
        # lcd.setCursor(7, 0)
        # lcd.message('123')
        # lcd.message('x')
        # lcd.clear()
        return 'ok'
    except Exception,e:
        return e
예제 #2
0
class LCD_display(object):
    bus = 1  # Note you need to change the bus number to 0 if running on a revision 1 Raspberry Pi.
    address = 0x20  # I2C address of the MCP230xx chip.
    gpio_count = 8  # Number of GPIOs exposed by the MCP230xx chip, should be 8 or 16 depending on chip.

    # LCD 20x4
    num_columns = 20
    num_lines = 4

    def __init__(self, init=True):
        # Create MCP230xx GPIO adapter.
        mcp = MCP230XX_GPIO(self.bus, self.address, self.gpio_count)

        # Create LCD, passing in MCP GPIO adapter.
        self.lcd = Adafruit_CharLCD(pin_rs=1,
                                    pin_e=2,
                                    pin_bl=7,
                                    pins_db=[3, 4, 5, 6],
                                    GPIO=mcp)
        if init:
            self.initialisation()

    def initialisation(self):
        self.lcd.clear()
        self.lcd.begin(self.num_columns, self.num_lines)
        self.lcd.backlightOn()
        self.lcd.setCursor(0, 0)
        #self.lcd.message(datetime.datetime.now().strftime(' %a %d %b - %H:%M'))

    def line_message(self, row, text):
        # set the position (row from 0 to 3)
        self.lcd.setCursor(0, row)
        # display the message
        self.lcd.message(text)

    def temperature(self, text):
        #set the position
        self.lcd.setCursor(0, 1)
        #display the message and value
        self.lcd.message("Temperature: %.2f" % text)
        self.lcd.write4bits(0xDF, True)  #display the degree symbol "°"
        self.lcd.message("C")

    def humidity(self, text):
        #set the position
        self.lcd.setCursor(0, 2)
        #display the message and value
        self.lcd.message("Humidity:   %.2f%%RH" % text)

    def pressure(self, text):
        #set the position
        self.lcd.setCursor(0, 3)
        #display the message and value
        self.lcd.message("Pressure: %.2fhPa" % text)

    def date(self):
        #set the position
        self.lcd.setCursor(0, 0)
        #display the message and value
        self.lcd.message(datetime.datetime.now().strftime(' %a %d %b  %H:%M'))
예제 #3
0
파일: RPiLogger.py 프로젝트: imoralesgt/WSN
class GUI(object):
	def __init__(self, rPI = True):
		self.rPI = rPI
		self.PUSH_BUTTONS = (17, 27, 22, 23)
		self.RDY = 24
		self.RST = 25
		if self.rPI:
			import RPi.GPIO as GPIO
			from Adafruit_CharLCD import Adafruit_CharLCD
			self.GPIO = GPIO
			self.lcd = Adafruit_CharLCD()
			GPIO.setwarnings(False)
			GPIO.setmode(GPIO.BCM)
			GPIO.setup(self.RDY, GPIO.OUT)

			#self.setRDYstate(1)

			self.showIntro()

			#self.setRDYstate(0)			

			GPIO.setup(self.RST, GPIO.OUT)
			self.sendRST()
			for i in self.PUSH_BUTTONS:
				GPIO.setup(i, GPIO.IN)

	def readPushButtons(self): #Wire pull-down resistors to each Push-Button
		state = []
		for i in self.PUSH_BUTTONS:
			state.append(self.GPIO.input(i))
		time.sleep(0.150) #Debouncing delay
		for i in range(len(self.PUSH_BUTTONS)):
			state[i] = self.GPIO.input(self.PUSH_BUTTONS[i]) and state[i]
		return state

	def setRDYstate(self, state):
		self.GPIO.output(self.RDY, state)

	def setRSTstate(self, state):
		self.GPIO.output(self.RST, state)

	def sendRST(self):
		self.setRSTstate(0)
		time.sleep(0.01)
		self.setRSTstate(1)

	def lcdClear(self):
		if self.rPI:
			self.lcd.clear()

	def lcdMessage(self, msg):
		if self.rPI:
			self.lcd.message(msg)

	def showIntro(self):
		msg = 'WSN Arquitectura' + '\n' + 'Inicializando...'
		self.lcdClear()
		self.lcdMessage(msg)
		time.sleep(4)
예제 #4
0
    class Display(Thread):
        # TODO: move this to a config file
        COLS = 16
        ROWS = 2
        COL_OFFSET = 2 # You may choose to add an offset to the original position
        DURATION = 15
        PREFIX = "WARNING: "

        def __init__(self, msg):
            Thread.__init__(self)
            LCDReactor.Display.START_POSITION = LCDReactor.Display.COLS - LCDReactor.Display.COL_OFFSET
            self.msgs = [LCDReactor.Display.PREFIX, msg]
            self.lcd = CharLCD(pin_rs=2, pin_e=4, pins_db=[3, 14, 25, 24])

        def init_display(self):
            self.lcd.clear()
            self.lcd.begin(LCDReactor.Display.COLS, LCDReactor.Display.ROWS)

        def display_message(self):
            self.lcd.setCursor(LCDReactor.Display.START_POSITION, 0)
            self.lcd.message(self.msgs[0])
            self.lcd.setCursor(LCDReactor.Display.START_POSITION, 1)
            self.lcd.message(self.msgs[1])

        def shift_text(self):
            self.lcd.DisplayLeft()
            time.sleep(0.3)

        def loop_message(self):
            # Calculate the maximum length and the start position
            # Needed for when the time runs out and the message is in the
            # middle of the LCD
            position = LCDReactor.Display.START_POSITION
            max_len = max(len(self.msgs[0]), len(self.msgs[1]))
            start_time = time.time()

            # Display for n seconds
            while time.time() < start_time + LCDReactor.Display.DURATION:
                self.shift_text()
                position = (position + 1) % max_len

            # If the text is in the middle of the screen, we want to shift it
            # off. The best way is to take the current position and move it
            # until the the position is out of the display.
            # "Out of display" is given by max_len (maximum image size) +
            # START_POSITION, since it starts in the right side of the LCD
            for x in range(position, LCDReactor.Display.START_POSITION + max_len):
                self.shift_text()

            self.lcd.clear()


        def display(self):
            self.init_display()
            self.display_message()
            self.loop_message()

        def run(self):
            self.display()
예제 #5
0
파일: orb.py 프로젝트: scarolan/weather_orb
def printLCD(string1, string2):
    '''Prints string1 and string2 onto a 16x2 character LCD.'''
    lcd = Adafruit_CharLCD()
    lcd.begin(16, 1)
    lcd.clear()
    sleep(0.5)
    lcd.message(string1 + "\n")
    lcd.message(string2)
예제 #6
0
def Pantalla(Linea1, Linea2):

        lcd = Adafruit_CharLCD()
        lcd.begin(16,1)
        lcd.clear()
        lcd.message(Linea1+"\n")
        lcd.message(Linea2)
        lcd.cerrar()
예제 #7
0
파일: orb.py 프로젝트: scarolan/weather_orb
def printLCD(string1, string2):
    '''Prints string1 and string2 onto a 16x2 character LCD.'''
    lcd = Adafruit_CharLCD()
    lcd.begin(16,1)
    lcd.clear()
    sleep(0.5)
    lcd.message(string1+"\n")
    lcd.message(string2)
예제 #8
0
class ScreenComponent(JNTComponent):
    """ A Screen component for gpio """
    def __init__(self, bus=None, addr=None, **kwargs):
        """
        """
        oid = kwargs.pop('oid', 'rpilcdchar.screen')
        name = kwargs.pop('name', "Screen")
        product_name = kwargs.pop('product_name', "Screen")
        product_type = kwargs.pop('product_type', "Screen")
        JNTComponent.__init__(self,
                              oid=oid,
                              bus=bus,
                              addr=addr,
                              name=name,
                              product_name=product_name,
                              product_type=product_type,
                              **kwargs)
        logger.debug("[%s] - __init__ node uuid:%s", self.__class__.__name__,
                     self.uuid)
        uuid = "message"
        self.values[uuid] = self.value_factory['action_string'](
            options=self.options,
            uuid=uuid,
            node_uuid=self.uuid,
            help='A message to print on the screen',
            label='Msg',
            default='Janitoo started',
            set_data_cb=self.set_message,
            is_writeonly=True,
            cmd_class=COMMAND_MOTOR,
            genre=0x01,
        )
        poll_value = self.values[uuid].create_poll_value(default=300)
        self.values[poll_value.uuid] = poll_value
        self.pin_lcd_rs = 27  # Note this might need to be changed to 21 for older revision Pi's.
        self.pin_lcd_en = 22
        self.pin_lcd_d4 = 25
        self.pin_lcd_d5 = 24
        self.pin_lcd_d6 = 23
        self.pin_lcd_d7 = 18
        self.pin_lcd_backlight = 4
        self.lcd_columns = 20
        self.lcd_rows = 4
        self.lcd = Adafruit_CharLCD(self.pin_lcd_rs, self.pin_lcd_en,
                                    self.pin_lcd_d4, self.pin_lcd_d5,
                                    self.pin_lcd_d6, self.pin_lcd_d7,
                                    self.lcd_columns, self.lcd_rows,
                                    self.pin_lcd_backlight)

    def set_message(self, node_uuid, index, data):
        """Set the message on the screen
        """
        try:
            self.lcd.clear()
            self.lcd.message(data)
        except Exception:
            logger.exception('Exception when displaying message')
def init(bus=1, address=0x20, gpio_count=8):
    # Create MCP230xx GPIO adapter.
    mcp = MCP230XX_GPIO(bus, address, gpio_count)

    # Create LCD, passing in MCP GPIO adapter.
    lcd = Adafruit_CharLCD(pin_rs=1, pin_e=2, pins_db=[3,4,5,6], GPIO=mcp)

    lcd.clear()
    return lcd
 def lcd_clear(self, topic, payload):
     """
     This method writes to the LCD
     """
     lcd = Adafruit_CharLCD(rs=26, en=19,
                    d4=13, d5=6, d6=5, d7=11,
                    cols=16, lines=2)
     lcd.clear()
     print("CLEARED")
예제 #11
0
def init(bus=1, address=0x20, gpio_count=8):
    # Create MCP230xx GPIO adapter.
    mcp = MCP230XX_GPIO(bus, address, gpio_count)

    # Create LCD, passing in MCP GPIO adapter.
    lcd = Adafruit_CharLCD(pin_rs=1, pin_e=2, pins_db=[3, 4, 5, 6], GPIO=mcp)

    lcd.clear()
    return lcd
예제 #12
0
class LCD_display(object):
    bus = 1         # Note you need to change the bus number to 0 if running on a revision 1 Raspberry Pi.
    address = 0x20  # I2C address of the MCP230xx chip.
    gpio_count = 8  # Number of GPIOs exposed by the MCP230xx chip, should be 8 or 16 depending on chip.

    # LCD 20x4
    num_columns = 20
    num_lines = 4
    
    def __init__(self, init=True):
        # Create MCP230xx GPIO adapter.
        mcp = MCP230XX_GPIO(self.bus, self.address, self.gpio_count)

        # Create LCD, passing in MCP GPIO adapter.
        self.lcd = Adafruit_CharLCD(pin_rs=1, pin_e=2, pin_bl=7, pins_db=[3,4,5,6], GPIO=mcp)
        if init:
            self.initialisation()
    
    def initialisation(self):
        self.lcd.clear()
        self.lcd.begin(self.num_columns, self.num_lines)
        self.lcd.backlightOn()
        self.lcd.setCursor(0, 0)
        #self.lcd.message(datetime.datetime.now().strftime(' %a %d %b - %H:%M'))
        
    def line_message(self, row, text):
        # set the position (row from 0 to 3)
        self.lcd.setCursor(0, row)
        # display the message
        self.lcd.message(text)
    
    def temperature(self, text):
        #set the position
        self.lcd.setCursor(0, 1)
        #display the message and value
        self.lcd.message("Temperature: %.2f" % text)
        self.lcd.write4bits( 0xDF, True) #display the degree symbol "°"
        self.lcd.message("C")
        
    def humidity(self, text):
        #set the position
        self.lcd.setCursor(0, 2)
        #display the message and value
        self.lcd.message("Humidity:   %.2f%%RH" % text)
        
    def pressure(self, text):
        #set the position
        self.lcd.setCursor(0, 3)
        #display the message and value
        self.lcd.message("Pressure: %.2fhPa" % text)
        
    def date(self):
        #set the position
        self.lcd.setCursor(0, 0)
        #display the message and value
        self.lcd.message(datetime.datetime.now().strftime(' %a %d %b  %H:%M'))
예제 #13
0
def dumpLCD():
    lcd = Adafruit_CharLCD()
    lcd.begin(20,4)
    lcd.clear()
    lcd.setCursor(0,0)
    lcd.message("Yay!  Treats!")
    lcd.setCursor(0,1)
    lcd.message(" ")
    lcd.setCursor(0,3)
    lcd.message("Thank you!")
예제 #14
0
def homescreen():
    lcd = Adafruit_CharLCD()
    lcd.begin(20,4)
    lcd.clear()
    lcd.setCursor(0,0)
    lcd.message("Judd Treat Machine!")
    lcd.setCursor(0,1)
    lcd.message("Awaiting Emails!")
    lcd.setCursor(0,3)
    lcd.message("Hurry up!")
예제 #15
0
class LCD:
    def __init__(self):
        self.lcd = Adafruit_CharLCD(25, 24, 23, 17, 21, 22, 16, 2)

    def data_print(self, msg, a, b):
        #self.lcd.clear()
        self.lcd.set_cursor(a, b)
        self.lcd.message(msg)

    def lcd_clear(self):
        self.lcd.clear()
예제 #16
0
class PapaDisplayCtrl:
	"""Class to display text from PaPasPy
	"""
	def __init__(self):
		self.lcd = Adafruit_CharLCD()
		self.lcd.begin(16,1)
		self.lcd.clear()

	def display(self, msg):
		self.lcd.clear()
		self.lcd.message(msg)
예제 #17
0
def print_on_display(message):
    lcd = Adafruit_CharLCD(rs=26,
                           en=19,
                           d4=13,
                           d5=6,
                           d6=5,
                           d7=11,
                           cols=16,
                           lines=2)

    lcd.clear()
    lcd.message(message)
예제 #18
0
def main():
    
    # now just write the code you would use in a real Raspberry Pi
    
    from Adafruit_CharLCD import Adafruit_CharLCD
    from gpiozero import Buzzer, LED, PWMLED, Button, DistanceSensor, LightSensor, MotionSensor
    from lirc import init, nextcode
    from py_irsend.irsend import send_once
    from time import sleep
    
    def show_sensor_values():
        lcd.clear()
        lcd.message(
            "Distance: %.2fm\nLight: %d%%" % (distance_sensor.distance, light_sensor.value * 100)
        )
        
    def send_infrared():
        send_once("TV", ["KEY_4", "KEY_2", "KEY_OK"])
    
    lcd = Adafruit_CharLCD(2, 3, 4, 5, 6, 7, 16, 2)
    buzzer = Buzzer(16)
    led1 = LED(21)
    led2 = LED(22)
    led3 = LED(23)
    led4 = LED(24)
    led5 = PWMLED(25)
    led5.pulse()
    button1 = Button(11)
    button2 = Button(12)
    button3 = Button(13)
    button4 = Button(14)
    button1.when_pressed = led1.toggle
    button2.when_pressed = buzzer.on
    button2.when_released = buzzer.off
    button3.when_pressed = show_sensor_values
    button4.when_pressed = send_infrared
    distance_sensor = DistanceSensor(trigger=17, echo=18)
    light_sensor = LightSensor(8)
    motion_sensor = MotionSensor(27)
    motion_sensor.when_motion = led2.on
    motion_sensor.when_no_motion = led2.off
    
    init("default")
    
    while True:
        code = nextcode()
        if code != []:
            key = code[0]
            lcd.clear()
            lcd.message(key + "\nwas pressed!")
            
        sleep(0.2)
예제 #19
0
def main(USERNAME, PASSWORD, SENSOR_ID):

    lcd = Adafruit_CharLCD()
    lcd.clear()

    sessionToken, objectID = LoginUser(USERNAME, PASSWORD)

    pubnub = Pubnub(publish_key="pub-c-e6b9a1fd-eed2-441a-8622-a3ef7cc5853a",
                    subscribe_key="sub-c-7e14a542-b148-11e4-9beb-02ee2ddab7fe")

    channel = SENSOR_ID

    def _callback(message, channel):
        print("Message received from channel: ", message)
        data = {'status': None, 'targetTemperature': None}
        if message['airconStatus']:
            if message['airconStatus'] == 'on':
                print "Lets turn on air con now"
                lcd.clear()
                lcd.message("Aircon On!")
                logging.warning("Lets turn on air con now")
            else:
                print "lets turn off aircon now"
                lcd.clear()
                lcd.message("Aircon Off!\n  Have a good day!")
                logging.warning("Lets turn off air con now")
            data['status'] = message['airconStatus']
        if message['targetTemperature']:
            print "Lets turn aircon to : ", message['targetTemperature']

            lcd.clear()
            lcd.message("Setting temperature\n" +
                        "Temp={0:0.1f}*C".format(message['targetTemperature']))

            logging.warning("Lets turn aircon to : " +
                            str(message['targetTemperature']))
            data['targetTemperature'] = message['targetTemperature']

        if message[
                'switchOffLCD']:  #note that this might happen a few times because current logic is if last activity was more than 3 mins ago, we swtich off
            print "Lets switch off LCD"
            lcd.clear()
            logging.warning("switching off LCD")

        needToReLogin = SendDataToParse(data, objectID, sessionToken,
                                        SENSOR_ID)

    def _error(message):
        print("Error: ", message)
        logging.warning("Error: ", message)

    pubnub.subscribe(channel, callback=_callback, error=_error)
    def lcd_write(self, topic, payload):
        """
        This method writes to the LCD
        """
        print(payload['value'])
        print(type(payload['value']))

        lcd = Adafruit_CharLCD(rs=26, en=19,
                       d4=13, d5=6, d6=5, d7=11,
                       cols=16, lines=2)
        lcd.clear()

        text = str(payload['value'])
        lcd.message(text)
예제 #21
0
def init():
    global lcd
    global sub
    pins = rospy.get_param('/pibot/pins/LCD1602')
    lcd = Adafruit_CharLCD(pin_rs=pins['RS'],
                           pin_e=pins['EN'],
                           pins_db=pins['DATA'],
                           GPIO=None)
    lcd.begin(16, 2)
    lcd.clear()
    lcd.write('  PiBot Loaded  \n  Hello World!  ')
    lcd.setCursor(0, 0)

    rospy.init_node('lcd1602')
    sub = rospy.Subscriber('/pibot/lcd1602', String, handler)
예제 #22
0
파일: LCDModule.py 프로젝트: khdb/kinderbox
class LCD:

    __line1 = ""
    __line2 = ""
    def __init__(self):
        self.lcd = Adafruit_CharLCD()
        self.lcd.clear()
        self.logger = LoggerModule.Logger("LCD Module")

    def hello(self):
        self.lcd.message("  Welcome to \n Kinderbox ")

    def turn_off(self):
        self.lcd.noDisplay()

    def display_pause(self):
        self.message("", "Pause")

    def display_ready(self):
        self.message("", "Ready")

    def display_volume(self, message):
        self.message("", message)


    def message(self, line1, line2):
        if self.__line1 == line1 and self.__line2 == line2:
            return
        try:
            n_line1 = normalization.remove_unicode(line1)
        except:
            n_line1 = "unkown"
        try:
            n_line2 = normalization.remove_unicode(line2)
        except:
            n_line2 = "unkown"

        self.lcd.clear()
        sleep(0.5)
        message = "%s\n%s" %(n_line1,n_line2)
        self.lcd.message(message)
        self.__line1 = line1
        self.__line2 = line2

    def scroll_to_left(self):
        #Check size message. If over 16 character --> move
        if len(self.__line1) > 16 or len(self.__line2) > 16:
            self.lcd.DisplayLeft()
예제 #23
0
class MCP23xxxDriver(object):
    def __init__(self, **kwargs):
        # Create MCP230xx GPIO adapter.
        mcp = MCP230XX_GPIO(CONF.lcd.bus, CONF.lcd.address, CONF.lcd.gpio_count)

        # Create LCD, passing in MCP GPIO adapter.
        self._lcd = Adafruit_CharLCD(pin_rs=1, pin_e=2, pins_db=[3,4,5,6], GPIO=mcp)

        self._lcd.clear()


    def write(self, msg):
        self.clear()
        self._lcd.message(msg)

    def clear(self):
        self._lcd.clear()
예제 #24
0
class ScreenWriter(object):
    """docstring for ScreenWriter."""
    def __init__(self, rs, en, d4, d5, d6, d7):
        """Config."""
        self.columns = 16
        self.lines = 1
        self.lcd = Adafruit_CharLCD(rs, en, d4, d5, d6, d7, self.columns,
                                    self.lines)

    def _direction_to_char(self, dir):
        return DIR_TO_CHAR[dir]

    def write_to_lcd(self, value, dir):
        """Write out to lcd."""
        self.lcd.clear()
        self.lcd.message(str(value) + ' mg/dl\n')
        self.lcd.message(self._direction_to_char(dir))
예제 #25
0
class ScreenComponent(JNTComponent):
    """ A Screen component for gpio """

    def __init__(self, bus=None, addr=None, **kwargs):
        """
        """
        oid = kwargs.pop('oid', 'rpilcdchar.screen')
        name = kwargs.pop('name', "Screen")
        product_name = kwargs.pop('product_name', "Screen")
        product_type = kwargs.pop('product_type', "Screen")
        JNTComponent.__init__(self, oid=oid, bus=bus, addr=addr, name=name,
                product_name=product_name, product_type=product_type, **kwargs)
        logger.debug("[%s] - __init__ node uuid:%s", self.__class__.__name__, self.uuid)
        uuid="message"
        self.values[uuid] = self.value_factory['action_string'](options=self.options, uuid=uuid,
            node_uuid=self.uuid,
            help='A message to print on the screen',
            label='Msg',
            default='Janitoo started',
            set_data_cb=self.set_message,
            is_writeonly = True,
            cmd_class=COMMAND_MOTOR,
            genre=0x01,
        )
        poll_value = self.values[uuid].create_poll_value(default=300)
        self.values[poll_value.uuid] = poll_value
        self.pin_lcd_rs        = 27  # Note this might need to be changed to 21 for older revision Pi's.
        self.pin_lcd_en        = 22
        self.pin_lcd_d4        = 25
        self.pin_lcd_d5        = 24
        self.pin_lcd_d6        = 23
        self.pin_lcd_d7        = 18
        self.pin_lcd_backlight = 4
        self.lcd_columns = 20
        self.lcd_rows    = 4
        self.lcd = Adafruit_CharLCD(self.pin_lcd_rs, self.pin_lcd_en, self.pin_lcd_d4, self.pin_lcd_d5, self.pin_lcd_d6, self.pin_lcd_d7,
                            self.lcd_columns, self.lcd_rows, self.pin_lcd_backlight)

    def set_message(self, node_uuid, index, data):
        """Set the message on the screen
        """
        try:
            self.lcd.clear()
            self.lcd.message(data)
        except Exception:
            logger.exception('Exception when displaying message')
예제 #26
0
class TwoLineLCD(object):
    def __init__(self, lcd_rs, lcd_en, lcd_d4, lcd_d5, lcd_d6, lcd_d7,
                 lcd_columns, lcd_rows, lcd_backlight):
        self.lcd = LCD(lcd_rs,
                       lcd_en,
                       lcd_d4,
                       lcd_d5,
                       lcd_d6,
                       lcd_d7,
                       lcd_columns,
                       lcd_rows,
                       lcd_backlight,
                       gpio=aGPIO.get_platform_gpio())
        self.lcd.clear()
        self._columns = lcd_columns
        self._in_progress = None

    def clear(self):
        self.lcd.clear()

    def cancel(self):
        if self._in_progress and self._in_progress.active():
            self._in_progress.cancel()
        self.clear()

    def message(self, line_1, line_2):
        self.cancel()
        if len(line_1) > self._columns:
            line_1 += " "  # Padding when scrolling
        if len(line_2) > self._columns:
            line_2 += " "  # Padding when scrolling
        self._in_progress = async .DelayedCall(0, self._message, line_1,
                                               line_2)

    def _message(self, line_1, line_2):
        self.lcd.home()
        self.lcd.message(line_1[:self._columns] + "\n" +
                         line_2[:self._columns])
        if len(line_1) > self._columns:
            line_1 = rotate(line_1)
        if len(line_2) > self._columns:
            line_2 = rotate(line_2)

        self._in_progress = async .DelayedCall(0.5, self._message, line_1,
                                               line_2)
예제 #27
0
class MCP23xxxDriver(object):
    def __init__(self, **kwargs):
        # Create MCP230xx GPIO adapter.
        mcp = MCP230XX_GPIO(CONF.lcd.bus, CONF.lcd.address,
                            CONF.lcd.gpio_count)

        # Create LCD, passing in MCP GPIO adapter.
        self._lcd = Adafruit_CharLCD(pin_rs=1,
                                     pin_e=2,
                                     pins_db=[3, 4, 5, 6],
                                     GPIO=mcp)

        self._lcd.clear()

    def write(self, msg):
        self.clear()
        self._lcd.message(msg)

    def clear(self):
        self._lcd.clear()
예제 #28
0
class GpioDisplay:
    def __init__(self, *_args):
        if GPIO.RPI_REVISION == 2:
            self.lcd = Adafruit_CharLCD(pins_db=[23, 17, 27, 22])
        else:
            self.lcd = Adafruit_CharLCD()
        self.lcd.begin(16, 2)

    def clear(self):
        self.lcd.clear()

    def move_to(self, row, col):
        self.lcd.setCursor(row, col)

    def write(self, string):
        self.lcd.message(string)

    def backlight(self, r, g, b):
        # not implemented
        pass
예제 #29
0
class GpioDisplay:

    def __init__(self, *_args):
        if GPIO.RPI_REVISION == 2:
            self.lcd = Adafruit_CharLCD(pins_db=[23, 17, 27, 22])
        else:
            self.lcd = Adafruit_CharLCD()
        self.lcd.begin(16,2)

    def clear(self):
        self.lcd.clear()

    def move_to(self, row, col):
        self.lcd.setCursor(row, col)

    def write(self, string):
        self.lcd.message(string)

    def backlight(self, r, g, b):
        # not implemented
        pass
예제 #30
0
def print_to_lcd():
    """ Print values to a 2x16 LCD display if it is provided with connections described """
    lcd = Adafruit_CharLCD(rs=26,
                           en=19,
                           d4=13,
                           d5=6,
                           d6=5,
                           d7=21,
                           cols=16,
                           lines=2)
    lcd.clear()
    lcd.set_cursor(0, 0)
    lcd.message("DHT22 Program")
    lcd.set_cursor(0, 1)
    lcd.message("Waiting...")
    sleep(2)
    try:
        while True:
            hum, temp = get_values()
            lcd.clear()
            lcd.set_cursor(0, 0)
            lcd.message("Temp: {0:.2f} C".format(temp))
            lcd.set_cursor(0, 1)
            lcd.message("Humi: {0:.2f} %".format(hum))
            sleep(5)
    except KeyboardInterrupt:
        print('Exiting...')
        lcd.clear()
        lcd.set_cursor(0, 0)
        lcd.message("OFFLINE")
예제 #31
0
def LCD(text):
    # instantiate lcd and specify pins
    lcd = Adafruit_CharLCD(rs=26,
                           en=19,
                           d4=13,
                           d5=6,
                           d6=5,
                           d7=11,
                           cols=16,
                           lines=2)
    lcd.clear()
    # display text on LCD display \n = new line
    lcd.message(text)
    sleep(3)
    # scroll text off display
    for x in range(0, 16):
        lcd.move_right()
        sleep(.1)
    sleep(3)
    # scroll text on display
    for x in range(0, 16):
        lcd.move_left()
        sleep(.1)
예제 #32
0
class PrinterWorkerThread(threading.Thread):
    def __init__(self, print_q):
        super(PrinterWorkerThread, self).__init__()
        self.print_q = print_q
        self.stoprequest = threading.Event()
        self.lcd = Adafruit_CharLCD()
        self.lcd.begin(16,1)
        self.lcd.clear()

    def run(self):
        while not self.stoprequest.isSet():
            try:
                to_print = self.print_q.get(True, 0.05)
                self.lcd.clear()
                self.lcd.message('%s' %(to_print))
                #self.lcd.message("Test")
                print("%s") % (to_print)
            except Queue.Empty:
                continue

    def join(self,timeout=None):
        self.stoprequest.set()
        super(PrinterWorkerThread, self).join(timeout)
예제 #33
0
def displayresult(prediction):
    lcd = Adafruit_CharLCD(rs=26,
                           en=19,
                           d4=13,
                           d5=6,
                           d6=5,
                           d7=11,
                           cols=16,
                           lines=2)
    lcd.clear()
    # display text on LCD display \n = new line
    lcd.message(prediction)
    sleep(.3)
    # scroll text off display
    '''for x in range(0, 16):
      lcd.move_right()
      sleep(.1)
    sleep(3)
    # scroll text on display 
    for x in range(0, 16):
      lcd.move_left()
      sleep(.1)'''

    sleep(.3)
예제 #34
0
class DisplayManager(object):
    def __init__(self):
        self.s=Adafruit_CharLCD()
        self.s.clear()
        self.__displayText("Welcome")
        time.sleep(1)
        self.s.clear()

    def __displayText(self, strText):
        self.s.message(strText)

    def displayText(self, strText):
        print("Displaying " + strText)
        if 'none' not in strText.lower():
            self.__displayText(strText)
        elif 'none' in strText.lower():
            self.s.clear()
        else:
            self.__displayText("Unknown!")
            self.s.clear()
예제 #35
0
    def run(self):
        # LCD object
        lcd = AdaLcd(**params['_lcd_pins'])
        lcd.clear()

        URL = params['_url']
        client = requests.session()

        # Retrieve the CSRF token first
        get = client.get(URL + '/login')  # sets cookie

        login_data = {
            'id':
            params['_permit'],
            'password':
            params['_password'],
            '_token':
            re.compile('\"_token\".*value=\"(?P<Value>\w*)\"\>').search(
                get.text).group('Value')  # get the token from text
        }
        client.post(URL + '/login', data=login_data, cookies=client.cookies)

        payment_count = 0
        lcd_str = 'Paid:%d. Rem:%d\n%s.'
        lcd.message(
            lcd_str %
            (payment_count, params['_mas_passengers'] - payment_count, '....'))

        reader = Serial(port=params['_port'])
        """ TheLoop """
        while True:
            read_val = reader.read(params['_size'])

            lcd.clear()
            lcd.message(lcd_str % (payment_count, params['_mas_passengers'] -
                                   payment_count, '....'))

            uid_val = json.loads(read_val[:-2].decode())['UID']
            ret = json.loads(
                client.get(URL + '/transfer/%s/%s/%s' %
                           (uid_val, params['_permit'], params['_cost']),
                           cookies=client.cookies).text)

            if ret['_status'] == 200:
                payment_count += 1

            lcd.clear()
            lcd.message(lcd_str % (payment_count, params['_mas_passengers'] -
                                   payment_count, ret['_description']))
예제 #36
0
class LCD(object):
    """ A 16x2 LCD Display """
    def __init__(self):
        """ LCD Constructor """

        # Setup LCD
        self.lcd = Adafruit_CharLCD(
            rs=12,
            en=5,
            d4=6,  # Pins are being hardcoded
            d5=13,
            d6=19,
            d7=26,  # 
            cols=16,
            lines=2)  # (16x2 LCD)
        # Clear the LCD
        self.lcd.clear()

    def setText(self, message, displayTime=None):
        """
		Set the LCD display text

		Parameters
	    	----------
	    	message : string
		        The message to be displayed on the LCD

	    	displayTime : int,optional
		            The amount of time the message will be displayed
			    If omitted, the message will disappear once the LCD is cleared

		Returns
	    	-------
	    	None
		"""

        # Clear the LCD
        self.lcd.clear()

        # Set the LCD text
        self.lcd.message(message)

        #If displayTime is provided, sleep for 'displayTime' seconds, then clear LCD
        if displayTime != None:
            time.sleep(displayTime)
            self.lcd.clear()
예제 #37
0
	def run(self):
		# LCD object
		lcd = AdaLcd(**params['_lcd_pins'])
		lcd.clear()

		URL = params['_url']
		client = requests.session()

		# Retrieve the CSRF token first
		get = client.get(URL + '/login')  # sets cookie

		login_data = {
			'id'       : params['_permit'],
			'password' : params['_password'],
			'_token'   : re.compile('\"_token\".*value=\"(?P<Value>\w*)\"\>')
						   .search(get.text).group('Value') # get the token from text
		}
		client.post(URL+'/login', data=login_data, cookies=client.cookies)

		payment_count = 0
		lcd_str       = 'Paid:%d. Rem:%d\n%s.'
		lcd.message(lcd_str%(payment_count, params['_mas_passengers'] - payment_count, '....'))

		reader = Serial(port=params['_port'])
		""" TheLoop """
		while True:
			read_val = reader.read(params['_size'])

			lcd.clear()
			lcd.message(lcd_str%(payment_count, params['_mas_passengers'] - payment_count, '....'))

			uid_val  = json.loads(read_val[:-2].decode())['UID']
			ret      = json.loads(client.get(URL+'/transfer/%s/%s/%s'%(uid_val, params['_permit'], params['_cost']), cookies=client.cookies).text)

			if ret['_status'] == 200:
				payment_count += 1

			lcd.clear()
			lcd.message(lcd_str%(payment_count, params['_mas_passengers'] - payment_count, ret['_description']))
예제 #38
0
  # Get data from SHT11
  sht1x = SHT1x(dataPin, clkPin)
  temperature = sht1x.read_temperature_C()
  humidity = sht1x.read_humidity()
  try:
    dewPoint = sht1x.calculate_dew_point(temperature, humidity)
  except ValueError, msg:
    print("Error calculating dew point: %s" % msg)

  # Format time
  curtime = strftime("%H:%M", localtime())
  curdate = strftime("%Y-%m-%d", localtime())

  # Setup LCD
  lcd = Adafruit_CharLCD()
  lcd.clear()
  # \xDF = degree symbol for LCD display

  # Show the data
  lcd.message("T: {:2.2f}\xDFC H: {:2.2f}%\nD: {:2.2f}\xDFC T: {}".format(temperature, humidity, dewPoint, curtime))
  # print("T: {:2.2f}\xC2\xB0C H: {:2.2f}%\nD: {:2.2f}\xB0C T: {}".format(temperature, humidity, dewPoint, curtime))
  print("Date: {} Time: {} Temperature: {:2.2f}\xC2\xB0C Humiditiy: {:2.2f}% Dew Point: {:2.2f}\xC2\xB0C".format(curdate, curtime, temperature, humidity, dewPoint))
  
  # Flush output, needed to get output if ran with nohup
  sys.stdout.flush()

  if count < totalcount:
    count += 1 
  else:
    count = 0
예제 #39
0
#!/usr/local/bin/python
# -*- coding: utf-8 -*-

import sys
sys.path.append('/home/pi/Adafruit-Raspberry-Pi-Python-Code-legacy/Adafruit_CharLCD') 
from Adafruit_CharLCD import Adafruit_CharLCD
 
text1 = u'コンニチワ!'
text2 = u'RasberryPi デス'
 
text1 = text1.encode('shift-jis')
text2 = text2.encode('shift-jis')
 
try:
  lcd = Adafruit_CharLCD()
  lcd.clear()
 
  lcd.message(text1)
  lcd.message('\n')
  lcd.message(text2)
finally:
  print 'cleanup'
  lcd.GPIO.cleanup()

예제 #40
0
class HashTagDisplay():
    def __init__(self, cols, rows, delay, debug=False):
        # number of columns on the character LCD (min: 16, max: 20)
        self.cols = cols
        # number of rows on the character LCD (min: 1, max: 4)
        self.rows = rows
        # duration in seconds to allow human to read LCD lines
        self.delay = delay
        # print messages to shell for debugging 
        self.debug = debug
        if debug == True:
            print " cols = {0}".format(cols)
            print " rows = {0}".format(rows)
            print "delay = {0}".format(delay)
        self.lcd = Adafruit_CharLCD()
        self.lcd.begin(cols, rows)

    def search(self, hashtag):
        """ search for tweets with specified hashtag """
        twitter_search = Twitter(domain="search.twitter.com")
        return twitter_search.search(q=hashtag)
    
    def display(self, results):
        """ Display each tweet in the twitter search results """
        for tweet in results.get('results'):
            msg = "@" + tweet.get('from_user') + ": " + tweet.get('text') 
            if self.debug == True:
                print "msg: " + msg
            # break tweet into lines the width of LCD
            lines = textwrap.wrap(msg, self.cols)
            self.printLines(lines)

    def printLines(self, lines):
        """ display each line of the tweet """
        i = 0
        while i < lines.__len__():
            self.lcd.clear()
                
            # print line to each LCD row 
            for row in range(self.rows):

                # display line on current LCD row
                self.lcd.setCursor(0,row)
                self.lcd.message(lines[i])
                i=i+1
                # 200ms delay is now only for visual effect
                # initially added the delay to avoid issue 
                # where garbage characters were displayed:
                # https://github.com/adafruit/Adafruit-Raspberry-Pi-Python-Code/pull/13
                sleep(0.2)

                # no more lines remaining for this tweet
                if i >= lines.__len__():
                    # sleep according to the number of rows displayed
                    row_delay = self.delay / float(self.rows)
                    delay = row_delay * (row+1)
                    if(delay < 1):
                        delay = 1
                    sleep(delay)
                    break

                # pause to allow human to read displayed rows
                if(row+1 >= self.rows):
                     sleep(self.delay)
class Humsie_DisplayThread (threading.Thread):

    intCurIndex = -1;
    arrPages = { };
    bRunning = False;
    LCD = False;
    intTimePerPage = 3;
    bUpdatingDisplay = False;
    intColor = -1;
    arrColors = [];

    def __init__(self, threadID, name, counter, GPIO=False):
        threading.Thread.__init__(self)
        self.threadID = threadID
        self.name = name
        self.counter = counter
        if GPIO == False:
            self.LCD = Adafruit_CharLCDPlate();
            self.arrColors = [self.LCD.RED,self.LCD.GREEN,self.LCD.BLUE,self.LCD.YELLOW,self.LCD.TEAL,self.LCD.VIOLET,self.LCD.WHITE,self.LCD.ON ]
            self.intColor = 0;
        else:
            self.LCD = Adafruit_CharLCD(25, 24, [23, 17, 27, 22], GPIO);

    def start(self):
        self.bRunning = True;
        threading.Thread.start(self)

    def run(self):
        while self.bRunning == True:
            self.intCurIndex += 1;
            if self.arrPages.has_key(self.intCurIndex) == False:
                self.intCurIndex = 0;
            
            self.displayPage(self.intCurIndex);
            sleep(self.intTimePerPage);
            if self.intColor >= 0:
               self.intColor += 1;
               if self.intColor >= len(self.arrColors):
                 self.intColor = 0;
               self.LCD.backlight(self.arrColors[self.intColor]);

        return

    def gotoPage(self, index):
        self.intCurIndex = index;
        if self.arrPages.has_key(self.intCurIndex) == False:
            self.intCurIndex = 0;
        
        self.displayPage(index)

    def displayPage(self, index):
	if self.bUpdatingDisplay == False:
	    if self.arrPages.has_key(index) != False:
                self.bUpdatingDisplay = True
                self.LCD.clear()
                self.LCD.message(self.arrPages[index])
                self.bUpdatingDisplay = False
       	return;       

    def setTimePerPage(self, seconds=3):
        self.intTimePerPage = seconds
        return self.intTimePerPage

    def stop(self):
        self.LCD.clear();
        self.bRunning = False
        return

    def stopped(self):
        return self.bRunning
        
    def setPage(self, index, line):
        if self.arrPages[index] != line:
            self.arrPages[index] = line;
            if self.intCurIndex == index:
                self.displayPage(self.intCurIndex);
        return;

    def registerPage(self, content = ''):
        length = len(self.arrPages);
        self.arrPages[length] = content;
        return length;
예제 #42
0
class launcher:
    def __init__(self):
        # Need a state set for this launcher.
        self.menu = ["Remote Control"]
        self.menu += ["Three Point Turn"]
        self.menu += ["Straight Line Speed"]
        self.menu += ["Line Following"]
        self.menu += ["Proximity"]
        self.menu += ["Quit Challenge"]
        self.menu += ["Power Off Pi"]

        self.menu_quit_challenge = 3

        # default menu item is remote control
        self.menu_state = 0
        self.menu_button_pressed = False
        self.drive = None
        self.wiimote = None
        # Current Challenge
        self.challenge = None
        self.challenge_name = ""

        GPIO.setwarnings(False)
        self.GPIO = GPIO

        # LCD Display
        self.lcd = Adafruit_CharLCD( pin_rs=25, pin_e=24, pins_db=[23, 17, 27, 22], GPIO=self.GPIO )
        self.lcd.begin(16, 1)
        self.lcd.clear()
        self.lcd.message('Initiating...')
        self.lcd_loop_skip = 5
        # Shutting down status
        self.shutting_down = False

    def menu_item_selected(self):
        """Select the current menu item"""
        # If ANYTHING selected, we gracefully
        # kill any challenge threads open
        self.stop_threads()
        if self.menu[self.menu_state]=="Remote Control":
            # Start the remote control
            logging.info("Entering into Remote Control Mode")
            self.challenge = rc.rc(self.drive, self.wiimote)
            # Create and start a new thread running the remote control script
            self.challenge_thread = threading.Thread(target=self.challenge.run)
            self.challenge_thread.start()
            # Ensure we know what challenge is running
            if self.challenge:
                self.challenge_name = self.menu[self.menu_state]
            # Move menu index to quit challenge by default
            self.menu_state = self.menu_quit_challenge
        elif self.menu[self.menu_state]=="Three Point Turn":
            # Start the three point turn challenge
            logging.info("Starting Three Point Turn Challenge")
            self.challenge = ThreePointTurn(self.drive)
            # Create and start a new thread running the remote control script
            self.challenge_thread = threading.Thread(target=self.challenge.run)
            self.challenge_thread.start()
            # Ensure we know what challenge is running
            if self.challenge:
                self.challenge_name = self.menu[self.menu_state]
            # Move menu index to quit challenge by default
            self.menu_state = self.menu_quit_challenge
        elif self.menu[self.menu_state]=="Straight Line Speed":
            # Start the straight line speed challenge
            logging.info("Starting Straight Line Speed Challenge")
            self.challenge = StraightLineSpeed(self.drive)
            # Ensure we know what challenge is running
            if self.challenge:
                self.challenge_name = self.menu[self.menu_state]
            # Move menu index to quit challenge by default
            self.menu_state = self.menu_quit_challenge
        elif self.menu[self.menu_state]=="Line Following":
            # Start the Line Following challenge
            logging.info("Starting Line Following Challenge")
            self.challenge = LineFollowing(self.drive)
            # Ensure we know what challenge is running
            if self.challenge:
                self.challenge_name = self.menu[self.menu_state]
            # Move menu index to quit challenge by default
            self.menu_state = self.menu_quit_challenge
        elif self.menu[self.menu_state]=="Proximity":
            # Start the Proximity challenge
            logging.info("Starting Proximity Challenge")
            self.challenge = Proximity(self.drive)
            # Ensure we know what challenge is running
            if self.challenge:
                self.challenge_name = self.menu[self.menu_state]
            # Move menu index to quit challenge by default
            self.menu_state = self.menu_quit_challenge        
        elif self.menu[self.menu_state]=="Quit Challenge":
            # Reset menu item back to top of list
            self.menu_state = 0
            logging.info("No Challenge Challenge Thread")
        elif self.menu[self.menu_state]=="Power Off Pi":
            # Power off the raspberry pi safely
            # by sending shutdown command to terminal
            logging.info("Shutting Down Pi")
            os.system("sudo shutdown -h now")
            self.shutting_down = True

    def set_neutral(self, drive, wiimote):
        """Simple method to ensure motors are disabled"""
        if drive:
            drive.set_neutral()
            drive.disable_drive()
        if wiimote is not None:
            # turn on leds on wii remote
            wiimote.led = 2

    def set_drive(self, drive, wiimote):
        """Simple method to highlight that motors are enabled"""
        if wiimote is not None:
            # turn on leds on wii remote
            #turn on led to show connected
            drive.enable_drive()
            wiimote.led = 1

    def stop_threads(self):
        """Method neatly closes any open threads started by this class"""
        if self.challenge:
            self.challenge.stop()
            self.challenge = None
            self.challenge_thread = None
            logging.info("Stopping Challenge Thread")
        else:
            logging.info("No Challenge Challenge Thread")
        # Safety setting
        self.set_neutral(self.drive, self.wiimote)

    def run(self):
        """ Main Running loop controling bot mode and menu state """
        # Tell user how to connect wiimote
        self.lcd.clear()
        self.lcd.message( 'Press 1+2 \n' )
        self.lcd.message( 'On Wiimote' )

        # Initiate the drivetrain
        self.drive = drivetrain.DriveTrain(pwm_i2c=0x40)
        self.wiimote = None
        try:
            self.wiimote = Wiimote()

        except WiimoteException:
            logging.error("Could not connect to wiimote. please try again")

        if not self.wiimote:
            # Tell user how to connect wiimote
            self.lcd.clear()
            self.lcd.message( 'Wiimote \n' )
            self.lcd.message( 'Not Found' + '\n' )

        # Constantly check wiimote for button presses
        loop_count = 0
        while self.wiimote:
            buttons_state = self.wiimote.get_buttons()
            nunchuk_buttons_state = self.wiimote.get_nunchuk_buttons()
            joystick_state = self.wiimote.get_joystick_state()

#            logging.info("joystick_state: {0}".format(joystick_state))
#            logging.info("button state {0}".format(buttons_state))
            # Always show current menu item
            # logging.info("Menu: " + self.menu[self.menu_state])

            if loop_count >= self.lcd_loop_skip:
                # Reset loop count if over
                loop_count = 0

                self.lcd.clear()
                if self.shutting_down:
                    # How current menu item on LCD
                    self.lcd.message( 'Shutting Down Pi' + '\n' )
                else:
                    # How current menu item on LCD
                    self.lcd.message( self.menu[self.menu_state] + '\n' )

                    # If challenge is running, show it on line 2
                    if self.challenge:
                        self.lcd.message( '[' + self.challenge_name + ']' )

            # Increment Loop Count
            loop_count = loop_count + 1

            # Test if B button is pressed
            if joystick_state is None or (buttons_state & cwiid.BTN_B) or (nunchuk_buttons_state & cwiid.NUNCHUK_BTN_Z):
                # No nunchuk joystick detected or B or Z button
                # pressed, must go into neutral for safety
                logging.info("Neutral")
                self.set_neutral(self.drive, self.wiimote)
            else:
                # Enable motors
                self.set_drive(self.drive, self.wiimote)

            if ((buttons_state & cwiid.BTN_A)
                or (buttons_state & cwiid.BTN_UP)
                or (buttons_state & cwiid.BTN_DOWN)):
                # Looking for state change only
                if not self.menu_button_pressed and (buttons_state & cwiid.BTN_A):
                    # User wants to select a menu item
                    self.menu_item_selected()
                elif not self.menu_button_pressed and (buttons_state & cwiid.BTN_UP):
                    # Decrement menu index
                    self.menu_state = self.menu_state - 1
                    if self.menu_state < 0:
                        # Loop back to end of list
                        self.menu_state = len(self.menu)-1
                    logging.info("Menu item: {0}".format(self.menu[self.menu_state]))
                elif not self.menu_button_pressed and (buttons_state & cwiid.BTN_DOWN):
                    # Increment menu index
                    self.menu_state = self.menu_state + 1
                    if self.menu_state >= len(self.menu):
                        # Loop back to start of list
                        self.menu_state = 0
                    logging.info("Menu item: {0}".format(self.menu[self.menu_state]))

                # Only change button state AFTER we have used it
                self.menu_button_pressed = True
            else:
                # No menu buttons pressed
                self.menu_button_pressed = False

            time.sleep(0.05)
예제 #43
0
파일: SkyPi.py 프로젝트: atimokhin/SkyPi
class SkyPi:

    def __init__(self):
        self.FSM = SkyPi_FSM()
        # flags
        self.redraw_flag = True
        self.wifi_mode_adhoc_flag = False
        # setup LCD screen
        self.lcd = Adafruit_CharLCD()
        self.lcd.begin(16, 2)
        self.lcd.clear()
        self.lcd.message("Start SkyPi_LCDd\n")
        # setup datetime
        self.time_state = True
        self.time_str_fmt = ' %m/%d %H:%M'
        self.datetime_str=datetime.now().strftime(self.time_str_fmt)
        # gps
        self.gps = SkyPi_GPS(SP_CFG.DT_GPS_CHECK)
        # net
        self.net = SkyPi_NET()
        # setup GPIOs
        GPIO.setmode(GPIO.BCM)
        GPIO.setup(SP_CFG.PIN_BUTTON_HC_SETUP,   GPIO.IN, pull_up_down=GPIO.PUD_UP)
        GPIO.setup(SP_CFG.PIN_SWITCH_ADHOC_MODE, GPIO.IN, pull_up_down=GPIO.PUD_UP)


    def Show_GPS_IP(self):
        # gps status
        self._show_gps_status()
        # time
        self._show_time()
        # ip
        self._show_ip()
        # reset redraw_flag
        self.redraw_flag = False
        # monitor button
        self.check_buttons()

    def Change_WiFi_Mode(self,mode):
        if mode == 'A':
            self.net.switch_to_AdHoc()
        elif mode == 'M':
            self.net.switch_to_Managed()
            
    def Setup_HC(self):
        self.lcd.clear()
        self.lcd.setCursor(0,0)
        self.lcd.message('Button pressed\n')
        sleep(1)
        self.lcd.clear()
        self.lcd.setCursor(0,0)
        lat,lon,status = self.gps.get_location()
        self.lcd.message('S:%2d lat:%g' % (status,lat))
        self.lcd.setCursor(0,1)
        self.lcd.message('    lon:%g' % lon)
        self.redraw_flag = True
        sleep(2)
        self.lcd.clear()
        
    def check_buttons(self):
        if GPIO.input(SP_CFG.PIN_BUTTON_HC_SETUP) == False:
            self.Setup_HC()
        if GPIO.input(SP_CFG.PIN_SWITCH_ADHOC_MODE) == False:
            if not self.wifi_mode_adhoc_flag:
                self.Change_WiFi_Mode('A')
                self.wifi_mode_adhoc_flag = True
        else:
            if self.wifi_mode_adhoc_flag:
                self.Change_WiFi_Mode('M')
                self.wifi_mode_adhoc_flag = False
        
    def _show_gps_status(self):
        """
        show GPS status
        """ 
        if ( self.gps.check_gps() or self.redraw_flag ):
            # show GPS info on LCD
            self.lcd.setCursor(0,0)
            self.lcd.message(self.gps.gps_status_str())
                
    def _show_ip(self):
        local_redraw_flag = False
        # if address has changed
        if ( self.net.check_net() or self.redraw_flag ):                     
             # clear previous IP
             self.lcd.setCursor(0,1)
             self.lcd.message(16*' ')
             # new IP
             self.lcd.setCursor(0,1)
             self.lcd.message(self.net.net_status_str())

    def _show_time(self):
        current_datetime_str=datetime.now().strftime(self.time_str_fmt)
        if ( current_datetime_str != self.datetime_str or
             self.redraw_flag ):
            self.datetime_str = current_datetime_str
            self.lcd.setCursor(3,0)
            self.lcd.message(self.datetime_str)
        # blinking ":"
        self.time_state = not self.time_state
        self.lcd.setCursor(15,0)
        if self.time_state:
            self.lcd.message(':')
        else:
            self.lcd.message(' ')
예제 #44
0
class HashTagDisplay():
    def __init__(self, cols, rows, delay, debug=False):
        # number of columns on the character LCD (min: 16, max: 20)
        self.cols = cols
        # number of rows on the character LCD (min: 1, max: 4)
        self.rows = rows
        # duration in seconds to allow human to read LCD lines
        self.delay = delay
        # print messages to shell for debugging
        self.debug = debug
        if debug == True:
            print " cols = {0}".format(cols)
            print " rows = {0}".format(rows)
            print "delay = {0}".format(delay)
        self.lcd = Adafruit_CharLCD()
        self.lcd.begin(cols, rows)

    def search(self, hashtag):
        """ search for tweets with specified hashtag """
        twitter_search = Twitter(domain="search.twitter.com")
        return twitter_search.search(q=hashtag)

    def display(self, results):
        """ Display each tweet in the twitter search results """
        for tweet in results.get('results'):
            msg = "@" + tweet.get('from_user') + ": " + tweet.get('text')
            if self.debug == True:
                print "msg: " + msg
            # break tweet into lines the width of LCD
            lines = textwrap.wrap(msg, self.cols)
            self.printLines(lines)

    def printLines(self, lines):
        """ display each line of the tweet """
        i = 0
        while i < lines.__len__():
            self.lcd.clear()

            # print line to each LCD row
            for row in range(self.rows):

                # display line on current LCD row
                self.lcd.setCursor(0, row)
                self.lcd.message(lines[i])
                i = i + 1
                # 200ms delay is now only for visual effect
                # initially added the delay to avoid issue
                # where garbage characters were displayed:
                # https://github.com/adafruit/Adafruit-Raspberry-Pi-Python-Code/pull/13
                sleep(0.2)

                # no more lines remaining for this tweet
                if i >= lines.__len__():
                    # sleep according to the number of rows displayed
                    row_delay = self.delay / float(self.rows)
                    delay = row_delay * (row + 1)
                    if (delay < 1):
                        delay = 1
                    sleep(delay)
                    break

                # pause to allow human to read displayed rows
                if (row + 1 >= self.rows):
                    sleep(self.delay)
예제 #45
0
파일: LCDModule.py 프로젝트: khdb/kinderbox
class LCD:

    __line1 = ""
    __line2 = ""
    __isLock = False
    __wait = 3 #seconds
    def __init__(self):
        self.lcd = Adafruit_CharLCD()
        self.lcd.clear()
        self.logger = LoggerModule.Logger("LCD Module")

    def hello(self):
        self.lcd.message("  Welcome to \n Kinderbox ")

    def turn_off(self):
        self.lcd.noDisplay()

    def display_ip(self):
        cmd = "ip addr show eth0 | grep inet | awk '{print $2}' | cut -d/ -f1"
        p = Popen(cmd, shell=True, stdout=PIPE)
        ipaddr = p.communicate()[0]
        self.message("Ready to scan", "IP: %s" %ipaddr, True)

    def display_pause(self):
        self.message("", "Pause", True)

    def display_ready(self):
        #self.message("", "Ready", True)
        self.display_ip()

    def display_volume(self, message):
        self.message("", message, True)
        self.__isLock = True
        self.__locked_time = time()


    def message(self, line1, line2, force = False):
        if force:
            self.__isLock = False

        if self.__isLock:
            current_time = time()
            if current_time - self.__locked_time >= self.__wait:
                self.__isLock == False
            else:
                return

        if self.__line1 == line1 and self.__line2 == line2:
            return

        try:
            n_line1 = normalization.remove_unicode(line1)
        except Exception, e1:
            print "Line1: %s" %e1
            n_line1 = "unkown"

        try:
            n_line2 = normalization.remove_unicode(line2)
        except Exception, e2:
            print "Line2: %s" %e2
            n_line2 = "unkown"
예제 #46
0
def programa():

    # importação de bibliotecas
    import random
    import numpy as np
    from time import sleep
    from mplayer import Player
    from gpiozero import LED
    from gpiozero import Button
    from Adafruit_CharLCD import Adafruit_CharLCD

    # definição de funções
    #player.loadfile("musica.mp3")
    #player.loadlist("lista.txt")

    def TocarEPausar():
        player.pause()
        if (player.paused):
            led.blink()
        else:
            led.on()

    def ProximaFaixa():
        player.pt_step(1)
        #player.speed = 2
        return

    def FaixaAnterior():
        if (player.time_pos > 2.00):
            player.time_pos = 0.00
            return
        player.pt_step(-1)
        return

    def Acelera():
        player.speed = player.speed * 2

    def VoltaAoNormal():
        velocidade = player.speed
        if velocidade != None and velocidade > 1:
            player.speed = 1
            return
        ProximaFaixa()

    def embaralhaLista():

        f = open("playlist.txt", "r")
        lista = f.readlines()
        random.shuffle(lista)
        f.close()

        f = open("playlist_nova.txt", "w")
        f.writelines(lista)
        f.close()

        player.loadlist("playlist_nova.txt")
        #lista = random.shuffle("playlist.txt")
        #player.loadlist(lista)
        ###
        #arr = np.array(lista)
        #test =np.loadtxt(lista)
        #test =np.loadtxt("playlist.txt")
        #test= np.random.shuffle(test)
        #np.savetxt("listanova.txt",test)

        #print(test)

    # criação de componentes

    player = Player()
    player.loadlist("playlist.txt")

    led = LED(21)

    lcd = Adafruit_CharLCD(2, 3, 4, 5, 6, 7, 16, 2)

    button1 = Button(11)
    button2 = Button(12)
    button3 = Button(13)
    button4 = Button(14)

    button1.when_pressed = FaixaAnterior

    button2.when_pressed = TocarEPausar

    button3.when_held = Acelera

    button3.when_released = VoltaAoNormal
    button4.when_pressed = embaralhaLista

    led.on()
    # loop infinito
    while True:
        metadados = player.metadata
        posicao = player.time_pos
        duracao = player.length

        if (metadados != None and posicao != None and duracao != None):
            nome = metadados["Title"]
            #if string.count(nome)>16:

            tempo_atual = int(posicao)
            tamanho = int(duracao)

            minuto_atual = str(tempo_atual // 60)
            segundos_atual = str(int(tempo_atual % 60))

            tamanho_minutos = str(tamanho // 60)
            tamanho_segundos = str(int(tamanho % 60))

            texto = "%s:%s de %s:%s" % (
                minuto_atual.zfill(2), segundos_atual.zfill(2),
                tamanho_minutos.zfill(2), tamanho_segundos.zfill(2))

            lcd.clear()
            lcd.message(nome)
            lcd.message('\n')
            lcd.message(texto)

        sleep(0.2)
예제 #47
-1
def programa():
    
    # importação de bibliotecas
    from time import sleep
    from mplayer import Player
    from gpiozero import LED
    from gpiozero import Button
    from Adafruit_CharLCD import Adafruit_CharLCD


    # definição de funções
    #player.loadfile("musica.mp3")
    #player.loadlist("lista.txt")

    def TocarEPausar():
      player.pause()
      if (player.paused):
        led.blink()
      else:
        led.on()


    def ProximaFaixa():
      player.pt_step(1)
      return

    def FaixaAnterior():
      if (player.time_pos > 2.00):
        player.time_pos = 0.00
        return
      player.pt_step(-1)
      return

    # criação de componentes
    player = Player()
    player.loadlist("playlist.txt")

    led = LED(21)
    
    lcd = Adafruit_CharLCD(2,3,4,5,6,7,16,2)

    button1 = Button(11)
    button2 = Button(12)
    button3 = Button(13)
    
    button1.when_pressed = FaixaAnterior
    button2.when_pressed = TocarEPausar
    button3.when_pressed = ProximaFaixa

    led.on()
    # loop infinito
    while True:
      metadados = player.metadata
      if metadados != None: 
        nome = player.metadata["Title"]
        lcd.clear()
        lcd.message(nome)
      sleep(0.2)