Exemple #1
0
class BBQpi_Config():
    def __init__(self):
        # Configuration
        self.pins_T0 = 3             # chip select pin for 1st thermocouple
        self.pins_T1 = 5             # chip select pin for 2nd thermocouple
        self.pins_out = 11           # output pin
        self.pins_clock = 7          # clock pin
        self.pins_relay = 24         # relay switch pin

        self.plot_avg = 5            # number of temp readings to be averaged

        self.control_time = 0        # initialize control time
        self.control_delay = 35      # control delay in second
        self.control_tolerance = 2   # tolerance

        self.alert_delay = 60       # alert delay in seconds
        self.alert_time = 0         # initialize alert time
        self.alert_email = '*****@*****.**'   # Send message to email/smtp

        self.out_temp = 'temp.csv'          # output file name for temperature data
        self.out_control = 'control.csv'    # input file name for control parameters

        self.network_cmd0 = "ip addr show wlan0 | grep inet | awk '{print $2}' | cut -d/ -f1"
        self.network_cmd1 = "ip addr show eth0 | grep inet | awk '{print $2}' | cut -d/ -f1"
        self.network_smtp = ['*****@*****.**', '030206raspberrypi']
        self.network_tweet = "/usr/local/bin/twitter [email protected] set "

        #Initialize components:
        self.LCD = Adafruit_CharLCD()
        self.LCD.begin(16, 1)
        self.RELAY = BBQpi_relay(self.pins_relay)
        self.T0 = BBQpi_thermocouple(self.pins_T0, self.pins_out, self.pins_clock)
        self.T1 = BBQpi_thermocouple(self.pins_T1, self.pins_out, self.pins_clock)

        # Initialize output files
        if os.path.isfile(self.out_temp):
            os.remove(self.out_temp)
        self.f = open(self.out_temp, 'wb')
        self.CSV = csv.writer(self.f, delimiter=',', quoting=csv.QUOTE_MINIMAL)

        # Find the devices IP Address
        self.ipaddr = ''
        try:
            self.ipaddr = run_cmd(self.network_cmd0)
        except:
            pass
        if (self.ipaddr == ''):
            self.ipaddr = run_cmd(self.network_cmd1)

    def sendmail(self, header, message):
        server = smtplib.SMTP("smtp.gmail.com", 587)
        server.starttls()
        server.login(self.network_smtp[0], self.network_smtp[1])
        server.sendmail(header, self.alert_email, message)

    def sendtweet(self, message):
        print "trying to send a tweet!"
        tweetcommand = self.network_tweet + message
        subprocess.call(tweetcommand, shell=True)
Exemple #2
0
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)
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 __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);
Exemple #5
0
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)
Exemple #6
0
	def run(self):
		global lcd
		loadconfig()
		if (mod_config["lcd"] == "yes"):
			lcd = Adafruit_CharLCD()
			lcd.begin(16,1)
		while True:
			loadcurrentconditions()
			evaluaterules()
			timestamp = time.time()
			while (time.time() - timestamp < mod_config["interval"]):
				if (mod_config["lcd"] == "yes"):
					lcd_showcurrentconditions()
Exemple #7
0
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()
Exemple #8
0
 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 __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)
Exemple #10
0
    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 __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()
Exemple #12
0
    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()
Exemple #13
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)
Exemple #14
0
    def get_lcd_controller(self, columns, lines):
        from Adafruit_CharLCD import Adafruit_CharLCD
        lcd = Adafruit_CharLCD(
            cols = columns,
            lines = lines,
            rs = self._pin_rs,
            en = self._pin_en,
            d4 = self._pin_d4,
            d5 = self._pin_d5,
            d6 = self._pin_d6,
            d7 = self._pin_d7,
            backlight = self._pin_backlight,
            invert_polarity = False,
            enable_pwm = self._enable_pwm,
            pwm = self._get_pwm(),
        )

        # Create custom chars, since not all ROMS have the PLAY and
        # PAUSE chars or other ones the user might need
        for i, pattern in enumerate(self._custom_char_patterns):
            lcd.create_char(i, pattern)

        return lcd
Exemple #15
0
 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 __init__(self, sortedlist, config):
        nokia_lcds = []
        #get bus pins first
        hd44780bus = config['local']['buses']['hd44780']
        nokiabus = config['local']['buses']['nokia']
        hd44780data_pins = []
        for i in range(8):
            thispin = 'LCD_D'+str(i)
            if thispin in hd44780bus:
                hd44780data_pins.append(hd44780bus[thispin])

        nokia_rst = nokiabus['LCD_RST']
        nokia_dc = nokiabus['LCD_DC']

        for ctrlid in sortedlist:
            dispdef = config['local']['controls'][ctrlid]['display']
            if dispdef['type'] == 'hd44780':
                newlcd = Adafruit_CharLCD(pin_rs = hd44780bus['LCD_RS'], pins_db=hd44780data_pins)
                newlcd.pin_e = dispdef['pin']
                GPIO.setup(newlcd.pin_e, GPIO.OUT)
                GPIO.output(newlcd.pin_e, GPIO.LOW)
                newlcd.begin(dispdef['width'], dispdef['height'])
                self.lcd[ctrlid] = newlcd
                print "Control %s is hd44780 on pin %s" % (ctrlid, newlcd.pin_e)
            else:
                if "contrast" in dispdef:
                    contrast = int(dispdef['contrast'])
                else:
                    contrast = 0xbb
                newlcd = NokiaLCD(pin_DC=nokia_dc, pin_RST=nokia_rst, pin_SCE=dispdef['pin'], contrast=contrast)
                newlcd.width = dispdef['width']
                newlcd.height = dispdef['height']
                newlcd.display_init()
                self.lcd[ctrlid] = newlcd
                nokia_lcds.append(newlcd)
                print "Control %s is nokia on pin %s" % (ctrlid, dispdef['pin'])
        # Do this now as it does not work in the big loop for some reason.
        if len(nokia_lcds) > 0:
            nokia_lcds[0].reset_all_displays()
            for nokia_lcd in nokia_lcds:
                nokia_lcd.display_init()
