Exemple #1
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 
Exemple #2
0
GPIO.setup(buzzerPin, GPIO.OUT)  # set buzzerPin to OUTPUT mode

#---------------------------------------------------------------------------------------------#

ledPin = 40  # define ledPin

GPIO.setup(ledPin, GPIO.OUT)  # set ledPin to OUTPUT mode

#----------------------------------------------------------------------------------------------#

trigPin = 38
echoPin = 32
MAX_DISTANCE = 220  # define the maximum measuring distance, unit: cm
timeOut = MAX_DISTANCE * 60  # calculate timeout according to the maximum measuring distance

GPIO.setup(trigPin, GPIO.OUT)  # set trigPin to OUTPUT mode
GPIO.setup(echoPin, GPIO.IN)  # set echoPin to INPUT mode

#----------------------------------------------------------------------------------------------#

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

if __name__ == '__main__':
    print('Program is starting ... ')
    try:
        loop()
    except KeyboardInterrupt:
        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()