Пример #1
0
def lcd_setup():
	global lcd
	global lcd_t
	global terminate
	global mcp
	PCF8574_address = 0x27  # I2C address of the PCF8574 chip.
	PCF8574A_address = 0x3F  # I2C address of the PCF8574A chip.
	# Create PCF8574 GPIO adapter.
	try:
		mcp = PCF8574_GPIO(PCF8574_address)
	except:
		try:
			mcp = PCF8574_GPIO(PCF8574A_address)
		except:
			print ('I2C Address Error !')
		exit(1)
	# Create LCD, passing in MCP GPIO adapter.
	lcd = Adafruit_CharLCD(pin_rs=0, pin_e=2, pins_db=[4,5,6,7], GPIO=mcp)

	mcp.output(3,1)     # turn on LCD backlight
	lcd.begin(16,2)     # set number of LCD lines and columns

	terminate = False
	lcd_t = threading.Thread(target = lcd_thread)
	lcd_t.daemon = True
	lcd_t.start()
Пример #2
0
    def __init__(self, echo=False):
        """
        :param echo: Whether or not to echo writes to the logger.
        :type echo: bool
        """
        from PCF8574 import PCF8574_GPIO
        from Adafruit_LCD1602 import Adafruit_CharLCD

        self.echo = echo
        PCF8574_address = 0x27  # I2C address of the PCF8574 chip.
        PCF8574A_address = 0x3F  # I2C address of the PCF8574A chip.

        logging.info('looking for LCD on i2c bus')
        try:
            logging.info('trying address ' + str(PCF8574_address) + '.. ')
            self.mcp = PCF8574_GPIO(PCF8574_address)  # PCF8574 GPIO adapter
            logging.info('found PCF8574!')
        except:
            try:
                logging.info('trying addr %s.. ' % str(PCF8574A_address))
                self.mcp = PCF8574_GPIO(PCF8574A_address)
                logging.info('found PCF8574A!')
            except:
                logging.error('I2C error')

        # create LCD and pass in MCP GPIO adapter
        self.lcd = Adafruit_CharLCD(pin_rs=0,
                                    pin_e=2,
                                    pins_db=[4, 5, 6, 7],
                                    GPIO=self.mcp)

        self.mcp.output(3, 1)  # turn on LCD backlight
        self.lcd.begin(16, 2)  # set number of LCD lines and columns
        self.lcd.message('initializing...')
Пример #3
0
def destroy():
	PCF8574_address = 0x27  # I2C address of the PCF8574 chip.
	PCF8574A_address = 0x3F  # I2C address of the PCF8574A chip.
	# Create PCF8574 GPIO adapter.
	mcp = PCF8574_GPIO(PCF8574_address)
	# Create LCD, passing in MCP GPIO adapter.
	lcd = Adafruit_CharLCD(pin_rs=0, pin_e=2, pins_db=[4,5,6,7], GPIO=mcp)
	lcd.clear() #Clear the LCD when game is exited
Пример #4
0
 def __init__(self): # 
     try:
         self.mcp = PCF8574_GPIO(PCF8574_address)
     except:
         try:
             self.mcp = PCF8574_GPIO(PCF8574A_address)
         except:
             print ('I2C Address Error!')
             exit(1)
     self.lcd = Adafruit_CharLCD(pin_rs=0, pin_e=2,pins_db=[4,5,6,7], GPIO=self.mcp)
     self.mcp.output(3,1)
     self.lcd.begin(16,2)
     self.max_msg_len=0
     self.row1=None
     self.row2=None
     _thread.start_new_thread(self._scroll_looper,())
    def __init__(self, controller):
        self.PCF8574_address = 0x27  # I2C address of the PCF8574 chip.
        self.PCF8574A_address = 0x3F  # I2C address of the PCF8574A chip.
        self.mcp = None
        self.controller = controller
        self.run = True

        # Create PCF8574 GPIO adapter.
        try:
            self.mcp = PCF8574_GPIO(self.PCF8574_address)
        except:
            try:
                self.mcp = PCF8574_GPIO(self.PCF8574A_address)
            except:
                print('I2C Address Error !')
                exit(1)

        # Create LCD, passing in MCP GPIO adapter.
        self.lcd = Adafruit_CharLCD(pin_rs=0,
                                    pin_e=2,
                                    pins_db=[4, 5, 6, 7],
                                    GPIO=self.mcp)
Пример #6
0
def create_lcd(pin):

    # Setup Display
    PCF8574_address = 0x27
    PCF8574A_address = 0x3F

    # Create MCP
    try:
        mcp = PCF8574_GPIO(PCF8574_address)
    except Exception:
        try:
            mcp = PCF8574_GPIO(PCF8574A_address)
        except Exception as e:
            raise e
    lcd = Adafruit_CharLCD(pin_rs=0, pin_e=2, pins_db=[4,5,6,7], GPIO=mcp)

    # Turn on LCD
    mcp.output(pin,1)
    lcd.begin(16, 2)

    # Return LCD
    return lcd
Пример #7
0
def setup(detection_flag):
    PCF8574_address = 0x27
    PCF8574A_address = 0x3F

    try:
        mcp = PCF8574_GPIO(PCF8574_address)
    except:
        try:
            mcp = PCF8574_GPIO(PCF8574A_address)
        except:
            print('I2C Address Error!')
            exit(1)
    lcd = Adafruit_CharLCD(pin_rs=0, pin_e=2, pins_db=[4, 5, 6, 7], GPIO=mcp)
    loop(mcp, lcd, detection_flag)
Пример #8
0
 def run(self):
     PCF8574_address = 0x27  # I2C address of the PCF8574 chip.
     PCF8574A_address = 0x3F  # I2C address of the PCF8574A chip.
     try:
         try:
             mcp = PCF8574_GPIO(PCF8574_address)
         except:
             try:
                 mcp = PCF8574_GPIO(PCF8574A_address)
             except:
                 print('I2C Address Error for motion sensor!')
                 exit(1)
         self.setup()
         self.lcd = Adafruit_CharLCD(pin_rs=0,
                                     pin_e=2,
                                     pins_db=[4, 5, 6, 7],
                                     GPIO=mcp)
         mcp.output(3, 1)  # turn on LCD backlight
         self.lcd.begin(16, 2)  # set number of LCD lines and columns
         self.lcd.setCursor(0, 0)  # set cursor position
         self.loop()
     except KeyboardInterrupt:  # When 'Ctrl+C' is pressed, the child program destroy() will be  executed.
         self.destroy()
Пример #9
0
def init_LCD():
    global lcd
    global mcp
    PCF8574_address = 0x27  # I2C address of the PCF8574 chip.
    PCF8574A_address = 0x3F  # I2C address of the PCF8574A chip.
    # Create PCF8574 GPIO adapter.
    try:
        mcp = PCF8574_GPIO(PCF8574_address)
    except:
        try:
            mcp = PCF8574_GPIO(PCF8574A_address)
        except:
            print('I2C Address Error !')
            exit(1)
    # Create LCD, passing in MCP GPIO adapter.
    lcd = Adafruit_CharLCD(pin_rs=0, pin_e=2, pins_db=[4, 5, 6, 7], GPIO=mcp)