class GpioDisplay:

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

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

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

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

    def backlight(self, r, g, b):
        # not implemented
        pass
Exemple #18
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)
Exemple #19
0
 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)
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()
Exemple #21
0
    def __init__(self):
        random.seed()
        self.width = 40
        self.height = 2
        self.timeoutmin = 20
        self.timeoutmax = 100
        self.wait_time = 40
        self.separator = ' +++ '
        self.paused = False
        self.paused_loop = 0
        self.busy = False
        self.busy_loop = 0
        self.elapsed = ''
        
        self.lines = []
        self.offset = []
        self.tag = []
        for i in range(self.height):
            self.lines.append('')
            self.offset.append(0)
            self.tag.append('')
            
        self.ascii_art = {}
        self.load_ascii_art()
        
        # 0   - animation running
        # > 0 - animation countdown
        # -1  - animation and countdown disabled
        self.easter_egg_countdown = -1
        
        self.animation_index = self.ascii_art.keys()[random.randrange(0, len(self.ascii_art))]
        self.animation_phase = 0

        self.lcd = Adafruit_CharLCD()
        self.lcd.begin(40, 2)
        self.lcd.define_char(1, [0, 0x10, 0x08, 0x04, 0x02, 0x01, 0, 0])
        self.lcd.define_char(2, [0, 31, 14, 4, 21, 10, 0, 0])
        self.current_lines = ["", ""]
Exemple #22
0
	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)
Exemple #23
0
import serial
import sys
import sqlite3 as lite

from Adafruit_CharLCD import Adafruit_CharLCD
from subprocess import *
from time import sleep, strftime
from datetime import datetime

ser = serial.Serial('/dev/ttyAMA0', 2400, timeout=1)
lcd = Adafruit_CharLCD()
lcd.begin(16, 1)

whatToExpect = 0
deviceID = 0
userID = 0
previousScan = 0
curTag = 0
lcdMessage = "Hello"

con = None
cur = None


def databaseQueryOne(query, arguments):
    con = lite.connect('../devicelab/data/devicelabdb')
    cur = con.cursor()
    cur.execute(query, arguments)
    result = cur.fetchone()
    con.commit()
    con.close()
Exemple #24
0
import os
import glob
import time
from Adafruit_CharLCD import Adafruit_CharLCD
from time import sleep, strftime
lcd = Adafruit_CharLCD()

lcd.begin(16, 2)

os.system('modprobe w1-gpio') # this is specific to ds18b20
os.system('modprobe w1-therm')# this is specific to ds18b20
base_dir = '/sys/bus/w1/devices/' #address of base directory
#in linux, every device connected to system is considered as a single FILE
# and its address is shown above

device_folder = glob.glob(base_dir + '28*')[0] # to the base address, 28 and * means wild card is attached
# because actual sensor address starts from 28
device_file = device_folder + '/w1_slave'

def read_temp_raw():
    f = open(device_file, 'r') # read the device file with an attribute of 'r' means Read ONLY
    lines = f.readlines()#lines read the status
    f.close()   # close the file
    return lines

def read_temp():
    lines = read_temp_raw()                 # this is actual process of reading temperature from sensor, and processing it, 
    while lines[0].strip()[-3:] != 'YES':
        time.sleep(0.2)
        lines = read_temp_raw()
    equals_pos = lines[1].find('t=')
Exemple #25
0
import sys

sys.path.append('/home/pi/Adafruit-Raspberry-Pi-Python-Code/Adafruit_CharLCD')
from Adafruit_CharLCD import Adafruit_CharLCD

lcd = Adafruit_CharLCD()  # instantiate LCD Display
lcd.clear()
from time import sleep
import RPi.GPIO as GPIO

