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()
Beispiel #2
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)
Beispiel #3
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')
Beispiel #4
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()
Beispiel #5
0
def yellow(channel):
    global i
    i = 3
    GPIO.output(yellowLEDpin, GPIO.HIGH)
    sleep(.2)
    GPIO.output(yellowLEDpin, GPIO.LOW)
    print("yellow")
    
    



while play == 1:

    lcd.setCursor(0, 0)
    a = (random.randint(1, 4))
    output.append(a)
    print("Ready...")
    sleep(.7)
    cls()
    destroy()
    for val in output:  # shows each value in the list once, on its own screen
        if val == 1:
            GPIO.output(redLEDpin, GPIO.HIGH)
        elif val == 2:
            GPIO.output(greenLEDpin, GPIO.HIGH)
        elif val == 3:
            GPIO.output(yellowLEDpin, GPIO.HIGH)
        elif val == 4:
            GPIO.output(blueLEDpin, GPIO.HIGH)
Beispiel #6
0
    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

    while True:

        # Read PIR state
        current_pir_state = GPIO.input(pinpir)

        lcd.setCursor(0, 0)  # set cursor position
        if current_pir_state == 1:
            lcd.message('PIR = 1')
        else:
            lcd.message('PIR = 0')

        time.sleep(0.2)

except KeyboardInterrupt:
    print("...Stopped")

    # Reset GPIO settings
    lcd.clear()
    GPIO.cleanup()
Beispiel #7
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 
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()
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()