Пример #10
0
def setuplcd():
    global lcd
    PCF8574_address = 0x27  # I2C address of the PCF8574 chip.
    PCF8574A_address = 0x3F  # I2C address of the PCF8574A chip.
    # Create PCF8574 GPIO adapter.
    try:
        mcp = PCF8574_GPIO(PCF8574_address)
    except:
        try:
            mcp = PCF8574_GPIO(PCF8574A_address)
        except:
            print('I2C Address Error !')
            exit(1)
    # Create LCD, passing in MCP GPIO adapter.
    lcd = Adafruit_CharLCD(pin_rs=0, pin_e=2, pins_db=[4, 5, 6, 7], GPIO=mcp)

    mcp.output(3, 1)  # turn on LCD backlight
    lcd.begin(16, 2)  # set number of LCD lines and columns
    lcd.setCursor(0, 0)  # set cursor position
    print('setup end')
temp_alarm = float(2.0)

# variables to hold pir current and last states
current_pir_state = 0
previous_pir_state = 0

PCF8574A_address = 0x3F  # I2C address of the PCF8574A chip.
# Create PCF8574 GPIO adapter.
try:
    mcp = PCF8574_GPIO(PCF8574A_address)
except:
    print('I2C Address Error !')
    exit(1)

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

# Print out the temperture until the program is stopped with Ctrl-C

try:

    print("Waiting for PIR to settle ...")
    # Loop until PIR output is 0
    while GPIO.input(pinpir) == 1:
        current_pir_state = 0
    print("PIR is ready")

    setColor(100, 100, 100)
    time.sleep(1)
    setColor(0, 100, 0)
Пример #12
0
class LCD1602Display(BasicDisplay):
    """ implementation for displaying textual data on a display device

    Notes
    -----
    LCD wiring - RPi (physical)
     1 - GND - GND  (1)
     2 - VCC - 5V   (4)
     3 - SDA - SDA1 (3)
     4 - SCL - SCL1 (5)
    """
    def __init__(self, echo=False):
        """
        :param echo: Whether or not to echo writes to the logger.
        :type echo: bool
        """
        from PCF8574 import PCF8574_GPIO
        from Adafruit_LCD1602 import Adafruit_CharLCD

        self.echo = echo
        PCF8574_address = 0x27  # I2C address of the PCF8574 chip.
        PCF8574A_address = 0x3F  # I2C address of the PCF8574A chip.

        logging.info('looking for LCD on i2c bus')
        try:
            logging.info('trying address ' + str(PCF8574_address) + '.. ')
            self.mcp = PCF8574_GPIO(PCF8574_address)  # PCF8574 GPIO adapter
            logging.info('found PCF8574!')
        except:
            try:
                logging.info('trying addr %s.. ' % str(PCF8574A_address))
                self.mcp = PCF8574_GPIO(PCF8574A_address)
                logging.info('found PCF8574A!')
            except:
                logging.error('I2C error')

        # create LCD and pass in MCP GPIO adapter
        self.lcd = Adafruit_CharLCD(pin_rs=0,
                                    pin_e=2,
                                    pins_db=[4, 5, 6, 7],
                                    GPIO=self.mcp)

        self.mcp.output(3, 1)  # turn on LCD backlight
        self.lcd.begin(16, 2)  # set number of LCD lines and columns
        self.lcd.message('initializing...')

    def clear(self):
        """ Clear the display. """
        self.lcd.clear()

    def display(self, message, trace=None):
        """ Display a message.

        :param message: The message to display on the device.
        :type message: str
        :param trace: Ignored. LCD displays can't display graphical traces.
        :type trace: bool
        """
        self.lcd.clear()
        self.lcd.message(message)
        if (self.echo):
            logging.info(message)

    def destroy(self):
        """ Clean up the display. """
        self.mcp.output(3, 0)
        self.lcd.clear()
Пример #13
0
    need_clean = True

    PCF8574_address = 0x27  # I2C address of the PCF8574 chip.
    PCF8574A_address = 0x3F  # I2C address of the PCF8574A chip.
    # Create PCF8574 GPIO adapter.
    try:
        mcp = PCF8574_GPIO(PCF8574_address)
    except:
        try:
            mcp = PCF8574_GPIO(PCF8574A_address)
        except:
            print ('I2C Address Error !')
            exit(1)
    # Create LCD, passing in MCP GPIO adapter.
    lcd = Adafruit_CharLCD(pin_rs=0, pin_e=2, pins_db=[4,5,6,7], GPIO=mcp)

    #Running actual program
    print('Ready!')
    mcp.output(3,1)     # turn on LCD backlight
    lcd.begin(16,2)     # set number of LCD lines and columns
    thread.start_new_thread(send_msg, ("\nAlarm Activated\n\nType 'stop' to stop deactivate it",))
    off = 0
    #Run infinitely
  
    thread.start_new_thread(while_read,("",))

    while True:
        
        #Check for next state
        if GPIO.input(PIN) == next_state:
Пример #14
0
    lcd.clear()


PCF8574_address = 0x27  # I2C address of the PCF8574 chip.
PCF8574A_address = 0x3F  # I2C address of the PCF8574A chip.
# Create PCF8574 GPIO adapter.
try:
    mcp = PCF8574_GPIO(PCF8574_address)
except:
    try:
        mcp = PCF8574_GPIO(PCF8574A_address)
    except:
        print('I2C Address Error !')
        exit(1)
# Create LCD, passing in MCP GPIO adapter.
lcd = Adafruit_CharLCD(pin_rs=0, pin_e=2, pins_db=[4, 5, 6, 7], GPIO=mcp)


def cls(): print("\n" * 50)  # moves current text off of the screen


mcp.output(3, 1)  # turn on LCD backlight
lcd.begin(16, 2)


def red(channel):
    global i
    i = 1 
    GPIO.output(redLEDpin, GPIO.HIGH)
    sleep(.2)
    GPIO.output(redLEDpin, GPIO.LOW)
Пример #15
0
    GPIO.setup(
        Green, GPIO.OUT
    )  #Sets GPIO pin 38 to output, as 38 is stored in varable "Green"
    GPIO.output(Red, GPIO.LOW)  #Sets Red to Low power, or 0, for no LED
    GPIO.output(Green, GPIO.LOW)  #Sets Green to low power, or 0 for no LED


try:
    mcp = PCF8574_GPIO(PCF8574_address)
except:
    try:
        mcp = PCF8574_GPIO(PCF8574A_address)
    except:
        print('I2C Address Error !')
        exit(1)
lcd = Adafruit_CharLCD(pin_rs=0, pin_e=2, pins_db=[4, 5, 6, 7],
                       GPIO=mcp)  # Create LCD, passing in MCP GPIO adapter.

try:
    if __name__ == '__main__':
        print('Program is starting ... ')

        GPIO.setmode(GPIO.BOARD)

    PIN_TRIGGER = 7
    PIN_ECHO = 11

    GPIO.setup(PIN_TRIGGER, GPIO.OUT)
    GPIO.setup(PIN_ECHO, GPIO.IN)

    GPIO.output(PIN_TRIGGER, GPIO.LOW)