GPIO.setmode(GPIO.BCM)  # set up BCM GPIO numbering
# Set up input pin
GPIO.setup(21, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
# Set up LED output
GPIO.setup(20, GPIO.OUT)


# Callback function to run when motion detected
def motionSensor(channel):
    lcd.clear()
    GPIO.output(20, GPIO.LOW)
    if GPIO.input(21):  # True = Rising
        global counter
        counter += 1
        lcd.message('Motion Detected\n{0}'.format(counter))
        GPIO.output(20, GPIO.HIGH)


# add event listener on pin 21
GPIO.add_event_detect(21, GPIO.BOTH, callback=motionSensor, bouncetime=300)
counter = 0
Exemple #26
0
#!/usr/bin/env python

from Adafruit_CharLCD import Adafruit_CharLCD
from subprocess import *
from time import sleep, strftime
from datetime import datetime

lcd = Adafruit_CharLCD()

cmd = "ip addr show eth0 | grep inet -m 1 | awk '{print $2}' | cut -d/ -f1"

lcd.begin(20, 1)


def run_cmd(cmd):
    p = Popen(cmd, shell=True, stdout=PIPE)
    output = p.communicate()[0]
    return output


while 1:
    lcd.clear()
    ipaddr = run_cmd(cmd)
    lcd.message(datetime.now().strftime('%Y-%m-%d  %p %I:%M\n'))
    lcd.message('IP %s\n' % (ipaddr))
    sleep(60)
Exemple #27
0
#!/usr/bin/python
import time
from Adafruit_CharLCD import Adafruit_CharLCD
from time import sleep, strftime
from datetime import datetime

lcd = Adafruit_CharLCD()
lcd.clear()
lcd.backlightOn()
lcd.begin(16, 4)
lcd.setCursor(0, 0)
lcd.message(datetime.now().strftime('%b %d  %H:%M\n'))
lcd.setCursor(0, 1)
lcd.message('hello')
Exemple #28
0
#!/usr/bin/python

#
# Simple CMD Script for LCD Displays for Raspberry Pi
# Usage:
# sudo ./lcdcmd.py "Raspberry @ Fiae.ws" " " " Original Script by" "      Adafruit"
#

import sys
from Adafruit_CharLCD import Adafruit_CharLCD
from subprocess import *
from time import sleep, strftime
from datetime import datetime

lcd = Adafruit_CharLCD()
lcd.begin(16, 4)
lcd.clear()

print '\nLines:'
sys.argv.remove(sys.argv[0])
for item in sys.argv:
    print item
    lcd.message('' + item + '\n')

print 'Done.'
Exemple #29
0
lcd_cols = 16
lcd_rows = 2

hit_target = False

state_not_started = 1
state_pre_culture = 2
state_waiting_culture = 3
state_incubation = 4
state_done = 5
rampUpDown = 1  #1 is a ramp up temp, 2 is a ramp down temp

state = state_not_started
# Initialize the LCD using the pins above.
lcd = LCD(lcd_rs, lcd_en, lcd_d4, lcd_d5, lcd_d6, lcd_d7, lcd_cols, lcd_rows,
          lcd_backlight)

# Print a two line message
lcd.message('Yogurt Pi')


def setTemp(T):
    global hit_target
    global finishTime
    if (temp_f < T):
        if (rampUpDown == 2):
            if (hit_target == False):
                hit_target = True
                if (state == state_pre_culture):
                    sendTextMessage('Add Culture to the Yogurt')
        #turn on the heater
Exemple #30
0
#!/usr/bin/python
# -*- coding: utf-8 -*-
 
from Adafruit_CharLCD import Adafruit_CharLCD
from subprocess import *
from time import sleep, strftime
from datetime import datetime
 
lcd = Adafruit_CharLCD()
 
file = "/sys/bus/w1/devices/123-123456789/w1_slave"
 
lcd.begin(16,1)
 
def get_temp(file):
        #Open file written to by temp sensor
        tfile = open(file)
 
        #read all text in file
        text = tfile.read()
 
        #Close file once text is read
        tfile.close()
 
        #pull out the temperature value
        temperaturedata = text.split("\n")[1].split(" ")[9]
 
        # The first two characters are "t=", so get rid of those and convert the temperature from a string to a number.
        temperature = float(temperaturedata[2:])
 
        # Put the decimal point in the right place and display it.
Exemple #31
0
from Adafruit_CharLCD import Adafruit_CharLCD
from time import sleep, strftime
from datetime import datetime
import socket

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


def get_ip_address():
    return [(s.connect(('8.8.8.8', 53)), s.getsockname()[0], s.close())
            for s in [socket.socket(socket.AF_INET, socket.SOCK_DGRAM)]][0][1]


try:
    while 1:
        lcd.clear()
        ip = get_ip_address()
        lcd.message(datetime.now().strftime('%b %d  %H:%M:%S\n'))
        lcd.message('IP {}'.format(ip))
        sleep(2)

except KeyboardInterrupt:
    print('CTRL-C pressed.  Program exiting...')
Exemple #32
0
from Adafruit_CharLCD import Adafruit_CharLCD

#Getting the instance of the lib
lcd = Adafruit_CharLCD()

#Input from user
msg = raw_input("Enter message to display\n")

#Display it on the LCD
lcd.message(str(msg))

#You can use other functions in the library

#Clearing the display
#lcd.clear()

#Toggle the text visibility on the LCD
#lcd.noDisplay()  #Make the text invisible
#lcd.display()    #Make the text visible

#Toggle cursor visibility
#lcd.noCursor()   	#Make the cursor invisible
#lcd.cursor()     	#Make the cursor visible

#Blink the cursor
#lcd.noBlink()    	#Disable the cursor blink
#lcd.blink()	  	#Make the cursor blink

#Position the cursor to the start of the display
#lcd.home()
Exemple #33
0
from Adafruit_CharLCD 
import Adafruit_CharLCD 
import time 
import RPi.GPIO as GPIO 
import pygame.mixer 

pygame.mixer.init() 
Music= pygame.mixer.Sound("") 
MusicList = ["Ylvis- What The Fox Say- Lyrics.wav", "David Bowie Starman Lyrics.wav", "Queen - 'Bohemian Rhapsody'.wav"] 
AlarmMusicList= [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] 

lcd = Adafruit_CharLCD() 
lcd.begin(20, 4) 
buttonUp = 11 
buttonDown = 13 
buttonEnter = 15 
buttonBack = 37 


GPIO.setmode(GPIO.BOARD) 
Button = [11, 13, 15, 37] 

for x in Button:
    GPIO.setup(x, GPIO.IN, GPIO.PUD_UP) 

time_stamp_0 = time.time() 
time_stamp_1 = time.time() 
time_stamp_2 = time.time() 
time_stamp_3 = time.time() 

screen = 0 
#!/usr/bin/python

import RPi.GPIO as GPIO
from Adafruit_CharLCD import Adafruit_CharLCD
from subprocess import *
from time import sleep, strftime
from datetime import datetime
import os
import FPS, sys
import signal
import time

lcd = Adafruit_CharLCD()

lcd.begin(16, 1)
lcd_columns = 16
lcd_rows = 2


class keypad:
    def __init__(self, columnCount=3):
        GPIO.setmode(GPIO.BCM)

        # CONSTANTS
        if columnCount is 3:
            self.KEYPAD = [[1, 2, 3], [4, 5, 6], [7, 8, 9], ["*", 0, "#"]]

            self.ROW = [4, 17, 27, 22]
            self.COLUMN = [18, 23, 24]

        elif columnCount is 4:
Exemple #35
0
# -*- coding: utf-8 -*-

import sys
sys.path.append('/home/pi/Adafruit-Raspberry-Pi-Python-Code-legacy/Adafruit_CharLCD') 
from Adafruit_CharLCD import Adafruit_CharLCD

import requests
import json

url = 'http://weather.livedoor.com/forecast/webservice/json/v1'
locale = {'city': '110010'}
data = requests.get(url, params = locale).json()

tenkiNo = [u'ハレ',u'ハレトキドキクモリ',u'ハレトキドキアメ',u'ハレトキドキユキ',u'ハレノチクモリ',u'ハレノチアメ',u'ハレノチユキ',u'クモリ',u'クモリトキドキハレ',u'クモリトキドキアメ',u'クモリトキドキユキ',u'クモリノチハレ',u'クモリノチアメ',u'クモリノチユキ',u'アメ',u'アメトキドキハレ',u'アメトキドキクモリ',u'アメトキドキユキ',u'アメノチハレ',u'アメノチクモリ',u'アメノチユキ',u'ツヨイアメ',u'ユキ',u'ユキトキドキクハレ',u'ユキトキドキクモリ',u'ユキトキドキアメ',u'ユキノチハレ',u'ユキノチクモリ',u'ユキノチアメ',u'ツヨイユキ']
try:
  lcd = Adafruit_CharLCD()
  lcd.clear()

for weather in data['forecasts'][0:2]:
	tenki = int(weather['image']['url'][37:-4])-1
	print (tenki)
	#text=tenkiNo[tenki]
	#lcd.message(text)
	#lcd.message('\n')
 
#try:
#  lcd = Adafruit_CharLCD()
#  lcd.clear()
 
#  lcd.message(text1)
#  lcd.message('\n')
Exemple #36
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)

        return 'ok'
    except Exception as e:
        return 'ok'  # e