Пример #16
0
class Motor(Thread):
    def setup(self):
        #print ('Program is starting...')
        GPIO.setmode(GPIO.BOARD)  # Numbers GPIOs by physical location
        GPIO.setup(RelayPin, GPIO.OUT)  # Set ledPin's mode is output
        GPIO.setup(sensorPin, GPIO.IN)  # Set sensorPin's mode is input
        GPIO.output(RelayPin, True)

    def loop(self):
        global PrevS
        global CurrS
        global text
        global watertime

        for i in range(watertime):
            i += 1
            GPIO.output(RelayPin, False)

            detect = GPIO.input(sensorPin)
            if (detect == 1):
                CurrS = False
                if CurrS != PrevS:
                    PrevS = CurrS
                    print('Motion detected')
                    print('Relay close: Sprinkler Off')
                    self.lcd.clear()
                    self.lcd.message('Motion detected. \n' + 'Sprinkler Off.')
                    sleep(0.7)
                    self.lcd.clear()
                    print(text)
                    self.lcd.message(text)
                    GPIO.setup(RelayPin, GPIO.IN)
                    time.sleep(3)

            elif (detect == 0):
                CurrS = True
                if CurrS != PrevS:
                    PrevS = CurrS
                    print('No motion')
                    print('Relay open: Sprinkler On')
                    self.lcd.clear()
                    self.lcd.setCursor(0, 0)
                    self.lcd.message('No motion. \n' + 'Sprinkler On.')
                    sleep(1)
                    self.lcd.clear()
                    print(text)
                    self.lcd.message(text)
                    GPIO.setup(RelayPin, GPIO.OUT)
                    GPIO.output(RelayPin, GPIO.LOW)

            GPIO.setup(RelayPin, GPIO.OUT)
            sleep(1)
        GPIO.cleanup()

    def destroy(self):
        GPIO.cleanup()  # Release resource
        self.lcd.clear()

    def run(self):
        PCF8574_address = 0x27  # I2C address of the PCF8574 chip.
        PCF8574A_address = 0x3F  # I2C address of the PCF8574A chip.
        try:
            try:
                mcp = PCF8574_GPIO(PCF8574_address)
            except:
                try:
                    mcp = PCF8574_GPIO(PCF8574A_address)
                except:
                    print('I2C Address Error for motion sensor!')
                    exit(1)
            self.setup()
            self.lcd = Adafruit_CharLCD(pin_rs=0,
                                        pin_e=2,
                                        pins_db=[4, 5, 6, 7],
                                        GPIO=mcp)
            mcp.output(3, 1)  # turn on LCD backlight
            self.lcd.begin(16, 2)  # set number of LCD lines and columns
            self.lcd.setCursor(0, 0)  # set cursor position
            self.loop()
        except KeyboardInterrupt:  # When 'Ctrl+C' is pressed, the child program destroy() will be  executed.
            self.destroy()
Пример #17
0
	p_R.start(0)      # Initial duty Cycle = 0
	p_G.start(0)
	p_B.start(0)
# Create PCF8574 GPIO adapter.


try:
	mcp = PCF8574_GPIO(PCF8574_address)
except:
	try:
		mcp = PCF8574_GPIO(PCF8574A_address)
	except:
		print('I2C Address Error !')
		exit(1)
# Create LCD, passing in MCP GPIO adapter.
lcd = Adafruit_CharLCD(pin_rs=0, pin_e=2, pins_db=[4, 5, 6, 7], GPIO=mcp)

continue_reading = True


# Capture SIGINT for cleanup when the script is aborted
def destroy():
	p_R.stop()
	p_G.stop()
	p_B.stop()
	GPIO.output(buzzerPin, GPIO.LOW)
	GPIO.cleanup()


def end_read(signal, frame):
	global continue_reading
Пример #18
0

## setup display stuff (copied from example from freenove) #########
PCF8574_address = 0x27  # I2C address of the PCF8574 chip.
PCF8574A_address = 0x3F  # I2C address of the PCF8574A chip.
# Create PCF8574 GPIO adapter.
try:
    mcp = PCF8574_GPIO(PCF8574_address)
except:
    try:
        mcp = PCF8574_GPIO(PCF8574A_address)
    except:
        print('I2C Address Error !')
        exit(1)
# Create LCD, passing in MCP GPIO adapter.
lcd = Adafruit_CharLCD(pin_rs=0, pin_e=2, pins_db=[4, 5, 6, 7], GPIO=mcp)
mcp.output(3,
           1)  # turn on LCD backlight (set second param to 0 for no backlight)
lcd.begin(16, 2)  # set number of LCD lines and columns
lcd.clear()  # clear the display in case something was not removed before


def main():
    logger.info('Displaying humidity.')
    while True:
        time, humidity, temperature = get_data()

        # display measurements on display
        lcd.setCursor(
            0, 0
        )  # set cursor position. this needs to be here, otherwise the display keeps old output
Пример #19
0
GPIO.setup(pinpir, GPIO.IN)

# variables to hold pir current and last states
current_pir_state = 0
previous_pir_state = 0

PCF8574A_address = 0x27  # I2C address of the PCF8574A chip.
# Create PCF8574 GPIO adapter.
try:
    mcp = PCF8574_GPIO(PCF8574A_address)
except:
    print('I2C Address Error !')
    exit(1)

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

# Print out the temperture until the program is stopped with Ctrl-C

try:

    print("Waiting for PIR to settle ...")
    # Loop until PIR output is 0
    while GPIO.input(pinpir) == 1:
        current_pir_state = 0
    print("PIR is ready")

    time.sleep(1)

    mcp.output(3, 1)  # turn on LCD backlight
    lcd.begin(16, 2)  # set number of LCD lines and columns
Пример #20
0
def setduration():
    settings.gallonsneeded = (float(settings.eto[0]) * 165.333)
    settings.secondsneeded = (settings.gallonsneeded / 0.283)
    val = settings.secondsneeded
    print('Need ', val, 'seconds of irrigation at 1020 gallons per hour')


PCF8574_address = 0x27  # I2C address of the PCF8574 chip.

try:
    mcp = PCF8574_GPIO(PCF8574_address)
except:
    print('I2C Address Error !')
    exit(1)

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

#adding event detection for PIR sensor, if detected callback is called
GPIO.add_event_detect(7, GPIO.RISING, callback=PIR_test.loop)

if __name__ == '__main__':
    print('Program is starting ... ')
    try:
        final()
    except KeyboardInterrupt:
        lcd.clear()  # lcd off
        GPIO.output(relayPin, GPIO.LOW)  # relay off
        RPi.GPIO.cleanup()
        exit()
Пример #21
0
def game(play):
	while play == 1: #Will continue the game until play again is selected
		
		#########################SET UP LCD#############################
		PCF8574_address = 0x27  # I2C address of the PCF8574 chip.
		PCF8574A_address = 0x3F  # I2C address of the PCF8574A chip.
		
		# Create PCF8574 GPIO adapter.
		mcp = PCF8574_GPIO(PCF8574_address)
		
		# Create LCD, passing in MCP GPIO adapter.
		lcd = Adafruit_CharLCD(pin_rs=0, pin_e=2, pins_db=[4,5,6,7],
		GPIO=mcp)
		
		#turn on LCD backlight 
		mcp.output(3,1)
		lcd.begin(16,2) #set lcd lines and columns
		lcd.setCursor(0,0) #set cursor position
		
		lcd.message('Let\'s Play, \n Math Time!')
		
		for i in range(16):
			lcd.scrollDisplayRight()
			time.sleep(.1)
		for i in range(16):
			lcd.DisplayLeft()
			time.sleep(.1)
		################################################################	
		
		#Allow user to pick a category
		selection = 1.11
		while selection <0 or selection >3 or selection == 1.11:
		#print 'Select one: \n 1) Addition \n 2) Subtraction \n 3) Multiplication'
			lcd.clear()
			lcd.setCursor(0,0)
			lcd.message('1.Add 2.Subtract \n 3.Multiply :')
			selection = input("Which one do you want to play? Pick a number between 1-3:")
			lcd.message('{}'.format(selection))	
			time.sleep(1)
							
		#Allow the user to pick a difficulty 
		#print 'Select a difficulty: 1) EASY 2) MEDIUM 3) HARD'
		difficulty = 1.11
		while difficulty < 0 or difficulty > 3 or difficulty == 1.11:
			lcd.clear()
			lcd.setCursor(0,0)
			lcd.message('Difficulty:')
			difficulty = input("Difficulty Desired: ") 
			lcd.message('{}'.format(difficulty))
			time.sleep(1)
		#Allow the user to select the number of questions they wanna answer
		lcd.clear()
		lcd.setCursor(0,0)
		lcd.message('Questions \n Desired:')
		num_questions = input("How many questions do you want? :")
		lcd.message('{}'.format(num_questions))	
		time.sleep(1)
			
		#Select the range based on difficulty
		if difficulty  == 1:
			num_range = 10
		elif difficulty == 2:
			num_range = 15
		else: 
			num_range = 100


		counter = 0 #Counter of questions starts at 0
		right_tally = 0 #Questions answered correctly
		
		#-------------------ADDITION------------------------------------#
		
		if  selection == 1:

				while counter < num_questions:
					num1 = random.randint(0,num_range)
					num2 = random.randint(0,num_range)
					#print("%d + %d = ") %(num1,num2)
					lcd.clear()
					lcd.setCursor(0,0)
					lcd.message("{} + {} =".format(num1,num2))
					answer = num1 + num2
					user_answer = input("Your Answer:")
					lcd.message("{}".format(user_answer))
					if answer == user_answer:
						led = LED(23)
						led.on()
						time.sleep(1)
						led.off()
						right_tally= right_tally + 1
					else:
						led = LED(12)
						led.on()
						time.sleep(1)
						led.off()
						
					del led
					counter = counter + 1
						 
					

		#-------------------SUBTRACTION---------------------------------#		
		elif selection ==2:
				while counter < num_questions:
					num1 = random.randint(0,num_range)
					num2 = random.randint(0,num_range)
					#print("%d - %d = ") %(num1,num2)
					lcd.clear()
					lcd.setCursor(0,0)
					lcd.message("{} - {} =".format(num1,num2))
					answer = num1 - num2
					user_answer = input("Your Answer:")
					lcd.message("{}".format(user_answer))
					
					if answer == user_answer:
						led = LED(23)
						led.on()
						time.sleep(1)
						led.off()
						right_tally = right_tally + 1
						
					else:
						led = LED(12)
						led.on()
						time.sleep(1)
						led.off()
						
					del led
					counter = counter + 1
								
		#----------------------Multiplication------------------------------#	
		elif selection ==3:
			while counter < num_questions:
					num1 = random.randint(0,num_range)
					num2 = random.randint(0,num_range)
					#print("%d * %d = ") %(num1,num2)
					lcd.clear()
					lcd.setCursor(0,0)
					lcd.message("{} * {} =".format(num1,num2))
					answer = num1 * num2
					user_answer = input("Your Answer:")
					lcd.message("{}".format(user_answer))
					if answer == user_answer:
						led = LED(23)
						led.on()
						time.sleep(1)
						led.off()
						right_tally = right_tally + 1
					else:
						led = LED(12)
						led.on()
						time.sleep(1)
						led.off()
						
					del led
					counter = counter + 1
		
		#TELL THE USER  HOW THEY DID
		print("You answered %d/%d questions correctly\n") %(right_tally,num_questions)
		lcd.clear()
		lcd.setCursor(0,0)
		lcd.message("Result: {}/{}".format(right_tally,num_questions))
		time.sleep(3)
		#ASK THE USER IF THEY WANNA PLAY AGAIN
		#print 'Do you want to keep playing?. TYPE 1 for yes or anything else for no'
		lcd.clear()
		lcd.setCursor(0,0)
		lcd.message('Play Again? \n 1.YES 2.NO  :')
		play = input("Choice:")
		
		if play == 1:
			lcd.clear()
			lcd.setCursor(0,0)
			lcd.message('Playing \n Again!')
			time.sleep(1)
			#print "\nLet's play again"
		else:
			#print "\nGood game. Play again Next time!"
			lcd.clear()
			lcd.setCursor(0,0)
			lcd.message("Play Again \n Next Time!")
			time.sleep(1)
			destroy()
	return 
Пример #22
0
            lcd.clear
        time.sleep(5)
        
def destroy():
    lcd.clear()
    
    
PCF8574_address = 0x27
PCF8574A_address = 0x3F #I2C address of the chips

try:
    mcp = PCF8574_GPIO(PCF8574_address)
except:
    try:
        mcp = PCF8574_GPIO(PCF8574A_address)
    except:
        print('  I2C error')
        exit(1)
        
lcd = Adafruit_CharLCD(pin_rs=0, pin_e=2, pins_db=[4,5,6,7], GPIO=mcp)

        
if __name__ == '__main__':
    try:
        loop()
        
    except KeyboardInterrupt:
        destroy()
        GPIO.cleanup()
        exit()