Exemple #37
0
def getkey():
    fd = sys.stdin.fileno()
    old = termios.tcgetattr(fd)
    new = termios.tcgetattr(fd)
    new[3] = new[3] & ~TERMIOS.ICANON & ~TERMIOS.ECHO
    new[6][TERMIOS.VMIN] = 1
    new[6][TERMIOS.VTIME] = 0
    termios.tcsetattr(fd, TERMIOS.TCSANOW, new)
    c = None
    try:
        c = os.read(fd, 10)
    finally:
        termios.tcsetattr(fd, TERMIOS.TCSAFLUSH, old)
    return c

lcd = Adafruit_CharLCD()

def terminal():
    lcd.begin(40,2)
    lcd.cursor()
    lcd.testfun()
    col = 0;
    row = 0;
    while True:
        x = getkey()
        c = x[0]
        rest = x[1:]
        n = ord(c)
        print col, row, n, rest, [ord(i) for i in rest]
        if n == 127:
            col = max(col - 1,0)
Exemple #38
0
class _LcdProc(Process):
    ''' The process which manages the LCD output. '''
    def __init__(self, queues):
        ''' Initialize the LCD display '''
        Process.__init__(self, name="LCD")

        self.inQueue = queues[0]  # to read from
        self.outQueue = queues[1]  # to write to

        # LCD PINS
        self.PIN_RS = 26  # RS pin of LCD
        self.PIN_E = 19  # enable pin of LCD
        self.PIN_DB = [13, 6, 5, 11]  # data pins for LCD
        self.LCD_COL_SIZE = 2  # number of charactes available vertically on LCD
        self.LCD_ROW_SIZE = 16  # the number of characters available horizontally on LCD
        self.PIN_BLT = None

        self.DEF_MSG_LEN = 10  # the default space allocated for displaying a message on LCD

        self.PIN_LCD_BACKLIGHT = 20  # backlight pin for LCD
        # the Adafruit LCD object
        self.lcd = Adafruit_CharLCD(self.PIN_RS, self.PIN_E, self.PIN_DB[0],
                                    self.PIN_DB[1], self.PIN_DB[2],
                                    self.PIN_DB[3], self.LCD_COL_SIZE,
                                    self.LCD_ROW_SIZE)

        self.curr_screen = []

        # fill current screen with empty
        for i in range(self.LCD_COL_SIZE * self.LCD_ROW_SIZE):
            self.curr_screen.append(" ")

        # turn on the display
        if (self.PIN_BLT != None):
            GPIO.setmode(GPIO.BCM)
            GPIO.setup(PIN_BLT, GPIO.OUT)
            GPIO.output(self.PIN_BLT, 1)

    def run(self: '_LcdProc') -> None:
        ''' The main loop of the process waits for something to print, then prints it '''
        while True:
            # check for data to print
            data = self.inQueue.get()
            # start a new thread to print data to LCD
            t = threading.Thread(target=self._write_message, args=(data, ))
            t.start()

    def _update_osd(self: '_LcdProc', overlay: '[str]') -> None:
        ''' Display the overlay on the LCD sccreen. Given overrlay which is a list of characters
        for each position of the lcd screen, Loop through each character, and write to the 
        correct position in the LCD screen individually.

        REQ: len(overlay) is even
        REQ: each item in overlay is a single character
        '''
        # only update
        for i in range(len(overlay)):
            if self.curr_screen[i] != overlay[i]:
                # do if the current character is different from the overlay character at this position
                row = int(i >= self.LCD_ROW_SIZE)
                col = i % self.LCD_ROW_SIZE

                # set the position of the cursor, and write a character
                self.lcd.set_cursor(col, row)
                self.lcd.message(overlay[i])
                # remember the state of the current screen
                self.curr_screen[i] = overlay[i]

    def _create_osd_layer(self: '_LcdProc', data: 'str',
                          dType: 'int') -> [str]:
        ''' Given the data, and a type, return an overlay layer which is a list of 
        characters in positions corresponding to the position of each pixel. Depending on the type,
        the characters will be positioned differently. Data can be positioned in any programed position below.
        
        REQ: data is a string of characters
        REQ: dType an int that is handled below 
        '''

        new_screen = []
        # clear the screen layer
        for i in range(self.LCD_ROW_SIZE * self.LCD_COL_SIZE):
            new_screen.append(" ")

        if dType == 1:
            # 10 character message
            dbug(PARCEL, str(len(new_screen)) + " and " + str(len(data)))
            for i in range(len(data)):
                new_screen[i] = data[i]

        elif dType == 2:
            # temperature top right (print from right to left)
            new_screen[15] == "C"
            new_screen[14] == "°"
            if len(data) == 1:
                # single digit temperatures
                new_screen[13] == data
            elif len(data) == 2:
                # double digit temperatures
                new_screen[12] == data[0]
                new_screen[13] == data[1]

        return new_screen

    def _new_message_scroll(self: '_LcdProc', message: 'str',
                            length: 'int') -> [[str]]:
        ''' Given a message, create a list of overlays to be displayed on LCD screen.
        If the message is less than the given length, create ony one layer, or one list
        of list of characters. Otherwise, create enough layers for there to be a full loop 
        cycle of the string printed.
        '''
        full_scroll_arr = [
        ]  # contains list of list of strings for full scroll
        lcd_arr = []  # contains the current scroll

        # if message shorter than or equal to 16 characters, no need to scroll
        if (len(message) <= length):
            for i in range(len(message)):
                lcd_arr.append(message[i])

            full_scroll_arr.append(lcd_arr)
            return full_scroll_arr

        # add extra spaces so tail is not connected to head while scrolling
        message += "  "

        # populate the char_arr with whitespace
        for i in range(length):
            lcd_arr.append(" ")

        # populate with content
        for i in range(len(message) + 1):
            a = 0
            for j in range(i, i + length):
                k = j
                if (j >= len(message)):
                    k = j - len(message)

                lcd_arr[a] = message[k]
                a += 1
            # remember the scroll instance
            full_scroll_arr.append(deepcopy(lcd_arr))

        # return all scroll instances for full scroll effect
        return full_scroll_arr

    def _clear(self: '_LcdProc') -> None:
        ''' Clear the LCD screen, along with the overlay in memory. '''
        self.lcd.clear()
        # clear screen in memory
        for i in range(self.LCD_COL_SIZE * self.LCD_ROW_SIZE):
            self.curr_screen[i] = " "

    def _write_message(self: '_LcdProc', message: 'str') -> None:
        ''' Given a message, write the message to screen. '''

        message_layers = self._new_message_scroll(message, 10)
        for i in range(len(message_layers)):
            start = time.time()
            osd_layer = self._create_osd_layer(message_layers[i], 1)
            self._update_osd(osd_layer)  # display on screen
            dbug(PARCEL, time.time() - start)
            time.sleep(0.5)
        dbug(PARCEL, "---------------------------------")
        return