Пример #23
0
class HT_sensor(Thread):
    def setup(self):

        # motion sensor & Relay
        GPIO.setmode(GPIO.BOARD)  # Numbers GPIOs by physical location
        GPIO.setup(RelayPin, GPIO.OUT)  # Set ledPin's mode is output
        GPIO.setup(sensorPin, GPIO.IN)  # Set sensorPin's mode is input

    def loop(self):

        global text
        global watertime

        global hourhum_val
        global hourtemp_val
        global cnt_hour
        global result_hum
        global result_temp
        global cnt_hum
        global cnt_temp

        #print(date+"(inside loop)")

        dht = DHT.DHT(DHTPin)  #create a DHT class object
        sumCnt = 0  #number of reading times

        hourhum_val = hourtemp_val = cnt_hour = 0
        cimis_tmp = None

        for cnt_hour in range(60):
            if (cimis_tmp == None):
                try:
                    global data
                    data = requests.get(self.url).json()
                except HTTPError as http_err:
                    print("HTTP error occurred:", http_err)
                except Exception as err:
                    print("Other error occurred:", err)
                else:
                    cimis_tmp = data['Data']['Providers'][0]['Records'][
                        self.now.hour - 2]['HlyAirTmp']['Value']
                    print("cimis success")

            for i in range(60):
                sumCnt += 1  #counting number of reading times
                chk = dht.readDHT11(
                )  #read DHT11 and get a return value. Then determine whether data read is normal according to the return value.
                print("The sumCnt is : %d, \t chk    : %d" % (sumCnt, chk))
                if (
                        chk is dht.DHTLIB_OK
                ):  #read DHT11 and get a return value. Then determine whether data read is normal according to the return value.
                    print("DHT11,OK!")
                    result_hum += dht.humidity
                    result_temp += dht.temperature * 1.8 + 32  #dht.temp in Celsius
                    cnt_hum += 1
                    cnt_temp += 1
                elif (chk is
                      dht.DHTLIB_ERROR_CHECKSUM):  #data check has errors
                    print("DHTLIB_ERROR_CHECKSUM!!")
                elif (chk is dht.DHTLIB_ERROR_TIMEOUT):  #reading DHT times out
                    print("DHTLIB_ERROR_TIMEOUT!")
                else:  #other errors
                    print("Other error!")

                print("Humidity : %.2f, \t Temperature : %.2f \n" %
                      (dht.humidity,
                       dht.temperature * 1.8 + 32))  # dht.temp in Celsius

                sleep(1)
                self.lcd.DisplayLeft()

                i += 1

            print("%.2f " % (result_temp / cnt_temp))
            print("%.2f " % (result_hum / cnt_hum))
            self.lcd.setCursor(0, 0)
            self.lcd.message("%.2f " % (result_temp / cnt_temp))
            self.lcd.setCursor(0, 1)
            self.lcd.message("%.2f " % (result_hum / cnt_hum))

            hourtemp_val += result_temp / cnt_temp
            hourhum_val += result_hum / cnt_hum
            cnt_hour += 1

    def destroy(self):
        self.lcd.clear()
        GPIO.cleanup()

    def run(self):

        PCF8574_address = 0x27  # I2C address of the PCF8574 chip.
        PCF8574A_address = 0x3F  # I2C address of the PCF8574A chip.

        global result_hum
        global result_temp
        global cnt_hum
        global cnt_temp
        global cnt_hour
        global hourtemp_val
        global hourhum_val
        global data

        # Create PCF8574 GPIO adapter.
        try:
            # self.lcd
            try:
                mcp = PCF8574_GPIO(PCF8574_address)
            except:
                try:
                    mcp = PCF8574_GPIO(PCF8574A_address)
                except:
                    print('I2C Address Error for HT_sensor!')
                    exit(1)

            # Create self.lcd, passing in MCP GPIO adapter.
            self.lcd = Adafruit_CharLCD(pin_rs=0,
                                        pin_e=2,
                                        pins_db=[4, 5, 6, 7],
                                        GPIO=mcp)
            mcp.output(3, 1)  # turn on LCD backlight
            self.lcd.begin(16, 2)  # set number of LCD lines and columns
            self.lcd.setCursor(0, 0)  # set cursor position
            self.lcd.clear()
            self.lcd.message(
                "Weather Station\n")  #display  main title of progra
            self.lcd.message("sampling data..\n")

            self.setup()

            header = "Date\t\tHour\tLocalHum\tLocalTmp\tLocalEto\tCIMISHum\tCIMISTmp\tCIMISEto\n"
            if not open("file.txt").readlines():
                print("empty file, write header")
                open("file.txt", "w").write(header)
            else:
                print("file not empty")
                print(open("file.txt").readlines())

            while (True):

                self.now = datetime.now()
                if self.now.hour == 0 or self.now.hour == 1 or self.now.hour == 2:
                    self.now_list = [
                        str(self.now.year),
                        str(self.now.month),
                        str(self.now.day - 1)
                    ]
                    hour = self.now.hour + 22
                else:
                    self.now_list = [
                        str(self.now.year),
                        str(self.now.month),
                        str(self.now.day)
                    ]
                    hour = self.now.hour - 2
                #self.now_list = [str(self.now.year), str(self.now.month), str(self.now.day)]
                date = self.now_list[0] + "-" + self.now_list[
                    1] + "-" + self.now_list[2]
                print(date)
                print(hour)
                self.url = "http://et.water.ca.gov/api/data?appKey=55a1b0c5-298b-4fd5-9c42-2576c839580d&targets=75&startDate=" + date + "&endDate=" + date + "&unitOfMeasure=E&dataItems=hly-eto,hly-air-tmp,hly-rel-hum"

                self.loop()

                print("Humidity : %.2f, \t Temperature : %.2f \n" %
                      (result_hum / cnt_hum, result_temp / cnt_temp))

                #        self.now = datetime.now()
                #        if self.now.hour == 0 or self.now.hour == 1 or self.now.hour == 2:
                #            self.now_list = [str(self.now.year), str(self.now.month), str(self.now.day-1)]
                #            hour = self.now.hour+22
                #        else:
                #            self.now_list = [str(self.now.year), str(self.now.month), str(self.now.day)]
                #            hour = self.now.hour-2
                #
                #        #self.now_list = [str(self.now.year), str(self.now.month), str(self.now.day)]
                #        date = self.now_list[0]+"-"+self.now_list[1]+"-"+self.now_list[2]
                #        print(date)
                #        print(hour)
                #
                #
                #        #self.url = "http://et.water.ca.gov/api/data?appKey=55a1b0c5-298b-4fd5-9c42-2576c839580d&targets=75&startDate="+self.now.strftime("%Y-%m-%d")+"&endDate="+self.now.strftime("%Y-%m-%d")+"&unitOfMeasure=M&dataItems=hly-eto,hly-air-tmp,hly-rel-hum"
                #        #self.url = "http://et.water.ca.gov/api/data?appKey=55a1b0c5-298b-4fd5-9c42-2576c839580d&targets=75&startDate=2019-6-12&endDate=2019-6-12&unitOfMeasure=M&dataItems=hly-eto,hly-air-tmp,hly-rel-hum"
                #        self.url = "http://et.water.ca.gov/api/data?appKey=55a1b0c5-298b-4fd5-9c42-2576c839580d&targets=75&startDate="+date+"&endDate="+date+"&unitOfMeasure=E&dataItems=hly-eto,hly-air-tmp,hly-rel-hum"

                #        data=requests.get(self.url).json()
                for index in range(
                        0, len(data['Data']['Providers'][0]['Records'])):
                    if index == hour:
                        #print(index)
                        cimis_hour = data['Data']['Providers'][0]['Records'][
                            index]['Hour']
                        print('Hour= ', cimis_hour)
                        cimis_eto = float(
                            data['Data']['Providers'][0]['Records'][index]
                            ['HlyEto']['Value'])
                        cimis_hum = float(
                            data['Data']['Providers'][0]['Records'][index]
                            ['HlyRelHum']['Value'])
                        cimis_tmp = float(
                            data['Data']['Providers'][0]['Records'][index]
                            ['HlyAirTmp']['Value'])
                        #print('Hour= ', cimis_hour)
                        print('Eto = ', cimis_eto)
                        print('RelHum= ', cimis_hum)
                        print('AirTemp= ', cimis_tmp)
        #