Exemple #39
0
from Adafruit_CharLCD import Adafruit_CharLCD
import RPi.GPIO as GPIO
from time import sleep

gas = 8
relay2 = 6

GPIO.setmode(GPIO.BCM)
GPIO.setup(6, GPIO.OUT)
GPIO.setup(gas, GPIO.IN)
lcd = Adafruit_CharLCD()

lcd.begin(16, 2)
lcd.clear()

while True:
    if (GPIO.input(gas) == 0):
        lcd.setCursor(13, 0)
        lcd.message("GP")
        print "GP"
        GPIO.output(relay2, True)
        sleep(1)
    else:
        lcd.setCursor(13, 0)
        lcd.message("NG")
        print "NG"
        GPIO.output(relay2, False)
        sleep(1)
import time
from Adafruit_CharLCD import Adafruit_CharLCD
lcd = Adafruit_CharLCD(rs=21,
                       en=20,
                       d4=16,
                       d5=12,
                       d6=7,
                       d7=26,
                       cols=16,
                       lines=2)
lcd_length = 16


def measure_show(voltage, current, m_time, energy):
    voltage = str(voltage)[:6]
    current = str(current)[:6]
    m_time = str(m_time)[:5]
    energy = str(energy)[:5]
    lcd.clear()
    lcd.message(f"{voltage}V {current}A\n{m_time}s {energy}mAh")


def message(first_line, secound_line=None):
    if len(first_line) > lcd_length:
        print("too long first line")
    if len(secound_line) > lcd_length:
        print("too long secound line")
    lcd.clear()
    lcd.message(f"{first_line}\n{secound_line}")

Exemple #41
0
#!/usr/bin/python

from Adafruit_CharLCD import Adafruit_CharLCD
from time import sleep
import Adafruit_DHT

# initialize LCD (must specify pinout and dimensions)
lcd = Adafruit_CharLCD(rs=27, en=17, d4=14, d5=4, d6=3, d7=2, cols=16, lines=2)


# write message to LCD1602
def lcd_message(message):
    lcd.clear()
    lcd.message(message)


# welcome loading screen
lcd.clear()
lcd.message("LOADING...\n")
for i in range(16):
    lcd.message("*")
    sleep(0.5)

lcd.clear
lcd.message("***ENVIRO-HUB***\nSTATE: IDLE")
Exemple #42
0
    endereco = endereco_base + "/sendMessage"
    dados = {"chat_id": id_da_conversa, "text": "Oi!"}
    resposta = post(endereco, json=dados)


def TiraFoto():
    for i in range(0, 5):
        system("fswebcam --resolution 640x480 foto" + str(i + 1) + ".jpeg")
        led1.blink(n=1)
        sleep(2)


def Gravacao():
    lcd.clear()
    lcd.message("Gravando ...")
    system("arecord --duration 5 --format cd teste.wav")
    lcd.clear()


# criação de componentes
lcd = Adafruit_CharLCD(2, 3, 4, 5, 6, 7, 16, 2)
botao1 = Button(11)
botao2 = Button(12)
botao3 = Button(13)
led1 = LED(21)
botao1.when_pressed = Gravacao
botao2.when_pressed = TiraFoto
botao3.when_pressed = Envio
while True:
    sleep(0.5)
Exemple #43
0
#!/usr/bin/env python

import smbus
import time
from Adafruit_CharLCD import Adafruit_CharLCD

bus = smbus.SMBus(1)
lcd = Adafruit_CharLCD(rs=26,
                       en=19,
                       d4=13,
                       d5=27,
                       d6=17,
                       d7=22,
                       cols=16,
                       lines=2)

while True:
    bus.write_byte(0x40, 0xF5)
    time.sleep(0.3)

    data0 = bus.read_byte(0x40)
    data1 = bus.read_byte(0x40)

    humidity = str(((data0 * 256 + data1) * 125 / 65536.0) - 6)
    time.sleep(0.3)

    bus.write_byte(0x40, 0xF3)
    time.sleep(0.3)

    data0 = bus.read_byte(0x40)
    data1 = bus.read_byte(0x40)
# https://github.com/pedrobettoni/leskSecuritySystem
# http://pedrobettoni.website/2016/07/29/raspberry-pi-motion-security-system

from subprocess import Popen, PIPE  #To get the string time
import RPi.GPIO as GPIO
import time
from picamera import PiCamera
from time import sleep
from Adafruit_CharLCD import Adafruit_CharLCD
from subprocess import *
from time import sleep, strftime
from datetime import datetime
import sys

#Declaring and initialize 16x2 LCD object
lcd = Adafruit_CharLCD(pin_rs=26, pin_e=19, pins_db=[13, 6, 5, 11])
lcd.begin(16, 1)

#Declare and initialize camera
from picamera import PiCamera
from time import sleep
camera = PiCamera()

#Set GPIO  pin numbering.
GPIO.setmode(GPIO.BCM)

#PIR sensor input pin
PIR_PIN = 9

# defining PIR_PIN as an input.
GPIO.setup(PIR_PIN, GPIO.IN)
Exemple #45
0
import pigpio
import RPi.GPIO as GPIO
import time
from Adafruit_CharLCD import Adafruit_CharLCD
from firebase import firebase

# connect to the 
pi = pigpio.pi()

# 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()

sensor1 = 23
sensor2 = 18

GPIO.setmode(GPIO.BCM)

GPIO.setup(sensor1,GPIO.IN)
GPIO.setup(sensor2,GPIO.IN)

firebase = firebase.FirebaseApplication('https://login-f0a7b.firebaseio.com/', None)
firebase.put('https://login-f0a7b.firebaseio.com/Barrier','servo_in',False)
firebase.put('https://login-f0a7b.firebaseio.com/Barrier','servo_out',False)

lcd.message('READY')
time.sleep(1)
lcd.set_cursor(0,0)#col,row (start with 0-1 for row, col 0-15)
Exemple #46
0
SMOKE_IN = 19
TRIG = 2
ECHO = 3

# GPIO Pins
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
GPIO.setup(SMOKE_IN, GPIO.IN)
GPIO.setup(TRIG, GPIO.OUT)
GPIO.setup(ECHO, GPIO.IN)

# LCD GPIO Pins
lcd_af = Adafruit_CharLCD(rs=26,
                          en=12,
                          d4=13,
                          d5=6,
                          d6=5,
                          d7=11,
                          cols=16,
                          lines=2)  # GPIO.BCM

# Arduino Variables
office = 13
r_office = 4
kitchen = 12
r_kitchen = 2
meeting_room = 3
r_meeting_room = 5
waiting_room = 7
r_waiting_room = 14
employee_room = 9
bath_room = 8
Exemple #47
0
from Adafruit_CharLCD import Adafruit_CharLCD  # Importing Adafruit library for LCD
from time import sleep  # Importing sleep from time library to add delay in program
# instantiate lcd and specify pins
lcd = Adafruit_CharLCD(rs=26,
                       en=19,
                       d4=13,
                       d5=6,
                       d6=5,
                       d7=21,
                       cols=16,
                       lines=2)
lcd.clear()
# display text on LCD,  \n = new line
lcd.message('Welcome to\nElectronicshobbyists.com')
sleep(1)
Exemple #48
0
 def __init__(self):
     self.lcd = Adafruit_CharLCD(25, 24, 23, 17, 21, 22, 16, 2)
Exemple #49
0
import dht11
import time
import datetime
import sys
import os
import serial
#import serialget
sys.path.append('/home/pi/proj/Adafruit_CharLCD')
from Adafruit_CharLCD import Adafruit_CharLCD

# initialize GPIO
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
GPIO.cleanup()
lcd = Adafruit_CharLCD(rs=26, en=19,
                       d4=13, d5=6, d6=5, d7=11,
                       cols=16, lines=2)
ser = serial.Serial(              
               port='/dev/ttyACM0',
               baudrate = 9600,
               parity=serial.PARITY_NONE,
               stopbits=serial.STOPBITS_ONE,
               bytesize=serial.EIGHTBITS,
               timeout=1
           )