#                cimis_tmp = 78
#                cimis_hum = 63
#                cimis_eto = 0.01
                local_hum = hourhum_val / 60
                local_tmp = hourtemp_val / 60
                local_eto = cimis_eto * (local_tmp / cimis_tmp) * (cimis_hum /
                                                                   local_hum)
                print("%.2f" % (local_eto))
                waters = (local_eto * 1.0 * 200 * 0.62) / 0.75
                watertime = waters / 1020 * 60 * 60
                #                waterdiff = waters/((cimis_eto*1.0*200*0.62)/0.75)    # we cannot calculate the waterdiff when cimis_eto is 0

                #                watertime = 30 # for test

                text = 'Local: Hum:' + "%.2f " % (
                    local_hum
                ) + 'Temp:' + "%.2f " % (local_tmp) + 'Eto:' + "%.2f " % (
                    local_eto) + 'wa:' + "%.2f" % (
                        waters) + '\n' + 'CIMIS: Hum:' + "%.2f " % (
                            cimis_hum) + 'Temp:' + "%.2f " % (
                                cimis_tmp) + 'Eto:' + "%.2f " % (
                                    cimis_eto) + "%.2f" % (waterdiff) + '\n'
                self.lcd.setCursor(6, 0)
                self.lcd.message('L: H:' + "%.2f " % (local_hum) + 'T:' +
                                 "%.2f " % (local_tmp) + 'Eto:' + "%.2f " %
                                 (local_eto) + 'wa:' + "%.2f" % (waters))
                self.lcd.setCursor(6, 1)
                self.lcd.message('C: H:' + "%.2f " % (cimis_hum) + 'T:' +
                                 "%.2f " % (cimis_tmp) + 'Eto:' + "%.2f " %
                                 (cimis_eto) + 'wd:' + "%.2f" % (waterdiff))
                #output = date+'\t'+self.now.hour+':00\t'+local_hum+'\t'+local_tmp+'\t'+repr(local_eto)+'\t'+cimis_hum+'\t'+cimis_tmp+'\t'+cimis_eto+'\n'
                output = "{}\t{}\t{}\t\t{}\t\t{}\t\t{}\t\t{}\t\t{}\n".format(
                    date, cimis_hour, "%.2f" % (local_hum),
                    "%.2f" % (local_tmp), "%.2f" % (local_eto), cimis_hum,
                    cimis_tmp, cimis_eto)

                print(output)
                open("file.txt", "a").write(output)

                result_hum = result_temp = cnt_hum = cnt_temp = 0

        except KeyboardInterrupt:
            self.destroy()
            exit()
Пример #24
0
import random
import math
from PCF8574 import PCF8574_GPIO
from Adafruit_LCD1602 import Adafruit_CharLCD
from time import sleep, strftime
from datetime import datetime

#Select default play to 1 (YES)
play = 1
PCF8574_address = 0x27  # I2C address of the PCF8574 chip.
PCF8574A_address = 0x3F  # I2C address of the PCF8574A chip.
# Create PCF8574 GPIO adapter.
mcp = PCF8574_GPIO(PCF8574_address)

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

while play == 1:
    #Create LCD
    lcd = Adafruit_CharLCD(pin_rs=0, pin_e=2, pins_db=[4, 5, 6, 7], GPIO=mcp)
    #turn on LCD backlight
    mcp.output(3, 1)
    lcd.begin(16, 2)  #set lcd lines and columns
    lcd.setCursor(0, 0)  #set cursor position

    lcd.message('Let\'s play!')
    for i in range(16):
        lcd.scrollDisplayRight()
        time.sleep(.1)
    for i in range(16):
        lcd.DisplayLeft()
Пример #25
0
def main():
    global emptySpaces
    PCF8574_address = 0x27  # I2C address of the PCF8574 chip.
    PCF8574A_address = 0x3F  # I2C address of the PCF8574A chip.
    # Create PCF adapter
    try:
        mcp = PCF8574_GPIO(PCF8574_address)
    except:
        try:
            mcp = PCF8574_GPIO(PCF8574A_address)
        except:
            print('I2C Address Error !')
            exit(1)
            # Create LCD, passing in MCP GPIO adapter.
    lcd = Adafruit_CharLCD(pin_rs=0, pin_e=2, pins_db=[4, 5, 6, 7], GPIO=mcp)
    mcp.output(3, 1)  # LCD hattervilagitas
    lcd.clear()
    lcd.begin(16, 2)  # Sorok oszlopok beallitasa
    lcd.setCursor(0, 0)
    lcd.message('Szabad helyek:\n')
    lcd.message(str(emptySpaces))
    mydb = mysql.connector.connect(host="localhost",
                                   user="******",
                                   passwd="benc1e",
                                   database="db")
    mydb2 = mysql.connector.connect(host="localhost",
                                    user="******",
                                    passwd="benc1e",
                                    database="db2")
    cursor1 = mydb.cursor()
    cursor2 = mydb2.cursor()
    sql_addcard_db = "INSERT INTO parking (cardnumber) VALUES (%s)"
    sql_addcard_db2 = "INSERT INTO parked (cardnumber) VALUES (%s)"
    sql_deletecard_db2 = "DELETE FROM parked WHERE cardnumber = %s"
    sql_select_db = "SELECT cardnumber FROM parking WHERE cardnumber = %s"
    sql_select_db2 = "SELECT cardnumber FROM parked WHERE cardnumber = %s"
    cursor2.execute("DELETE FROM parked")
    mydb2.commit()
    global totalSpaces
    counter = 0
    initTwitter()  #twitter inicializacio
    try:
        while True:
            lcd.clear()
            lcd.setCursor(0, 0)
            lcd.message('Szabad helyek:\n')
            time.sleep(1)
            lcd.message(str(emptySpaces))
            counter = counter + 1
            if (counter > 10):
                counter = 0
                tweetString("Jelenleg a szabad helyek szama: " +
                            str(emptySpaces))
            print("Elindult a while true")
            print(str(emptySpaces))
            uidd = getUID()
            val = (str(uidd[0]) + "," + str(uidd[1]) + "," + str(uidd[2]) +
                   "," + str(uidd[3]) + "," + str(uidd[4]))
            cursor2.execute(sql_select_db2, (val, ))
            if cursor2.fetchone():
                blinkLed(gLedPin)
                lcd.clear()
                lcd.setCursor(0, 0)
                lcd.message('Viszontlatasra')
                print("Viszontlatasra")
                if (
                        emptySpaces != totalSpaces
                ):  #biztositjuk hogy a szabad helyek erteke a vart hatarakon belul maradjon
                    emptySpaces += 1
                cursor2.execute(sql_deletecard_db2, (val, ))
                mydb2.commit()
                time.sleep(sleepInterval)
            else:
                cursor1.execute(sql_select_db, (val, ))
                if (cursor1.fetchone() is not None) & (
                        emptySpaces > 0
                ):  #ha az uid az adatbazisban van ES van meg ures hely
                    lcd.clear()
                    lcd.setCursor(0, 0)
                    lcd.message('Belepes\n')
                    lcd.message('engedelyezve')
                    print("Belepes engedelyezve!")
                    if (
                            emptySpaces != 0
                    ):  #biztositjuk hogy a szabad helyek erteke a vart hatarakon belul maradjon
                        emptySpaces -= 1
                    GPIO.output(gLedPin, GPIO.HIGH)
                    #GPIO.output(gatePin, GPIO.HIGH) #aktivaljuk a gate pin-t
                    cursor2.execute(sql_addcard_db2, (val, ))
                    mydb2.commit()
                    while (not isThereACar()):
                        lcd.clear()
                        lcd.setCursor(0, 0)
                        lcd.message('Belepes\n')
                        lcd.message('engedelyezve.')
                        time.sleep(0.2)
                        lcd.clear()
                        lcd.setCursor(0, 0)
                        lcd.message('Belepes\n')
                        lcd.message('engedelyezve..')
                        time.sleep(0.2)
                        lcd.clear()
                        lcd.setCursor(0, 0)
                        lcd.message('Belepes\n')
                        lcd.message('engedelyezve...')
                        time.sleep(0.2)
                        print("")
                    lcd.clear()
                    lcd.setCursor(0, 0)
                    lcd.message('Auto\n')
                    lcd.message('megerkezett')
                    print("Auto megerkezett")
                    time.sleep(sleepInterval)
                    GPIO.output(gLedPin, GPIO.LOW)
                    print("Lecsukjuk a kaput")
                    #GPIO.output(gatePin, GPIO.LOW)
                else:
                    if emptySpaces == 0:
                        lcd.clear()
                        lcd.setCursor(0, 0)
                        lcd.message('Nincs hely')
                        print("Nincs szabad hely!")
                        blinkLed(rLedPin)
                    else:
                        lcd.clear()
                        lcd.setCursor(0, 0)
                        lcd.message('Nincs az\n')
                        lcd.message('adatbazisban')
                        print("Nem szerepel ez a kartya az adatbazisban!")
                        blinkLed(rLedPin)
                    time.sleep(1)
    except KeyboardInterrupt:  #biztonsagi megfontolasbol mindent leallitunk
        GPIO.output(gLedPin, GPIO.LOW)
        GPIO.output(rLedPin, GPIO.LOW)
        GPIO.cleanup()
        cursor2.execute("DELETE FROM parked")
        mydb2.commit()
        cursor1.close()
        cursor2.close()
        mydb.close()
        mydb2.close()
        lcd.clear()