ser.reset_input_buffer()
buzzer=23
count=0
count1=0
GPIO.setup(buzzer,GPIO.OUT)
lcd.clear()
import os, time, urllib2, httplib, csv, sys
import RPi.GPIO as GPIO

from Adafruit_CharLCD import Adafruit_CharLCD

lcd = Adafruit_CharLCD()
lcd.clear()
lcd.message("Awaiting first\nmeasurments")

os.system('sudo modprobe w1-gpio')
os.system('sudo modprobe w1-therm')
time.sleep(
    10)  # wait to give the 1-wire software time to find the connected sensors

GPIO.setmode(GPIO.BCM)
# Set led pin as out, and turn it of.
GPIO.setup(10, GPIO.OUT)
GPIO.setup(10, GPIO.LOW)

# Set optocoupler pin as in, where high readings means that a external power source is available.
GPIO.setup(8, GPIO.IN)

base_dir = '/sys/bus/w1/devices'


def get_settings():
    result = urllib2.urlopen("http://localhost/emoncms/raspberrypi/get.json")
    result = result.readline()
    result = result[1:-1].split(',')
    settings = {}
    for s in result:
Exemple #51
0
from Adafruit_CharLCD import Adafruit_CharLCD
from time import sleep

lcd = Adafruit_CharLCD(rs=22, en=11, d4=23, d5=10, d6=9, d7=25, cols=16, lines=2)
i=0

while True:
    lcd.clear()
    lcd.message('Counting: ' + str(i))
    sleep(1)
    i = i+1
Exemple #52
0
class ButtonQuery():
    website = 'http://bfitzy2142.appspot.com'
    headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}
    rsvp_stat = {"Status": "init"}
    # change filepath to a folder containing mp3 files
    file_path = '/home/pi/Music/temp/'
    data_sent = {'playing': ''}
    GPIO.setmode(GPIO.BCM)
    GPIO.setup(4, GPIO.OUT)
    #  Initialize LCD (must specify pinout and dimensions)
    lcd = Adafruit_CharLCD(rs=26, en=19,
                           d4=13, d5=6, d6=5, d7=11,
                           cols=16, lines=2)
    requests = 0
    getRequests = 0

    def __init__(self):
        self.sounds = self.get_sounds()
        self.run()

    def run(self):
        """
        This is the main body of the program. Run calls the webserver
        after waiting two seconds to determine if the ping status is true;
        the status of the server is stored in svr_stat. If it is found to
        be true, and another request has not already been sent, the script
        will send the song to be played via a post api request to the webserver
        and start playing that audio for me to hear.

        Parameters:
        svr_stat (Server Status): Will be used to store the value of
        webstat['Status'] which contains a boolean indicating if the
        webserver button has been pressed or not.

        rsvp_stat (Reply Status): Used to store the value of the reply
        from the webserver's data api serving the post with the song to
        be played by the Raspberry Pi.
        """
        try:
            while(True):
                self.lcd.clear()
                webstat = self.api_handler('GET')
                self.getRequests += 1
                svr_stat = webstat['Status']
                self.lcd.message('GET:' + str(self.getRequests) + 
                              'RQ:' + str(self.requests) + '\n')
                self.lcd.message(datetime.now().strftime('%b %d %H:%M:%S'))
                svr_stat = webstat['Status']
                rsvp = self.rsvp_stat['Status']

                if (svr_stat == True and rsvp == 'init'):
                    self.requests += 1
                    response = self.api_handler('POST')
                    self.rsvp_stat = json.loads(response.text)
                    print('Ping from website @' + str(datetime.now()))
                    self.lcd.clear()
                    self.lcd.message('About to play:\n')
                    self.lcd.message(self.current_sound)
                    time.sleep(2)
                    for x in range(0, 16):
                        self.lcd.move_left()
                        time.sleep(.4)
                    self.play_sound(self.current_sound)
                    self.lcd.clear()

                if (svr_stat == False and rsvp == 'Success'):
                    self.rsvp_stat = {"Status": "init"}

                time.sleep(2)

        except KeyboardInterrupt:
            print('\nCTRL-C pressed.  Program exiting...')
            self.lcd.clear()

        finally:
            self.lcd.clear()
            GPIO.cleanup()

    def get_sounds(self):
        """
        Gets available sound tracks to be played

        Returns:
        List of files in file_path directory
        """
        track_list = []
        for files in walk(self.file_path):
            for filename in files:
                track_list.append(filename)
        # Index 2 contains items in parent directory
        return track_list[2]

    def api_handler(self, request_type):
        """
        Method to send and retrieve data from webapp api.

        Parameters:
        request_type: 
        'GET': to retrieve status from webapp.
        'POST': Send next song to play.

        Returns:
        /get-status: {"Status": 'True/False'}
        /data: Status code of post <Success> if okay. 
        """
        if (request_type is 'GET'):
            raw_request = requests.get(self.website + '/get-status')
            return raw_request.json()
        elif (request_type is 'POST'):
            self.current_sound = self.sounds[randint(0, len(self.sounds)-1)]
            data_sent = {'playing': self.current_sound}
            return requests.post(
                self.website + '/data',
                allow_redirects=False,
                data=json.dumps(data_sent),
                headers=self.headers)

    def play_sound(self, sound):
        """
        Play_sound is called to play an audio track passed in via
        the sound parameter.
        """
        GPIO.output(4, True)
        mixer.init()
        mixer.music.load(self.file_path + sound)
        mixer.music.play()
        while mixer.music.get_busy() == 1:
            continue
        GPIO.output(4, False)
Exemple #53
0
#!/usr/bin/python
from Adafruit_CharLCD import Adafruit_CharLCD

lcd = Adafruit_CharLCD()

lcd.begin(16, 2)
lcd.clear()

lcd.message("STOP SkyPi_LCDd\n")
sleep(2)
Exemple #54
0
    else:
        stepperAzi.counterclockwise(5, abs(stepsToTakeAzi))

    stepsToTakeAlt = 128 - stepsTakenAlt
    if stepsToTakeAlt > 0:
        stepperAlt.counterclockwise(5, abs(stepsToTakeAlt))
    else:
        stepperAlt.clockwise(5, abs(stepsToTakeAlt))


from Adafruit_CharLCD import Adafruit_CharLCD
#Initiate LCD
lcd = Adafruit_CharLCD(rs=21,
                       en=20,
                       d4=24,
                       d5=25,
                       d6=12,
                       d7=16,
                       cols=16,
                       lines=2)

#StepperAzi
stepsPerRev = 512

#Checking Shelve for previous position, then return to true north first. If there is non assume true North already taken
shelfDirection = shelve.open('Direction')
try:
    stepsTakenAzi = shelfDirection['Azi']
    stepsTakenAlt = shelfDirection['Alt']
    #Bring bot axis to true north
    lcd.clear()
    lcd.message('Initialize to\n True North')
def read_temp():
    lines = read_temp_raw()                 # this is actual process of reading temperature from sensor, and processing it, 
    while lines[0].strip()[-3:] != 'YES':
        time.sleep(0.2)
        lines = read_temp_raw()
    equals_pos = lines[1].find('t=')
    if equals_pos != -1:
        temp_string = lines[1][equals_pos+2:]
        temp_c = float(temp_string) / 1000.0
        temp_f = temp_c * 9.0 / 5.0 + 32.0
        return temp_c, temp_f
###########################################################################

sensor = Adafruit_DHT.DHT22
pin = 22
lcd = Adafruit_CharLCD()
lcd.begin(16, 2)
lcd.clear()
 
# Define some constants from the datasheet
 
DEVICE     = 0x23 # Default device I2C address
 
POWER_DOWN = 0x00 # No active state
POWER_ON   = 0x01 # Power on
RESET      = 0x07 # Reset data register value
# Start measurement at 1lx resolution. Time typically 120ms
# Device is automatically set to Power Down after measurement.
ONE_TIME_HIGH_RES_MODE_1 = 0x20

 
x3 = 0
sensor_copo = 0  #auxiliar do sensor do copo
aux_alarme1 = 0
aux_alarme2 = 0  #auxiliar de alarme ativado
aux_alarme3 = 0
alarme1 = ['0']
alarme2 = ['0']  #vetor de alarmes
alarme3 = ['0']
ledbuzzer = 0
format = "%H:%M:%S"
auxaviso = 0  #auxiliar para aviso de tempo maximo
aviso = 0  #auxiliar do tempo para aviso de tempo maximo
lcd = Adafruit_CharLCD.Adafruit_CharLCD(rs=18,
                                        en=23,
                                        d4=24,
                                        d5=25,
                                        d6=8,
                                        d7=7,
                                        cols=20,
                                        lines=4)
auxi1 = 0
auxi2 = 0  #auxiliar info copo
auxi3 = 0
t = 0  #auxiliar tempo display linha 2
aux = 1  #auxiliar display linha 2
horario1 = ['0']
horario2 = [
    '0'
]  #vetor de alarmes transformados para string para o display linha 2
horario3 = ['0']
cont = 0  #auxiliar display linha 3
refuel1 = ''
#!/usr/bin/python

from Adafruit_CharLCD import Adafruit_CharLCD
from subprocess import *
from time import sleep, strftime
from datetime import datetime

lcd = Adafruit_CharLCD()

df_cmd = "df -h | grep pidata | awk '{print $3 \"/\" $2}'"
uptime_cmd = "uptime | grep -ohe 'up .*' | sed 's/,//g' | awk '{ print $2\" \"$3 }'"
free_cmd = "free | awk 'FNR == 3 {print $4/($3+$4)*100}'"

lcd.begin(16,1)

def run_cmd(cmd):
    p = Popen(cmd, shell=True, stdout=PIPE)
    output = p.communicate()[0]
    return output

def print_nas_usage():
    lcd.clear()
    usage = run_cmd(df_cmd)
    lcd.message("PiData NAS\n")
    lcd.message("Used: " + usage)

def print_system():
    lcd.clear()
    uptime = run_cmd(uptime_cmd)
    free = run_cmd(free_cmd)
    lcd.message("Up: " + uptime + "\n")
#!/usr/bin/env python

from Adafruit_CharLCD import Adafruit_CharLCD

lcd = Adafruit_CharLCD()

lcd.begin(20, 1)

lcd.clear()

lcd.message(
    "Line 1        Line 1\nLine 2        Line 2\nLine 3        Line 3\nLine 4        Line 4"
)
Exemple #59
0
while True:
  # 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
Exemple #60
0
                 headers=headers)

data = r.json()

weather = data["weather"]["hourly"]
cTime = weather[0]["timeRelease"]
cSky = weather[0]["sky"]["name"]
cWind = weather[0]["wind"]["wspd"]
cTemp = weather[0]["temperature"]["tc"]

cWeather1 = "      Time\n" + cTime
cWeather2 = "      Temp\n    " + cTemp + "'C"
lcd = Adafruit_CharLCD(rs=22,
                       en=11,
                       d4=23,
                       d5=10,
                       d6=9,
                       d7=25,
                       cols=16,
                       lines=2)


def playTTSLCD():
    """Play the label"""
    lcd.clear()
    lcd.message(cWeather1)
    sleep(2.5)
    lcd.clear()
    lcd.message(cWeather2)
    sleep(2.5)
    lcd.clear()