class LCDDisplay():
    def __init__(self, controller):
        self.PCF8574_address = 0x27  # I2C address of the PCF8574 chip.
        self.PCF8574A_address = 0x3F  # I2C address of the PCF8574A chip.
        self.mcp = None
        self.controller = controller
        self.run = True

        # Create PCF8574 GPIO adapter.
        try:
            self.mcp = PCF8574_GPIO(self.PCF8574_address)
        except:
            try:
                self.mcp = PCF8574_GPIO(self.PCF8574A_address)
            except:
                print('I2C Address Error !')
                exit(1)

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

    def get_time_now(self):  # get system time
        return datetime.now().strftime(' %H:%M:%S')

    def loop(self):
        self.mcp.output(3, 1)  # turn on LCD backlight
        self.lcd.begin(16, 2)  # set number of LCD lines and columns

        while (self.run):

            self.lcd.setCursor(0, 0)  # set cursor position
            self.lcd.message(self.get_time_now())  # display the time
            self.lcd.setCursor(0, 1)  # set cursor position
            self.lcd.message(self.controller.get_finger_status())

            sleep(0.2)

        if self.run == True:
            self.lcd.clear()

    def destroy(self):
        self.run = False
        self.lcd.clear()
Пример #27
0
from gpiozero import LED, Button
from time import sleep
import os
from subprocess import check_output
from mpd import MPDClient
import re
from PCF8574 import PCF8574_GPIO
from Adafruit_LCD1602 import Adafruit_CharLCD

volume = 0
current = "None"
client = MPDClient()
mpc = PCF8574_GPIO(0x27)
lcd = Adafruit_CharLCD(pin_rs=0, pin_e=2, pins_db=[4, 5, 6, 7], GPIO=mpc)
status = "None"


def toggle():
    os.popen("mpc toggle")
    getPlayPause()
    printToScreen()


def volumeUp():
    lcd.clear()
    global volume
    v = int(volume)
    x = v % 10
    if x > 0: v += 10 - x
    else: v += 10
    if v <= 100:
Пример #28
0
    def run(self):

        PCF8574_address = 0x27  # I2C address of the PCF8574 chip.
        PCF8574A_address = 0x3F  # I2C address of the PCF8574A chip.

        global result_hum
        global result_temp
        global cnt_hum
        global cnt_temp
        global cnt_hour
        global hourtemp_val
        global hourhum_val
        global data

        # Create PCF8574 GPIO adapter.
        try:
            # self.lcd
            try:
                mcp = PCF8574_GPIO(PCF8574_address)
            except:
                try:
                    mcp = PCF8574_GPIO(PCF8574A_address)
                except:
                    print('I2C Address Error for HT_sensor!')
                    exit(1)

            # Create self.lcd, passing in MCP GPIO adapter.
            self.lcd = Adafruit_CharLCD(pin_rs=0,
                                        pin_e=2,
                                        pins_db=[4, 5, 6, 7],
                                        GPIO=mcp)
            mcp.output(3, 1)  # turn on LCD backlight
            self.lcd.begin(16, 2)  # set number of LCD lines and columns
            self.lcd.setCursor(0, 0)  # set cursor position
            self.lcd.clear()
            self.lcd.message(
                "Weather Station\n")  #display  main title of progra
            self.lcd.message("sampling data..\n")

            self.setup()

            header = "Date\t\tHour\tLocalHum\tLocalTmp\tLocalEto\tCIMISHum\tCIMISTmp\tCIMISEto\n"
            if not open("file.txt").readlines():
                print("empty file, write header")
                open("file.txt", "w").write(header)
            else:
                print("file not empty")
                print(open("file.txt").readlines())

            while (True):

                self.now = datetime.now()
                if self.now.hour == 0 or self.now.hour == 1 or self.now.hour == 2:
                    self.now_list = [
                        str(self.now.year),
                        str(self.now.month),
                        str(self.now.day - 1)
                    ]
                    hour = self.now.hour + 22
                else:
                    self.now_list = [
                        str(self.now.year),
                        str(self.now.month),
                        str(self.now.day)
                    ]
                    hour = self.now.hour - 2
                #self.now_list = [str(self.now.year), str(self.now.month), str(self.now.day)]
                date = self.now_list[0] + "-" + self.now_list[
                    1] + "-" + self.now_list[2]
                print(date)
                print(hour)
                self.url = "http://et.water.ca.gov/api/data?appKey=55a1b0c5-298b-4fd5-9c42-2576c839580d&targets=75&startDate=" + date + "&endDate=" + date + "&unitOfMeasure=E&dataItems=hly-eto,hly-air-tmp,hly-rel-hum"

                self.loop()

                print("Humidity : %.2f, \t Temperature : %.2f \n" %
                      (result_hum / cnt_hum, result_temp / cnt_temp))

                #        self.now = datetime.now()
                #        if self.now.hour == 0 or self.now.hour == 1 or self.now.hour == 2:
                #            self.now_list = [str(self.now.year), str(self.now.month), str(self.now.day-1)]
                #            hour = self.now.hour+22
                #        else:
                #            self.now_list = [str(self.now.year), str(self.now.month), str(self.now.day)]
                #            hour = self.now.hour-2
                #
                #        #self.now_list = [str(self.now.year), str(self.now.month), str(self.now.day)]
                #        date = self.now_list[0]+"-"+self.now_list[1]+"-"+self.now_list[2]
                #        print(date)
                #        print(hour)
                #
                #
                #        #self.url = "http://et.water.ca.gov/api/data?appKey=55a1b0c5-298b-4fd5-9c42-2576c839580d&targets=75&startDate="+self.now.strftime("%Y-%m-%d")+"&endDate="+self.now.strftime("%Y-%m-%d")+"&unitOfMeasure=M&dataItems=hly-eto,hly-air-tmp,hly-rel-hum"
                #        #self.url = "http://et.water.ca.gov/api/data?appKey=55a1b0c5-298b-4fd5-9c42-2576c839580d&targets=75&startDate=2019-6-12&endDate=2019-6-12&unitOfMeasure=M&dataItems=hly-eto,hly-air-tmp,hly-rel-hum"
                #        self.url = "http://et.water.ca.gov/api/data?appKey=55a1b0c5-298b-4fd5-9c42-2576c839580d&targets=75&startDate="+date+"&endDate="+date+"&unitOfMeasure=E&dataItems=hly-eto,hly-air-tmp,hly-rel-hum"

                #        data=requests.get(self.url).json()
                for index in range(
                        0, len(data['Data']['Providers'][0]['Records'])):
                    if index == hour:
                        #print(index)
                        cimis_hour = data['Data']['Providers'][0]['Records'][
                            index]['Hour']
                        print('Hour= ', cimis_hour)
                        cimis_eto = float(
                            data['Data']['Providers'][0]['Records'][index]
                            ['HlyEto']['Value'])
                        cimis_hum = float(
                            data['Data']['Providers'][0]['Records'][index]
                            ['HlyRelHum']['Value'])
                        cimis_tmp = float(
                            data['Data']['Providers'][0]['Records'][index]
                            ['HlyAirTmp']['Value'])
                        #print('Hour= ', cimis_hour)
                        print('Eto = ', cimis_eto)
                        print('RelHum= ', cimis_hum)
                        print('AirTemp= ', cimis_tmp)
        #


#                cimis_tmp = 78
#                cimis_hum = 63
#                cimis_eto = 0.01
                local_hum = hourhum_val / 60
                local_tmp = hourtemp_val / 60
                local_eto = cimis_eto * (local_tmp / cimis_tmp) * (cimis_hum /
                                                                   local_hum)
                print("%.2f" % (local_eto))
                waters = (local_eto * 1.0 * 200 * 0.62) / 0.75
                watertime = waters / 1020 * 60 * 60
                #                waterdiff = waters/((cimis_eto*1.0*200*0.62)/0.75)    # we cannot calculate the waterdiff when cimis_eto is 0

                #                watertime = 30 # for test

                text = 'Local: Hum:' + "%.2f " % (
                    local_hum
                ) + 'Temp:' + "%.2f " % (local_tmp) + 'Eto:' + "%.2f " % (
                    local_eto) + 'wa:' + "%.2f" % (
                        waters) + '\n' + 'CIMIS: Hum:' + "%.2f " % (
                            cimis_hum) + 'Temp:' + "%.2f " % (
                                cimis_tmp) + 'Eto:' + "%.2f " % (
                                    cimis_eto) + "%.2f" % (waterdiff) + '\n'
                self.lcd.setCursor(6, 0)
                self.lcd.message('L: H:' + "%.2f " % (local_hum) + 'T:' +
                                 "%.2f " % (local_tmp) + 'Eto:' + "%.2f " %
                                 (local_eto) + 'wa:' + "%.2f" % (waters))
                self.lcd.setCursor(6, 1)
                self.lcd.message('C: H:' + "%.2f " % (cimis_hum) + 'T:' +
                                 "%.2f " % (cimis_tmp) + 'Eto:' + "%.2f " %
                                 (cimis_eto) + 'wd:' + "%.2f" % (waterdiff))
                #output = date+'\t'+self.now.hour+':00\t'+local_hum+'\t'+local_tmp+'\t'+repr(local_eto)+'\t'+cimis_hum+'\t'+cimis_tmp+'\t'+cimis_eto+'\n'
                output = "{}\t{}\t{}\t\t{}\t\t{}\t\t{}\t\t{}\t\t{}\n".format(
                    date, cimis_hour, "%.2f" % (local_hum),
                    "%.2f" % (local_tmp), "%.2f" % (local_eto), cimis_hum,
                    cimis_tmp, cimis_eto)

                print(output)
                open("file.txt", "a").write(output)

                result_hum = result_temp = cnt_hum = cnt_temp = 0

        except KeyboardInterrupt:
            self.destroy()
            exit()
Пример #29
0
    lcd.clear()


PCF8574_address = 0x27  # I2C address of the PCF8574 chip.
PCF8574A_address = 0x3F  # I2C address of the PCF8574A chip.
# Create PCF8574 GPIO adapter.
try:
    mcp = PCF8574_GPIO(PCF8574_address)
except:
    try:
        mcp = PCF8574_GPIO(PCF8574A_address)
    except:
        print('I2C Address Error !')
        exit(1)
# Create LCD, passing in MCP GPIO adapter.
lcd = Adafruit_CharLCD(pin_rs=0, pin_e=2, pins_db=[4, 5, 6, 7], GPIO=mcp)
mcp.output(3, 1)  # turn on LCD backlight
lcd.begin(16, 2)  # set number of LCD lines and columns

if __name__ == '__main__':
    print('Program is starting ... ')
    try:
        loop()
    except KeyboardInterrupt:
        destroy()


def display_lcd_line1(message):
    lcd.setCursor(0, 0)  # set cursor position
    lcd.message(message)  # display CPU temperature
Пример #30
0
class LCD(object):
    MAX_FIXED_MSG_LEN=16
    def __init__(self): # 
        try:
            self.mcp = PCF8574_GPIO(PCF8574_address)
        except:
            try:
                self.mcp = PCF8574_GPIO(PCF8574A_address)
            except:
                print ('I2C Address Error!')
                exit(1)
        self.lcd = Adafruit_CharLCD(pin_rs=0, pin_e=2,pins_db=[4,5,6,7], GPIO=self.mcp)
        self.mcp.output(3,1)
        self.lcd.begin(16,2)
        self.max_msg_len=0
        self.row1=None
        self.row2=None
        _thread.start_new_thread(self._scroll_looper,())

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

    def _scroll_looper(self,*argc):
        while True:
            if(self.max_msg_len>self.MAX_FIXED_MSG_LEN):self.lcd.DisplayLeft()
            sleep(0.5)

    def display_row1(self,msg='Default message'):
        # self.lcd.clear()
        self.lcd.setCursor(0,0)
        self.row1=msg
        self.lcd.message(msg)
        self.max_msg_len=max(len(msg),self.max_msg_len)

    def display_row2(self,msg='Default scrolling message'): # display scrolling message on the specific line
        # self.lcd.clear()
        self.lcd.setCursor(0,1)
        self.row2=msg
        self.lcd.message(msg)
        self.max_msg_len=max(len(msg),self.max_msg_len)
    
    def update_row1(self,msg='Default message'):
        if msg!=self.row1:self.display_row1(msg)
    def update_row2(self,msg='Default scrolling message'):
        if msg!=self.row2:self.display_row2(msg)