diff --git a/Code/Python_Code/00.0.0_Hello/Hello.py b/Code/Python_Code/00.0.0_Hello/Hello.py index 4640415..6421cee 100644 --- a/Code/Python_Code/00.0.0_Hello/Hello.py +++ b/Code/Python_Code/00.0.0_Hello/Hello.py @@ -7,6 +7,6 @@ ######################################################################## def Hello(): - print('Hello World!') + print('Hello World!') Hello() diff --git a/Code/Python_Code/01.1.1_Blink/Blink.py b/Code/Python_Code/01.1.1_Blink/Blink.py index 18555f1..1a10acf 100644 --- a/Code/Python_Code/01.1.1_Blink/Blink.py +++ b/Code/Python_Code/01.1.1_Blink/Blink.py @@ -11,28 +11,28 @@ import time ledPin = 11 # define ledPin def setup(): - GPIO.setmode(GPIO.BOARD) # use PHYSICAL GPIO Numbering - GPIO.setup(ledPin, GPIO.OUT) # set the ledPin to OUTPUT mode - GPIO.output(ledPin, GPIO.LOW) # make ledPin output LOW level - print ('using pin%d'%ledPin) + GPIO.setmode(GPIO.BOARD) # use PHYSICAL GPIO Numbering + GPIO.setup(ledPin, GPIO.OUT) # set the ledPin to OUTPUT mode + GPIO.output(ledPin, GPIO.LOW) # make ledPin output LOW level + print ('using pin%d'%ledPin) def loop(): - while True: - GPIO.output(ledPin, GPIO.HIGH) # make ledPin output HIGH level to turn on led - print ('led turned on >>>') # print information on terminal - time.sleep(1) # Wait for 1 second - GPIO.output(ledPin, GPIO.LOW) # make ledPin output LOW level to turn off led - print ('led turned off <<<') - time.sleep(1) # Wait for 1 second + while True: + GPIO.output(ledPin, GPIO.HIGH) # make ledPin output HIGH level to turn on led + print ('led turned on >>>') # print information on terminal + time.sleep(1) # Wait for 1 second + GPIO.output(ledPin, GPIO.LOW) # make ledPin output LOW level to turn off led + print ('led turned off <<<') + time.sleep(1) # Wait for 1 second def destroy(): - GPIO.cleanup() # Release all GPIO + GPIO.cleanup() # Release all GPIO if __name__ == '__main__': # Program entrance - print ('Program is starting ... \n') - setup() - try: - loop() - except KeyboardInterrupt: # Press ctrl-c to end the program. - destroy() + print ('Program is starting ... \n') + setup() + try: + loop() + except KeyboardInterrupt: # Press ctrl-c to end the program. + destroy() diff --git a/Code/Python_Code/01.1.1_Blink/Blink2.py b/Code/Python_Code/01.1.1_Blink/Blink2.py index 1718512..3d8a0de 100644 --- a/Code/Python_Code/01.1.1_Blink/Blink2.py +++ b/Code/Python_Code/01.1.1_Blink/Blink2.py @@ -23,7 +23,7 @@ led = LED("J8:11") # BOARD while True: led.on() # turn on LED - print ('led turned on >>>') # print message on terminal + print ('led turned on >>>') # print message on terminal sleep(1) # wait 1 second led.off() # turn off LED print ('led turned off <<<') diff --git a/Code/Python_Code/02.1.1_ButtonLED/ButtonLED.py b/Code/Python_Code/02.1.1_ButtonLED/ButtonLED.py index 3a5e361..8b98fae 100644 --- a/Code/Python_Code/02.1.1_ButtonLED/ButtonLED.py +++ b/Code/Python_Code/02.1.1_ButtonLED/ButtonLED.py @@ -11,29 +11,29 @@ ledPin = 11 # define ledPin buttonPin = 12 # define buttonPin def setup(): - - GPIO.setmode(GPIO.BOARD) # use PHYSICAL GPIO Numbering - GPIO.setup(ledPin, GPIO.OUT) # set ledPin to OUTPUT mode - GPIO.setup(buttonPin, GPIO.IN, pull_up_down=GPIO.PUD_UP) # set buttonPin to PULL UP INPUT mode + + GPIO.setmode(GPIO.BOARD) # use PHYSICAL GPIO Numbering + GPIO.setup(ledPin, GPIO.OUT) # set ledPin to OUTPUT mode + GPIO.setup(buttonPin, GPIO.IN, pull_up_down=GPIO.PUD_UP) # set buttonPin to PULL UP INPUT mode def loop(): - while True: - if GPIO.input(buttonPin)==GPIO.LOW: # if button is pressed - GPIO.output(ledPin,GPIO.HIGH) # turn on led - print ('led turned on >>>') # print information on terminal - else : # if button is relessed - GPIO.output(ledPin,GPIO.LOW) # turn off led - print ('led turned off <<<') + while True: + if GPIO.input(buttonPin)==GPIO.LOW: # if button is pressed + GPIO.output(ledPin,GPIO.HIGH) # turn on led + print ('led turned on >>>') # print information on terminal + else : # if button is relessed + GPIO.output(ledPin,GPIO.LOW) # turn off led + print ('led turned off <<<') def destroy(): - GPIO.output(ledPin, GPIO.LOW) # turn off led - GPIO.cleanup() # Release GPIO resource + GPIO.output(ledPin, GPIO.LOW) # turn off led + GPIO.cleanup() # Release GPIO resource if __name__ == '__main__': # Program entrance - print ('Program is starting...') - setup() - try: - loop() - except KeyboardInterrupt: # Press ctrl-c to end the program. - destroy() + print ('Program is starting...') + setup() + try: + loop() + except KeyboardInterrupt: # Press ctrl-c to end the program. + destroy() diff --git a/Code/Python_Code/02.1.1_ButtonLED/ButtonLED2.py b/Code/Python_Code/02.1.1_ButtonLED/ButtonLED2.py index c566cdf..841508a 100644 --- a/Code/Python_Code/02.1.1_ButtonLED/ButtonLED2.py +++ b/Code/Python_Code/02.1.1_ButtonLED/ButtonLED2.py @@ -14,12 +14,12 @@ led = LED(17) # define LED pin according to BCM Numbering button = Button(18) # define Button pin according to BCM Numbering def onButtonPressed(): - led.on() - print("Button is pressed, led turned on >>>") - + led.on() + print("Button is pressed, led turned on >>>") + def onButtonReleased(): - led.off() - print("Button is released, led turned on <<<") + led.off() + print("Button is released, led turned on <<<") button.when_pressed = onButtonPressed button.when_released = onButtonReleased diff --git a/Code/Python_Code/02.2.1_Tablelamp/Tablelamp2.py b/Code/Python_Code/02.2.1_Tablelamp/Tablelamp2.py index 2445f89..24e6813 100644 --- a/Code/Python_Code/02.2.1_Tablelamp/Tablelamp2.py +++ b/Code/Python_Code/02.2.1_Tablelamp/Tablelamp2.py @@ -14,11 +14,11 @@ led = LED(17) # define LED pin according to BCM Numbering button = Button(18) # define Button pin according to BCM Numbering def onButtonPressed(): - led.toggle() - if led.is_lit : - print("Led turned on >>>") - else : - print("Led turned off <<<") + led.toggle() + if led.is_lit : + print("Led turned on >>>") + else : + print("Led turned off <<<") button.when_pressed = onButtonPressed diff --git a/Code/Python_Code/03.1.1_LightWater/LightWater.py b/Code/Python_Code/03.1.1_LightWater/LightWater.py index 60bc77f..4fc8595 100644 --- a/Code/Python_Code/03.1.1_LightWater/LightWater.py +++ b/Code/Python_Code/03.1.1_LightWater/LightWater.py @@ -10,30 +10,30 @@ import time ledPins = [11, 12, 13, 15, 16, 18, 22, 3, 5, 24] -def setup(): - GPIO.setmode(GPIO.BOARD) # use PHYSICAL GPIO Numbering - GPIO.setup(ledPins, GPIO.OUT) # set all ledPins to OUTPUT mode - GPIO.output(ledPins, GPIO.HIGH) # make all ledPins output HIGH level, turn off all led +def setup(): + GPIO.setmode(GPIO.BOARD) # use PHYSICAL GPIO Numbering + GPIO.setup(ledPins, GPIO.OUT) # set all ledPins to OUTPUT mode + GPIO.output(ledPins, GPIO.HIGH) # make all ledPins output HIGH level, turn off all led def loop(): - while True: - for pin in ledPins: # make led(on) move from left to right - GPIO.output(pin, GPIO.LOW) - time.sleep(0.1) - GPIO.output(pin, GPIO.HIGH) - for pin in ledPins[::-1]: # make led(on) move from right to left - GPIO.output(pin, GPIO.LOW) - time.sleep(0.1) - GPIO.output(pin, GPIO.HIGH) + while True: + for pin in ledPins: # make led(on) move from left to right + GPIO.output(pin, GPIO.LOW) + time.sleep(0.1) + GPIO.output(pin, GPIO.HIGH) + for pin in ledPins[::-1]: # make led(on) move from right to left + GPIO.output(pin, GPIO.LOW) + time.sleep(0.1) + GPIO.output(pin, GPIO.HIGH) def destroy(): - GPIO.cleanup() # Release all GPIO + GPIO.cleanup() # Release all GPIO if __name__ == '__main__': # Program entrance - print ('Program is starting...') - setup() - try: - loop() - except KeyboardInterrupt: # Press ctrl-c to end the program. - destroy() + print ('Program is starting...') + setup() + try: + loop() + except KeyboardInterrupt: # Press ctrl-c to end the program. + destroy() diff --git a/Code/Python_Code/03.1.1_LightWater/LightWater2.py b/Code/Python_Code/03.1.1_LightWater/LightWater2.py index bcb1aa9..7df1d38 100644 --- a/Code/Python_Code/03.1.1_LightWater/LightWater2.py +++ b/Code/Python_Code/03.1.1_LightWater/LightWater2.py @@ -16,13 +16,13 @@ ledPins = ["J8:11", "J8:12","J8:13","J8:15","J8:16","J8:18","J8:22","J8:3","J8:5 leds = LEDBoard(*ledPins, active_high=False) while True: - for index in range(0,len(ledPins),1): #move led(on) from left to right - leds.on(index) - sleep(0.1) - leds.off(index) - for index in range(len(ledPins)-1,-1,-1): #move led(on) from right to left - leds.on(index) - sleep(0.1) - leds.off(index) + for index in range(0,len(ledPins),1): #move led(on) from left to right + leds.on(index) + sleep(0.1) + leds.off(index) + for index in range(len(ledPins)-1,-1,-1): #move led(on) from right to left + leds.on(index) + sleep(0.1) + leds.off(index) diff --git a/Code/Python_Code/04.1.1_BreathingLED/BreathingLED.py b/Code/Python_Code/04.1.1_BreathingLED/BreathingLED.py index f7c45d5..134a835 100644 --- a/Code/Python_Code/04.1.1_BreathingLED/BreathingLED.py +++ b/Code/Python_Code/04.1.1_BreathingLED/BreathingLED.py @@ -8,36 +8,36 @@ import RPi.GPIO as GPIO import time -LedPin = 12 # define the LedPin +LedPin = 12 # define the LedPin def setup(): - global p - GPIO.setmode(GPIO.BOARD) # use PHYSICAL GPIO Numbering - GPIO.setup(LedPin, GPIO.OUT) # set LedPin to OUTPUT mode - GPIO.output(LedPin, GPIO.LOW) # make ledPin output LOW level to turn off LED + global p + GPIO.setmode(GPIO.BOARD) # use PHYSICAL GPIO Numbering + GPIO.setup(LedPin, GPIO.OUT) # set LedPin to OUTPUT mode + GPIO.output(LedPin, GPIO.LOW) # make ledPin output LOW level to turn off LED - p = GPIO.PWM(LedPin, 500) # set PWM Frequence to 500Hz - p.start(0) # set initial Duty Cycle to 0 + p = GPIO.PWM(LedPin, 500) # set PWM Frequence to 500Hz + p.start(0) # set initial Duty Cycle to 0 def loop(): - while True: - for dc in range(0, 101, 1): # make the led brighter - p.ChangeDutyCycle(dc) # set dc value as the duty cycle - time.sleep(0.01) - time.sleep(1) - for dc in range(100, -1, -1): # make the led darker - p.ChangeDutyCycle(dc) # set dc value as the duty cycle - time.sleep(0.01) - time.sleep(1) + while True: + for dc in range(0, 101, 1): # make the led brighter + p.ChangeDutyCycle(dc) # set dc value as the duty cycle + time.sleep(0.01) + time.sleep(1) + for dc in range(100, -1, -1): # make the led darker + p.ChangeDutyCycle(dc) # set dc value as the duty cycle + time.sleep(0.01) + time.sleep(1) def destroy(): - p.stop() # stop PWM - GPIO.cleanup() # Release all GPIO + p.stop() # stop PWM + GPIO.cleanup() # Release all GPIO if __name__ == '__main__': # Program entrance - print ('Program is starting ... ') - setup() - try: - loop() - except KeyboardInterrupt: # Press ctrl-c to end the program. - destroy() + print ('Program is starting ... ') + setup() + try: + loop() + except KeyboardInterrupt: # Press ctrl-c to end the program. + destroy() diff --git a/Code/Python_Code/05.1.1_ColorfulLED/ColorfulLED.py b/Code/Python_Code/05.1.1_ColorfulLED/ColorfulLED.py index efa8cae..7d971b7 100644 --- a/Code/Python_Code/05.1.1_ColorfulLED/ColorfulLED.py +++ b/Code/Python_Code/05.1.1_ColorfulLED/ColorfulLED.py @@ -9,44 +9,44 @@ import RPi.GPIO as GPIO import time import random -pins = [11, 12, 13] # define the pins for R:11,G:12,B:13 +pins = [11, 12, 13] # define the pins for R:11,G:12,B:13 def setup(): - global pwmRed,pwmGreen,pwmBlue - GPIO.setmode(GPIO.BOARD) # use PHYSICAL GPIO Numbering - GPIO.setup(pins, GPIO.OUT) # set RGBLED pins to OUTPUT mode - GPIO.output(pins, GPIO.HIGH) # make RGBLED pins output HIGH level - pwmRed = GPIO.PWM(pins[0], 2000) # set PWM Frequence to 2kHz - pwmGreen = GPIO.PWM(pins[1], 2000) # set PWM Frequence to 2kHz - pwmBlue = GPIO.PWM(pins[2], 2000) # set PWM Frequence to 2kHz - pwmRed.start(0) # set initial Duty Cycle to 0 - pwmGreen.start(0) - pwmBlue.start(0) + global pwmRed,pwmGreen,pwmBlue + GPIO.setmode(GPIO.BOARD) # use PHYSICAL GPIO Numbering + GPIO.setup(pins, GPIO.OUT) # set RGBLED pins to OUTPUT mode + GPIO.output(pins, GPIO.HIGH) # make RGBLED pins output HIGH level + pwmRed = GPIO.PWM(pins[0], 2000) # set PWM Frequence to 2kHz + pwmGreen = GPIO.PWM(pins[1], 2000) # set PWM Frequence to 2kHz + pwmBlue = GPIO.PWM(pins[2], 2000) # set PWM Frequence to 2kHz + pwmRed.start(0) # set initial Duty Cycle to 0 + pwmGreen.start(0) + pwmBlue.start(0) def setColor(r_val,g_val,b_val): # change duty cycle for three pins to r_val,g_val,b_val - pwmRed.ChangeDutyCycle(r_val) # change pwmRed duty cycle to r_val - pwmGreen.ChangeDutyCycle(g_val) - pwmBlue.ChangeDutyCycle(b_val) + pwmRed.ChangeDutyCycle(r_val) # change pwmRed duty cycle to r_val + pwmGreen.ChangeDutyCycle(g_val) + pwmBlue.ChangeDutyCycle(b_val) def loop(): - while True : - r=random.randint(0,100) #get a random in (0,100) - g=random.randint(0,100) - b=random.randint(0,100) - setColor(r,g,b) #set random as a duty cycle value - print ('r=%d, g=%d, b=%d ' %(r ,g, b)) - time.sleep(0.3) - + while True : + r=random.randint(0,100) #get a random in (0,100) + g=random.randint(0,100) + b=random.randint(0,100) + setColor(r,g,b) #set random as a duty cycle value + print ('r=%d, g=%d, b=%d ' %(r ,g, b)) + time.sleep(0.3) + def destroy(): - pwmRed.stop() - pwmGreen.stop() - pwmBlue.stop() - GPIO.cleanup() - + pwmRed.stop() + pwmGreen.stop() + pwmBlue.stop() + GPIO.cleanup() + if __name__ == '__main__': # Program entrance - print ('Program is starting ... ') - setup() - try: - loop() - except KeyboardInterrupt: # Press ctrl-c to end the program. - destroy() + print ('Program is starting ... ') + setup() + try: + loop() + except KeyboardInterrupt: # Press ctrl-c to end the program. + destroy() diff --git a/Code/Python_Code/06.1.1_Doorbell/Doorbell.py b/Code/Python_Code/06.1.1_Doorbell/Doorbell.py index 9e829d7..e62517f 100644 --- a/Code/Python_Code/06.1.1_Doorbell/Doorbell.py +++ b/Code/Python_Code/06.1.1_Doorbell/Doorbell.py @@ -11,27 +11,27 @@ buzzerPin = 11 # define buzzerPin buttonPin = 12 # define buttonPin def setup(): - GPIO.setmode(GPIO.BOARD) # use PHYSICAL GPIO Numbering - GPIO.setup(buzzerPin, GPIO.OUT) # set buzzerPin to OUTPUT mode - GPIO.setup(buttonPin, GPIO.IN, pull_up_down=GPIO.PUD_UP) # set buttonPin to PULL UP INPUT mode + GPIO.setmode(GPIO.BOARD) # use PHYSICAL GPIO Numbering + GPIO.setup(buzzerPin, GPIO.OUT) # set buzzerPin to OUTPUT mode + GPIO.setup(buttonPin, GPIO.IN, pull_up_down=GPIO.PUD_UP) # set buttonPin to PULL UP INPUT mode def loop(): - while True: - if GPIO.input(buttonPin)==GPIO.LOW: # if button is pressed - GPIO.output(buzzerPin,GPIO.HIGH) # turn on buzzer - print ('buzzer turned on >>>') - else : # if button is relessed - GPIO.output(buzzerPin,GPIO.LOW) # turn off buzzer - print ('buzzer turned off <<<') + while True: + if GPIO.input(buttonPin)==GPIO.LOW: # if button is pressed + GPIO.output(buzzerPin,GPIO.HIGH) # turn on buzzer + print ('buzzer turned on >>>') + else : # if button is relessed + GPIO.output(buzzerPin,GPIO.LOW) # turn off buzzer + print ('buzzer turned off <<<') def destroy(): - GPIO.cleanup() # Release all GPIO + GPIO.cleanup() # Release all GPIO if __name__ == '__main__': # Program entrance print ('Program is starting...') setup() try: - loop() + loop() except KeyboardInterrupt: # Press ctrl-c to end the program. - destroy() + destroy() diff --git a/Code/Python_Code/06.1.1_Doorbell/Doorbell2.py b/Code/Python_Code/06.1.1_Doorbell/Doorbell2.py index 55821ee..bc8a146 100644 --- a/Code/Python_Code/06.1.1_Doorbell/Doorbell2.py +++ b/Code/Python_Code/06.1.1_Doorbell/Doorbell2.py @@ -14,12 +14,12 @@ led = LED(17) button = Button(18) def onButtonPressed(): - led.on() - print("Button is pressed, led turned on >>>") - + led.on() + print("Button is pressed, led turned on >>>") + def onButtonReleased(): - led.off() - print("Button is released, led turned on <<<") + led.off() + print("Button is released, led turned on <<<") button.when_pressed = onButtonPressed button.when_released = onButtonReleased diff --git a/Code/Python_Code/06.2.1_Alertor/Alertor.py b/Code/Python_Code/06.2.1_Alertor/Alertor.py index c159178..fe801d3 100644 --- a/Code/Python_Code/06.2.1_Alertor/Alertor.py +++ b/Code/Python_Code/06.2.1_Alertor/Alertor.py @@ -13,41 +13,41 @@ buzzerPin = 11 # define the buzzerPin buttonPin = 12 # define the buttonPin def setup(): - global p - GPIO.setmode(GPIO.BOARD) # Use PHYSICAL GPIO Numbering - GPIO.setup(buzzerPin, GPIO.OUT) # set RGBLED pins to OUTPUT mode - GPIO.setup(buttonPin, GPIO.IN, pull_up_down=GPIO.PUD_UP) # Set buttonPin to INPUT mode, and pull up to HIGH level, 3.3V - p = GPIO.PWM(buzzerPin, 1) - p.start(0); - + global p + GPIO.setmode(GPIO.BOARD) # Use PHYSICAL GPIO Numbering + GPIO.setup(buzzerPin, GPIO.OUT) # set RGBLED pins to OUTPUT mode + GPIO.setup(buttonPin, GPIO.IN, pull_up_down=GPIO.PUD_UP) # Set buttonPin to INPUT mode, and pull up to HIGH level, 3.3V + p = GPIO.PWM(buzzerPin, 1) + p.start(0); + def loop(): - while True: - if GPIO.input(buttonPin)==GPIO.LOW: - alertor() - print ('alertor turned on >>> ') - else : - stopAlertor() - print ('alertor turned off <<<') + while True: + if GPIO.input(buttonPin)==GPIO.LOW: + alertor() + print ('alertor turned on >>> ') + else : + stopAlertor() + print ('alertor turned off <<<') def alertor(): - p.start(50) - for x in range(0,361): # Make frequency of the alertor consistent with the sine wave - sinVal = math.sin(x * (math.pi / 180.0)) # calculate the sine value - toneVal = 2000 + sinVal * 500 # Add to the resonant frequency with a Weighted - p.ChangeFrequency(toneVal) # Change Frequency of PWM to toneVal - time.sleep(0.001) - + p.start(50) + for x in range(0,361): # Make frequency of the alertor consistent with the sine wave + sinVal = math.sin(x * (math.pi / 180.0)) # calculate the sine value + toneVal = 2000 + sinVal * 500 # Add to the resonant frequency with a Weighted + p.ChangeFrequency(toneVal) # Change Frequency of PWM to toneVal + time.sleep(0.001) + def stopAlertor(): - p.stop() - + p.stop() + def destroy(): - GPIO.output(buzzerPin, GPIO.LOW) # Turn off buzzer - GPIO.cleanup() # Release GPIO resource + GPIO.output(buzzerPin, GPIO.LOW) # Turn off buzzer + GPIO.cleanup() # Release GPIO resource if __name__ == '__main__': # Program entrance - print ('Program is starting...') - setup() - try: - loop() - except KeyboardInterrupt: # Press ctrl-c to end the program. - destroy() + print ('Program is starting...') + setup() + try: + loop() + except KeyboardInterrupt: # Press ctrl-c to end the program. + destroy() diff --git a/Code/Python_Code/07.1.1_ADC/ADC.py b/Code/Python_Code/07.1.1_ADC/ADC.py index 9cabe9a..ba98031 100644 --- a/Code/Python_Code/07.1.1_ADC/ADC.py +++ b/Code/Python_Code/07.1.1_ADC/ADC.py @@ -8,33 +8,33 @@ import smbus import time -address = 0x48 # default address of PCF8591 +address = 0x48 # default address of PCF8591 bus=smbus.SMBus(1) -cmd=0x40 # command, 0100 0000 +cmd=0x40 # command, 0100 0000 def analogRead(chn): # read ADC value,chn:0,1,2,3 - value = bus.read_byte_data(address,cmd+chn) - return value - + value = bus.read_byte_data(address,cmd+chn) + return value + def analogWrite(value): # write DAC value - bus.write_byte_data(address,cmd,value) - + bus.write_byte_data(address,cmd,value) + def loop(): - while True: - value = analogRead(0) # read the ADC value of channel 0 - analogWrite(value) # write the DAC value to control led - voltage = value / 255.0 * 3.3 # calculate the voltage value - print ('ADC Value : %d, Voltage : %.2f'%(value,voltage)) - time.sleep(0.01) + while True: + value = analogRead(0) # read the ADC value of channel 0 + analogWrite(value) # write the DAC value to control led + voltage = value / 255.0 * 3.3 # calculate the voltage value + print ('ADC Value : %d, Voltage : %.2f'%(value,voltage)) + time.sleep(0.01) def destroy(): - bus.close() - + bus.close() + if __name__ == '__main__': # Program entrance - print ('Program is starting ... ') - try: - loop() - except KeyboardInterrupt: # Press ctrl-c to end the program. - destroy() - - + print ('Program is starting ... ') + try: + loop() + except KeyboardInterrupt: # Press ctrl-c to end the program. + destroy() + + diff --git a/Code/Python_Code/08.1.1_Softlight/Softlight.py b/Code/Python_Code/08.1.1_Softlight/Softlight.py index 323055a..b64e54c 100644 --- a/Code/Python_Code/08.1.1_Softlight/Softlight.py +++ b/Code/Python_Code/08.1.1_Softlight/Softlight.py @@ -15,39 +15,39 @@ cmd=0x40 # command, 0100 0000 ledPin = 11 def analogRead(chn): - value = bus.read_byte_data(address,cmd+chn) - return value - + value = bus.read_byte_data(address,cmd+chn) + return value + def analogWrite(value): - bus.write_byte_data(address,cmd,value) + bus.write_byte_data(address,cmd,value) def setup(): - global p - GPIO.setmode(GPIO.BOARD) - GPIO.setup(ledPin,GPIO.OUT) - GPIO.output(ledPin,GPIO.LOW) - - p = GPIO.PWM(ledPin,1000) - p.start(0) - + global p + GPIO.setmode(GPIO.BOARD) + GPIO.setup(ledPin,GPIO.OUT) + GPIO.output(ledPin,GPIO.LOW) + + p = GPIO.PWM(ledPin,1000) + p.start(0) + def loop(): - while True: - value = analogRead(0) #read ADC value of A0 pin - p.ChangeDutyCycle(value*100/255) #Convert ADC value to duty cycle of PWM - voltage = value / 255.0 * 3.3 #calculate voltage - print ('ADC Value : %d, Voltage : %.2f'%(value,voltage)) - time.sleep(0.01) + while True: + value = analogRead(0) #read ADC value of A0 pin + p.ChangeDutyCycle(value*100/255) #Convert ADC value to duty cycle of PWM + voltage = value / 255.0 * 3.3 #calculate voltage + print ('ADC Value : %d, Voltage : %.2f'%(value,voltage)) + time.sleep(0.01) def destroy(): - bus.close() - GPIO.cleanup() - + bus.close() + GPIO.cleanup() + if __name__ == '__main__': # Program entrance - print ('Program is starting ... ') - setup() - try: - loop() - except KeyboardInterrupt: # Press ctrl-c to end the program. - destroy() - - + print ('Program is starting ... ') + setup() + try: + loop() + except KeyboardInterrupt: # Press ctrl-c to end the program. + destroy() + + diff --git a/Code/Python_Code/10.1.1_Nightlamp/Nightlamp.py b/Code/Python_Code/10.1.1_Nightlamp/Nightlamp.py index e3c1a45..a294e3a 100644 --- a/Code/Python_Code/10.1.1_Nightlamp/Nightlamp.py +++ b/Code/Python_Code/10.1.1_Nightlamp/Nightlamp.py @@ -15,39 +15,39 @@ cmd=0x40 ledPin = 11 # define ledPin def analogRead(chn): - value = bus.read_byte_data(address,cmd+chn) - return value - + value = bus.read_byte_data(address,cmd+chn) + return value + def analogWrite(value): - bus.write_byte_data(address,cmd,value) + bus.write_byte_data(address,cmd,value) def setup(): - global p - GPIO.setmode(GPIO.BOARD) - GPIO.setup(ledPin,GPIO.OUT) # set ledPin to OUTPUT mode - GPIO.output(ledPin,GPIO.LOW) - - p = GPIO.PWM(ledPin,1000) # set PWM Frequence to 1kHz - p.start(0) - + global p + GPIO.setmode(GPIO.BOARD) + GPIO.setup(ledPin,GPIO.OUT) # set ledPin to OUTPUT mode + GPIO.output(ledPin,GPIO.LOW) + + p = GPIO.PWM(ledPin,1000) # set PWM Frequence to 1kHz + p.start(0) + def loop(): - while True: - value = analogRead(0) # read the ADC value of channel 0 - p.ChangeDutyCycle(value*100/255) - voltage = value / 255.0 * 3.3 - print ('ADC Value : %d, Voltage : %.2f'%(value,voltage)) - time.sleep(0.01) + while True: + value = analogRead(0) # read the ADC value of channel 0 + p.ChangeDutyCycle(value*100/255) + voltage = value / 255.0 * 3.3 + print ('ADC Value : %d, Voltage : %.2f'%(value,voltage)) + time.sleep(0.01) def destroy(): - bus.close() - GPIO.cleanup() - + bus.close() + GPIO.cleanup() + if __name__ == '__main__': # Program entrance - print ('Program is starting ... ') - setup() - try: - loop() - except KeyboardInterrupt: # Press ctrl-c to end the program. - destroy() - - + print ('Program is starting ... ') + setup() + try: + loop() + except KeyboardInterrupt: # Press ctrl-c to end the program. + destroy() + + diff --git a/Code/Python_Code/11.1.1_Thermometer/Thermometer.py b/Code/Python_Code/11.1.1_Thermometer/Thermometer.py index cc61f4b..40d2f75 100644 --- a/Code/Python_Code/11.1.1_Thermometer/Thermometer.py +++ b/Code/Python_Code/11.1.1_Thermometer/Thermometer.py @@ -15,34 +15,34 @@ bus=smbus.SMBus(1) cmd=0x40 def analogRead(chn): - value = bus.read_byte_data(address,cmd+chn) - return value - + value = bus.read_byte_data(address,cmd+chn) + return value + def analogWrite(value): - bus.write_byte_data(address,cmd,value) - + bus.write_byte_data(address,cmd,value) + def setup(): - GPIO.setmode(GPIO.BOARD) - + GPIO.setmode(GPIO.BOARD) + def loop(): - while True: - value = analogRead(0) # read ADC value A0 pin - voltage = value / 255.0 * 3.3 # calculate voltage - Rt = 10 * voltage / (3.3 - voltage) # calculate resistance value of thermistor - tempK = 1/(1/(273.15 + 25) + math.log(Rt/10)/3950.0) # calculate temperature (Kelvin) - tempC = tempK -273.15 # calculate temperature (Celsius) - print ('ADC Value : %d, Voltage : %.2f, Temperature : %.2f'%(value,voltage,tempC)) - time.sleep(0.01) + while True: + value = analogRead(0) # read ADC value A0 pin + voltage = value / 255.0 * 3.3 # calculate voltage + Rt = 10 * voltage / (3.3 - voltage) # calculate resistance value of thermistor + tempK = 1/(1/(273.15 + 25) + math.log(Rt/10)/3950.0) # calculate temperature (Kelvin) + tempC = tempK -273.15 # calculate temperature (Celsius) + print ('ADC Value : %d, Voltage : %.2f, Temperature : %.2f'%(value,voltage,tempC)) + time.sleep(0.01) def destroy(): - GPIO.cleanup() - + GPIO.cleanup() + if __name__ == '__main__': # Program entrance - print ('Program is starting ... ') - setup() - try: - loop() - except KeyboardInterrupt: # Press ctrl-c to end the program. - destroy() - - + print ('Program is starting ... ') + setup() + try: + loop() + except KeyboardInterrupt: # Press ctrl-c to end the program. + destroy() + + diff --git a/Code/Python_Code/14.1.1_Relay/Relay.py b/Code/Python_Code/14.1.1_Relay/Relay.py index 41d7d90..22e8f0b 100644 --- a/Code/Python_Code/14.1.1_Relay/Relay.py +++ b/Code/Python_Code/14.1.1_Relay/Relay.py @@ -12,44 +12,44 @@ relayPin = 11 # define the relayPin buttonPin = 12 # define the buttonPin debounceTime = 50 -def setup(): - GPIO.setmode(GPIO.BOARD) - GPIO.setup(relayPin, GPIO.OUT) # set relayPin to OUTPUT mode - GPIO.setup(buttonPin, GPIO.IN) # set buttonPin to INTPUT mode +def setup(): + GPIO.setmode(GPIO.BOARD) + GPIO.setup(relayPin, GPIO.OUT) # set relayPin to OUTPUT mode + GPIO.setup(buttonPin, GPIO.IN) # set buttonPin to INTPUT mode def loop(): - relayState = False - lastChangeTime = round(time.time()*1000) - buttonState = GPIO.HIGH - lastButtonState = GPIO.HIGH - reading = GPIO.HIGH - while True: - reading = GPIO.input(buttonPin) - if reading != lastButtonState : - lastChangeTime = round(time.time()*1000) - if ((round(time.time()*1000) - lastChangeTime) > debounceTime): - if reading != buttonState : - buttonState = reading; - if buttonState == GPIO.LOW: - print("Button is pressed!") - relayState = not relayState - if relayState: - print("Turn on relay ...") - else : - print("Turn off relay ... ") - else : - print("Button is released!") - GPIO.output(relayPin,relayState) - lastButtonState = reading # lastButtonState store latest state - + relayState = False + lastChangeTime = round(time.time()*1000) + buttonState = GPIO.HIGH + lastButtonState = GPIO.HIGH + reading = GPIO.HIGH + while True: + reading = GPIO.input(buttonPin) + if reading != lastButtonState : + lastChangeTime = round(time.time()*1000) + if ((round(time.time()*1000) - lastChangeTime) > debounceTime): + if reading != buttonState : + buttonState = reading; + if buttonState == GPIO.LOW: + print("Button is pressed!") + relayState = not relayState + if relayState: + print("Turn on relay ...") + else : + print("Turn off relay ... ") + else : + print("Button is released!") + GPIO.output(relayPin,relayState) + lastButtonState = reading # lastButtonState store latest state + def destroy(): - GPIO.cleanup() + GPIO.cleanup() if __name__ == '__main__': # Program entrance - print ('Program is starting...') - setup() - try: - loop() - except KeyboardInterrupt: # Press ctrl-c to end the program. - destroy() + print ('Program is starting...') + setup() + try: + loop() + except KeyboardInterrupt: # Press ctrl-c to end the program. + destroy() diff --git a/Code/Python_Code/16.1.1_SteppingMotor/SteppingMotor.py b/Code/Python_Code/16.1.1_SteppingMotor/SteppingMotor.py index da4536c..7ee71c5 100644 --- a/Code/Python_Code/16.1.1_SteppingMotor/SteppingMotor.py +++ b/Code/Python_Code/16.1.1_SteppingMotor/SteppingMotor.py @@ -16,7 +16,7 @@ def setup(): GPIO.setmode(GPIO.BOARD) # use PHYSICAL GPIO Numbering for pin in motorPins: GPIO.setup(pin,GPIO.OUT) - + # as for four phase stepping motor, four steps is a cycle. the function is used to drive the stepping motor clockwise or anticlockwise to take four steps def moveOnePeriod(direction,ms): for j in range(0,4,1): # cycle for power supply order @@ -28,12 +28,12 @@ def moveOnePeriod(direction,ms): if(ms<3): # the delay can not be less than 3ms, otherwise it will exceed speed limit of the motor ms = 3 time.sleep(ms*0.001) - + # continuous rotation function, the parameter steps specifies the rotation cycles, every four steps is a cycle def moveSteps(direction, ms, steps): for i in range(steps): moveOnePeriod(direction, ms) - + # function used to stop motor def motorStop(): for i in range(0,4,1): diff --git a/Code/Python_Code/17.1.1_LightWater02/LightWater02.py b/Code/Python_Code/17.1.1_LightWater02/LightWater02.py index f2bb684..5cd65fc 100644 --- a/Code/Python_Code/17.1.1_LightWater02/LightWater02.py +++ b/Code/Python_Code/17.1.1_LightWater02/LightWater02.py @@ -11,50 +11,50 @@ import time LSBFIRST = 1 MSBFIRST = 2 # define the pins for 74HC595 -dataPin = 11 # DS Pin of 74HC595(Pin14) -latchPin = 13 # ST_CP Pin of 74HC595(Pin12) -clockPin = 15 # CH_CP Pin of 74HC595(Pin11) +dataPin = 11 # DS Pin of 74HC595(Pin14) +latchPin = 13 # ST_CP Pin of 74HC595(Pin12) +clockPin = 15 # CH_CP Pin of 74HC595(Pin11) def setup(): - GPIO.setmode(GPIO.BOARD) # use PHYSICAL GPIO Numbering - GPIO.setup(dataPin, GPIO.OUT) # set pin to OUTPUT mode - GPIO.setup(latchPin, GPIO.OUT) - GPIO.setup(clockPin, GPIO.OUT) - + GPIO.setmode(GPIO.BOARD) # use PHYSICAL GPIO Numbering + GPIO.setup(dataPin, GPIO.OUT) # set pin to OUTPUT mode + GPIO.setup(latchPin, GPIO.OUT) + GPIO.setup(clockPin, GPIO.OUT) + # shiftOut function, use bit serial transmission. def shiftOut(dPin,cPin,order,val): - for i in range(0,8): - GPIO.output(cPin,GPIO.LOW); - if(order == LSBFIRST): - GPIO.output(dPin,(0x01&(val>>i)==0x01) and GPIO.HIGH or GPIO.LOW) - elif(order == MSBFIRST): - GPIO.output(dPin,(0x80&(val<>i)==0x01) and GPIO.HIGH or GPIO.LOW) + elif(order == MSBFIRST): + GPIO.output(dPin,(0x80&(val<>=1 - time.sleep(0.1) + while True: + x=0x01 + for i in range(0,8): + GPIO.output(latchPin,GPIO.LOW) # Output low level to latchPin + shiftOut(dataPin,clockPin,LSBFIRST,x) # Send serial data to 74HC595 + GPIO.output(latchPin,GPIO.HIGH) # Output high level to latchPin, and 74HC595 will update the data to the parallel output port. + x<<=1 # make the variable move one bit to left once, then the bright LED move one step to the left once. + time.sleep(0.1) + x=0x80 + for i in range(0,8): + GPIO.output(latchPin,GPIO.LOW) + shiftOut(dataPin,clockPin,LSBFIRST,x) + GPIO.output(latchPin,GPIO.HIGH) + x>>=1 + time.sleep(0.1) def destroy(): - GPIO.cleanup() + GPIO.cleanup() if __name__ == '__main__': # Program entrance - print ('Program is starting...' ) - setup() - try: - loop() - except KeyboardInterrupt: # Press ctrl-c to end the program. - destroy() + print ('Program is starting...' ) + setup() + try: + loop() + except KeyboardInterrupt: # Press ctrl-c to end the program. + destroy() diff --git a/Code/Python_Code/18.1.1_SevenSegmentDisplay/SevenSegmentDisplay.py b/Code/Python_Code/18.1.1_SevenSegmentDisplay/SevenSegmentDisplay.py index 8a9814b..f3fd562 100644 --- a/Code/Python_Code/18.1.1_SevenSegmentDisplay/SevenSegmentDisplay.py +++ b/Code/Python_Code/18.1.1_SevenSegmentDisplay/SevenSegmentDisplay.py @@ -11,46 +11,46 @@ import time LSBFIRST = 1 MSBFIRST = 2 # define the pins for 74HC595 -dataPin = 11 # DS Pin of 74HC595(Pin14) -latchPin = 13 # ST_CP Pin of 74HC595(Pin12) -clockPin = 15 # CH_CP Pin of 74HC595(Pin11) +dataPin = 11 # DS Pin of 74HC595(Pin14) +latchPin = 13 # ST_CP Pin of 74HC595(Pin12) +clockPin = 15 # CH_CP Pin of 74HC595(Pin11) # SevenSegmentDisplay display the character "0"- "F" successively num = [0xc0,0xf9,0xa4,0xb0,0x99,0x92,0x82,0xf8,0x80,0x90,0x88,0x83,0xc6,0xa1,0x86,0x8e] def setup(): - GPIO.setmode(GPIO.BOARD) # use PHYSICAL GPIO Numbering - GPIO.setup(dataPin, GPIO.OUT) - GPIO.setup(latchPin, GPIO.OUT) - GPIO.setup(clockPin, GPIO.OUT) - + GPIO.setmode(GPIO.BOARD) # use PHYSICAL GPIO Numbering + GPIO.setup(dataPin, GPIO.OUT) + GPIO.setup(latchPin, GPIO.OUT) + GPIO.setup(clockPin, GPIO.OUT) + def shiftOut(dPin,cPin,order,val): - for i in range(0,8): - GPIO.output(cPin,GPIO.LOW); - if(order == LSBFIRST): - GPIO.output(dPin,(0x01&(val>>i)==0x01) and GPIO.HIGH or GPIO.LOW) - elif(order == MSBFIRST): - GPIO.output(dPin,(0x80&(val<>i)==0x01) and GPIO.HIGH or GPIO.LOW) + elif(order == MSBFIRST): + GPIO.output(dPin,(0x80&(val< loopCnt): - #print ("Echo LOW") - return self.DHTLIB_ERROR_TIMEOUT - t = time.time() - while(GPIO.input(pin) == GPIO.HIGH): - if((time.time() - t) > loopCnt): - #print ("Echo HIGH") - return self.DHTLIB_ERROR_TIMEOUT - for i in range(0,40,1): - t = time.time() - while(GPIO.input(pin) == GPIO.LOW): - if((time.time() - t) > loopCnt): - #print ("Data Low %d"%(i)) - return self.DHTLIB_ERROR_TIMEOUT - t = time.time() - while(GPIO.input(pin) == GPIO.HIGH): - if((time.time() - t) > loopCnt): - #print ("Data HIGH %d"%(i)) - return self.DHTLIB_ERROR_TIMEOUT - if((time.time() - t) > 0.00005): - self.bits[idx] |= mask - #print("t : %f"%(time.time()-t)) - mask >>= 1 - if(mask == 0): - mask = 0x80 - idx += 1 - #print (self.bits) - GPIO.setup(pin,GPIO.OUT) - GPIO.output(pin,GPIO.HIGH) - return self.DHTLIB_OK - #Read DHT sensor, analyze the data of temperature and humidity - def readDHT11(self): - rv = self.readSensor(self.pin,self.DHTLIB_DHT11_WAKEUP) - if (rv is not self.DHTLIB_OK): - self.humidity = self.DHTLIB_INVALID_VALUE - self.temperature = self.DHTLIB_INVALID_VALUE - return rv - self.humidity = self.bits[0] - self.temperature = self.bits[2] + self.bits[3]*0.1 - sumChk = ((self.bits[0] + self.bits[1] + self.bits[2] + self.bits[3]) & 0xFF) - if(self.bits[4] is not sumChk): - return self.DHTLIB_ERROR_CHECKSUM - return self.DHTLIB_OK - + DHTLIB_OK = 0 + DHTLIB_ERROR_CHECKSUM = -1 + DHTLIB_ERROR_TIMEOUT = -2 + DHTLIB_INVALID_VALUE = -999 + + DHTLIB_DHT11_WAKEUP = 0.020#0.018 #18ms + DHTLIB_TIMEOUT = 0.0001 #100us + + humidity = 0 + temperature = 0 + + def __init__(self,pin): + self.pin = pin + self.bits = [0,0,0,0,0] + GPIO.setmode(GPIO.BOARD) + #Read DHT sensor, store the original data in bits[] + def readSensor(self,pin,wakeupDelay): + mask = 0x80 + idx = 0 + self.bits = [0,0,0,0,0] + GPIO.setup(pin,GPIO.OUT) + GPIO.output(pin,GPIO.LOW) + time.sleep(wakeupDelay) + GPIO.output(pin,GPIO.HIGH) + #time.sleep(40*0.000001) + GPIO.setup(pin,GPIO.IN) + + loopCnt = self.DHTLIB_TIMEOUT + t = time.time() + while(GPIO.input(pin) == GPIO.LOW): + if((time.time() - t) > loopCnt): + #print ("Echo LOW") + return self.DHTLIB_ERROR_TIMEOUT + t = time.time() + while(GPIO.input(pin) == GPIO.HIGH): + if((time.time() - t) > loopCnt): + #print ("Echo HIGH") + return self.DHTLIB_ERROR_TIMEOUT + for i in range(0,40,1): + t = time.time() + while(GPIO.input(pin) == GPIO.LOW): + if((time.time() - t) > loopCnt): + #print ("Data Low %d"%(i)) + return self.DHTLIB_ERROR_TIMEOUT + t = time.time() + while(GPIO.input(pin) == GPIO.HIGH): + if((time.time() - t) > loopCnt): + #print ("Data HIGH %d"%(i)) + return self.DHTLIB_ERROR_TIMEOUT + if((time.time() - t) > 0.00005): + self.bits[idx] |= mask + #print("t : %f"%(time.time()-t)) + mask >>= 1 + if(mask == 0): + mask = 0x80 + idx += 1 + #print (self.bits) + GPIO.setup(pin,GPIO.OUT) + GPIO.output(pin,GPIO.HIGH) + return self.DHTLIB_OK + #Read DHT sensor, analyze the data of temperature and humidity + def readDHT11(self): + rv = self.readSensor(self.pin,self.DHTLIB_DHT11_WAKEUP) + if (rv is not self.DHTLIB_OK): + self.humidity = self.DHTLIB_INVALID_VALUE + self.temperature = self.DHTLIB_INVALID_VALUE + return rv + self.humidity = self.bits[0] + self.temperature = self.bits[2] + self.bits[3]*0.1 + sumChk = ((self.bits[0] + self.bits[1] + self.bits[2] + self.bits[3]) & 0xFF) + if(self.bits[4] is not sumChk): + return self.DHTLIB_ERROR_CHECKSUM + return self.DHTLIB_OK + def loop(): - dht = DHT(11) - sumCnt = 0 - okCnt = 0 - while(True): - sumCnt += 1 - chk = dht.readDHT11() - if (chk is 0): - okCnt += 1 - okRate = 100.0*okCnt/sumCnt; - print("sumCnt : %d, \t okRate : %.2f%% "%(sumCnt,okRate)) - print("chk : %d, \t Humidity : %.2f, \t Temperature : %.2f "%(chk,dht.humidity,dht.temperature)) - time.sleep(3) - + dht = DHT(11) + sumCnt = 0 + okCnt = 0 + while(True): + sumCnt += 1 + chk = dht.readDHT11() + if (chk is 0): + okCnt += 1 + okRate = 100.0*okCnt/sumCnt; + print("sumCnt : %d, \t okRate : %.2f%% "%(sumCnt,okRate)) + print("chk : %d, \t Humidity : %.2f, \t Temperature : %.2f "%(chk,dht.humidity,dht.temperature)) + time.sleep(3) + if __name__ == '__main__': - print ('Program is starting ... ') - try: - loop() - except KeyboardInterrupt: - pass - exit() - - + print ('Program is starting ... ') + try: + loop() + except KeyboardInterrupt: + pass + exit() + + diff --git a/Code/Python_Code/21.1.1_DHT11/setup.py b/Code/Python_Code/21.1.1_DHT11/setup.py index e426364..8c0c9d5 100644 --- a/Code/Python_Code/21.1.1_DHT11/setup.py +++ b/Code/Python_Code/21.1.1_DHT11/setup.py @@ -2,12 +2,12 @@ from setuptools import setup,find_packages setup( - name = "Freenove_DHT", - version = "V1.0.0", - description = "Read DHT Sensor", - author = "Freenove", - url = "http://www.freenove.com", - license = " ", - packages = find_packages(), - scripts = ["Freenove_DHT.py"], - ) + name = "Freenove_DHT", + version = "V1.0.0", + description = "Read DHT Sensor", + author = "Freenove", + url = "http://www.freenove.com", + license = " ", + packages = find_packages(), + scripts = ["Freenove_DHT.py"], + ) diff --git a/Code/Python_Code/22.1.1_MatrixKeypad/Keypad.py b/Code/Python_Code/22.1.1_MatrixKeypad/Keypad.py index 5c0729b..12a944b 100644 --- a/Code/Python_Code/22.1.1_MatrixKeypad/Keypad.py +++ b/Code/Python_Code/22.1.1_MatrixKeypad/Keypad.py @@ -9,200 +9,200 @@ import RPi.GPIO as GPIO import time #class Key:Define some of the properties of Key class Key(object): - NO_KEY = '\0' - #Defines the four states of Key - IDLE = 0 - PRESSED = 1 - HOLD = 2 - RELEASED = 3 - #define OPEN and CLOSED - OPEN = 0 - CLOSED =1 - #constructor - def __init__(self): - self.kchar = self.NO_KEY - self.kstate = self.IDLE - self.kcode = -1 - self.stateChanged = False + NO_KEY = '\0' + #Defines the four states of Key + IDLE = 0 + PRESSED = 1 + HOLD = 2 + RELEASED = 3 + #define OPEN and CLOSED + OPEN = 0 + CLOSED =1 + #constructor + def __init__(self): + self.kchar = self.NO_KEY + self.kstate = self.IDLE + self.kcode = -1 + self.stateChanged = False class Keypad(object): - NULL = '\0' - LIST_MAX = 10 #Max number of keys on the active list. - MAPSIZE = 10 #MAPSIZE is the number of rows (times 16 columns) - bitMap = [0]*MAPSIZE - key = [Key()]*LIST_MAX - holdTime = 500 #key hold time - holdTimer = 0 - startTime = 0 - #Allows custom keymap, pin configuration, and keypad sizes. - def __init__(self,usrKeyMap,row_Pins,col_Pins,num_Rows,num_Cols): - GPIO.setmode(GPIO.BOARD) - self.rowPins = row_Pins - self.colPins = col_Pins - self.numRows = num_Rows - self.numCols = num_Cols - - self.keymap = usrKeyMap - self.setDebounceTime(10) - #Returns a single key only. Retained for backwards compatibility. - def getKey(self): - single_key = True - if(self.getKeys() and self.key[0].stateChanged and (self.key[0].kstate == self.key[0].PRESSED)): - return self.key[0].kchar - single_key = False - return self.key[0].NO_KEY - #Populate the key list. - def getKeys(self): - keyActivity = False - #Limit how often the keypad is scanned. - if((time.time() - self.startTime) > self.debounceTime*0.001): - self.scanKeys() - keyActivity = self.updateList() - self.startTime = time.time() - return keyActivity - #Hardware scan ,the result store in bitMap - def scanKeys(self): - #Re-intialize the row pins. Allows sharing these pins with other hardware. - for pin_r in self.rowPins: - GPIO.setup(pin_r,GPIO.IN,pull_up_down = GPIO.PUD_UP) - #bitMap stores ALL the keys that are being pressed. - for pin_c in self.colPins: - GPIO.setup(pin_c,GPIO.OUT) - GPIO.output(pin_c,GPIO.LOW) - for r in self.rowPins: #keypress is active low so invert to high. - self.bitMap[self.rowPins.index(r)] = self.bitWrite(self.bitMap[self.rowPins.index(r)],self.colPins.index(pin_c),not GPIO.input(r)) - #Set pin to high impedance input. Effectively ends column pulse. - GPIO.output(pin_c,GPIO.HIGH) - GPIO.setup(pin_c,GPIO.IN) - #Manage the list without rearranging the keys. Returns true if any keys on the list changed state. - def updateList(self): - anyActivity = False - kk = Key() - #Delete any IDLE keys - for i in range(self.LIST_MAX): - if(self.key[i].kstate == kk.IDLE): - self.key[i].kchar = kk.NO_KEY - self.key[i].kcode = -1 - self.key[i].stateChanged = False - # Add new keys to empty slots in the key list. - for r in range(self.numRows): - for c in range(self.numCols): - button = self.bitRead(self.bitMap[r],c) - keyChar = self.keymap[r * self.numCols +c] - keyCode = r * self.numCols +c - idx = self.findInList(keyCode) - #Key is already on the list so set its next state. - if(idx > -1): - self.nextKeyState(idx,button) - #Key is NOT on the list so add it. - if((idx == -1) and button): - for i in range(self.LIST_MAX): - if(self.key[i].kchar == kk.NO_KEY): #Find an empty slot or don't add key to list. - self.key[i].kchar = keyChar - self.key[i].kcode = keyCode - self.key[i].kstate = kk.IDLE #Keys NOT on the list have an initial state of IDLE. - self.nextKeyState(i,button) - break #Don't fill all the empty slots with the same key. - #Report if the user changed the state of any key. - for i in range(self.LIST_MAX): - if(self.key[i].stateChanged): - anyActivity = True - return anyActivity - #This function is a state machine but is also used for debouncing the keys. - def nextKeyState(self,idx, button): - self.key[idx].stateChanged = False - kk = Key() - if(self.key[idx].kstate == kk.IDLE): - if(button == kk.CLOSED): - self.transitionTo(idx,kk.PRESSED) - self.holdTimer = time.time() #Get ready for next HOLD state. - elif(self.key[idx].kstate == kk.PRESSED): - if((time.time() - self.holdTimer) > self.holdTime*0.001): #Waiting for a key HOLD... - self.transitionTo(idx,kk.HOLD) - elif(button == kk.OPEN): # or for a key to be RELEASED. - self.transitionTo(idx,kk.RELEASED) - elif(self.key[idx].kstate == kk.HOLD): - if(button == kk.OPEN): - self.transitionTo(idx,kk.RELEASED) - elif(self.key[idx].kstate == kk.RELEASED): - self.transitionTo(idx,kk.IDLE) - - def transitionTo(self,idx,nextState): - self.key[idx].kstate = nextState - self.key[idx].stateChanged = True - #Search by code for a key in the list of active keys. - #Returns -1 if not found or the index into the list of active keys. - def findInList(self,keyCode): - for i in range(self.LIST_MAX): - if(self.key[i].kcode == keyCode): - return i - return -1 - #set Debounce Time, The default is 50ms - def setDebounceTime(self,ms): - self.debounceTime = ms - #set HoldTime,The default is 500ms - def setHoldTime(self,ms): - self.holdTime = ms - # - def isPressed(keyChar): - for i in range(self.LIST_MAX): - if(self.key[i].kchar == keyChar): - if(self.key[i].kstate == self.self.key[i].PRESSED and self.key[i].stateChanged): - return True - return False - # - def waitForKey(): - kk = Key() - waitKey = kk.NO_KEY - while(waitKey == kk.NO_KEY): - waitKey = getKey() - return waitKey - - def getState(): - return self.key[0].kstate - # - def keyStateChanged(): - return self.key[0].stateChanged - - def bitWrite(self,x,n,b): - if(b): - x |= (1<>n)&1 == 1): - return True - else: - return False + NULL = '\0' + LIST_MAX = 10 #Max number of keys on the active list. + MAPSIZE = 10 #MAPSIZE is the number of rows (times 16 columns) + bitMap = [0]*MAPSIZE + key = [Key()]*LIST_MAX + holdTime = 500 #key hold time + holdTimer = 0 + startTime = 0 + #Allows custom keymap, pin configuration, and keypad sizes. + def __init__(self,usrKeyMap,row_Pins,col_Pins,num_Rows,num_Cols): + GPIO.setmode(GPIO.BOARD) + self.rowPins = row_Pins + self.colPins = col_Pins + self.numRows = num_Rows + self.numCols = num_Cols + + self.keymap = usrKeyMap + self.setDebounceTime(10) + #Returns a single key only. Retained for backwards compatibility. + def getKey(self): + single_key = True + if(self.getKeys() and self.key[0].stateChanged and (self.key[0].kstate == self.key[0].PRESSED)): + return self.key[0].kchar + single_key = False + return self.key[0].NO_KEY + #Populate the key list. + def getKeys(self): + keyActivity = False + #Limit how often the keypad is scanned. + if((time.time() - self.startTime) > self.debounceTime*0.001): + self.scanKeys() + keyActivity = self.updateList() + self.startTime = time.time() + return keyActivity + #Hardware scan ,the result store in bitMap + def scanKeys(self): + #Re-intialize the row pins. Allows sharing these pins with other hardware. + for pin_r in self.rowPins: + GPIO.setup(pin_r,GPIO.IN,pull_up_down = GPIO.PUD_UP) + #bitMap stores ALL the keys that are being pressed. + for pin_c in self.colPins: + GPIO.setup(pin_c,GPIO.OUT) + GPIO.output(pin_c,GPIO.LOW) + for r in self.rowPins: #keypress is active low so invert to high. + self.bitMap[self.rowPins.index(r)] = self.bitWrite(self.bitMap[self.rowPins.index(r)],self.colPins.index(pin_c),not GPIO.input(r)) + #Set pin to high impedance input. Effectively ends column pulse. + GPIO.output(pin_c,GPIO.HIGH) + GPIO.setup(pin_c,GPIO.IN) + #Manage the list without rearranging the keys. Returns true if any keys on the list changed state. + def updateList(self): + anyActivity = False + kk = Key() + #Delete any IDLE keys + for i in range(self.LIST_MAX): + if(self.key[i].kstate == kk.IDLE): + self.key[i].kchar = kk.NO_KEY + self.key[i].kcode = -1 + self.key[i].stateChanged = False + # Add new keys to empty slots in the key list. + for r in range(self.numRows): + for c in range(self.numCols): + button = self.bitRead(self.bitMap[r],c) + keyChar = self.keymap[r * self.numCols +c] + keyCode = r * self.numCols +c + idx = self.findInList(keyCode) + #Key is already on the list so set its next state. + if(idx > -1): + self.nextKeyState(idx,button) + #Key is NOT on the list so add it. + if((idx == -1) and button): + for i in range(self.LIST_MAX): + if(self.key[i].kchar == kk.NO_KEY): #Find an empty slot or don't add key to list. + self.key[i].kchar = keyChar + self.key[i].kcode = keyCode + self.key[i].kstate = kk.IDLE #Keys NOT on the list have an initial state of IDLE. + self.nextKeyState(i,button) + break #Don't fill all the empty slots with the same key. + #Report if the user changed the state of any key. + for i in range(self.LIST_MAX): + if(self.key[i].stateChanged): + anyActivity = True + return anyActivity + #This function is a state machine but is also used for debouncing the keys. + def nextKeyState(self,idx, button): + self.key[idx].stateChanged = False + kk = Key() + if(self.key[idx].kstate == kk.IDLE): + if(button == kk.CLOSED): + self.transitionTo(idx,kk.PRESSED) + self.holdTimer = time.time() #Get ready for next HOLD state. + elif(self.key[idx].kstate == kk.PRESSED): + if((time.time() - self.holdTimer) > self.holdTime*0.001): #Waiting for a key HOLD... + self.transitionTo(idx,kk.HOLD) + elif(button == kk.OPEN): # or for a key to be RELEASED. + self.transitionTo(idx,kk.RELEASED) + elif(self.key[idx].kstate == kk.HOLD): + if(button == kk.OPEN): + self.transitionTo(idx,kk.RELEASED) + elif(self.key[idx].kstate == kk.RELEASED): + self.transitionTo(idx,kk.IDLE) + + def transitionTo(self,idx,nextState): + self.key[idx].kstate = nextState + self.key[idx].stateChanged = True + #Search by code for a key in the list of active keys. + #Returns -1 if not found or the index into the list of active keys. + def findInList(self,keyCode): + for i in range(self.LIST_MAX): + if(self.key[i].kcode == keyCode): + return i + return -1 + #set Debounce Time, The default is 50ms + def setDebounceTime(self,ms): + self.debounceTime = ms + #set HoldTime,The default is 500ms + def setHoldTime(self,ms): + self.holdTime = ms + # + def isPressed(keyChar): + for i in range(self.LIST_MAX): + if(self.key[i].kchar == keyChar): + if(self.key[i].kstate == self.self.key[i].PRESSED and self.key[i].stateChanged): + return True + return False + # + def waitForKey(): + kk = Key() + waitKey = kk.NO_KEY + while(waitKey == kk.NO_KEY): + waitKey = getKey() + return waitKey + + def getState(): + return self.key[0].kstate + # + def keyStateChanged(): + return self.key[0].stateChanged + + def bitWrite(self,x,n,b): + if(b): + x |= (1<>n)&1 == 1): + return True + else: + return False -#######################EXAMPLE################################## +#######################EXAMPLE################################## ROWS = 4 COLS = 4 -keys = [ '1','2','3','A', - '4','5','6','B', - '7','8','9','C', - '*','0','#','D' ] +keys = [ '1','2','3','A', + '4','5','6','B', + '7','8','9','C', + '*','0','#','D' ] rowsPins = [12,16,18,22] -colsPins = [19,15,13,11] +colsPins = [19,15,13,11] def loop(): - keypad = Keypad(keys,rowsPins,colsPins,ROWS,COLS) - keypad.setDebounceTime(50) - while(True): - key = keypad.getKey() - if(key != keypad.NULL): - print ("You Pressed Key : %c "%(key) ) - + keypad = Keypad(keys,rowsPins,colsPins,ROWS,COLS) + keypad.setDebounceTime(50) + while(True): + key = keypad.getKey() + if(key != keypad.NULL): + print ("You Pressed Key : %c "%(key) ) + if __name__ == '__main__': # Program start from here - print ("Program is starting ... ") - try: - loop() - except KeyboardInterrupt: # When 'Ctrl+C' is pressed, the child program destroy() will be executed. - pass - GPIO.cleanup() - - - - + print ("Program is starting ... ") + try: + loop() + except KeyboardInterrupt: # When 'Ctrl+C' is pressed, the child program destroy() will be executed. + pass + GPIO.cleanup() + + + + diff --git a/Code/Python_Code/23.1.1_SenseLED/SenseLED.py b/Code/Python_Code/23.1.1_SenseLED/SenseLED.py index bc9fe55..8f816a3 100644 --- a/Code/Python_Code/23.1.1_SenseLED/SenseLED.py +++ b/Code/Python_Code/23.1.1_SenseLED/SenseLED.py @@ -11,27 +11,27 @@ ledPin = 12 # define ledPin sensorPin = 11 # define sensorPin def setup(): - GPIO.setmode(GPIO.BOARD) # use PHYSICAL GPIO Numbering - GPIO.setup(ledPin, GPIO.OUT) # set ledPin to OUTPUT mode - GPIO.setup(sensorPin, GPIO.IN) # set sensorPin to INPUT mode + GPIO.setmode(GPIO.BOARD) # use PHYSICAL GPIO Numbering + GPIO.setup(ledPin, GPIO.OUT) # set ledPin to OUTPUT mode + GPIO.setup(sensorPin, GPIO.IN) # set sensorPin to INPUT mode def loop(): - while True: - if GPIO.input(sensorPin)==GPIO.HIGH: - GPIO.output(ledPin,GPIO.HIGH) # turn on led - print ('led turned on >>>') - else : - GPIO.output(ledPin,GPIO.LOW) # turn off led - print ('led turned off <<<') + while True: + if GPIO.input(sensorPin)==GPIO.HIGH: + GPIO.output(ledPin,GPIO.HIGH) # turn on led + print ('led turned on >>>') + else : + GPIO.output(ledPin,GPIO.LOW) # turn off led + print ('led turned off <<<') def destroy(): - GPIO.cleanup() # Release GPIO resource + GPIO.cleanup() # Release GPIO resource if __name__ == '__main__': # Program entrance - print ('Program is starting...') - setup() - try: - loop() - except KeyboardInterrupt: # Press ctrl-c to end the program. - destroy() + print ('Program is starting...') + setup() + try: + loop() + except KeyboardInterrupt: # Press ctrl-c to end the program. + destroy() diff --git a/Code/Python_Code/24.1.1_UltrasonicRanging/UltrasonicRanging.py b/Code/Python_Code/24.1.1_UltrasonicRanging/UltrasonicRanging.py index 40406ad..c21def7 100644 --- a/Code/Python_Code/24.1.1_UltrasonicRanging/UltrasonicRanging.py +++ b/Code/Python_Code/24.1.1_UltrasonicRanging/UltrasonicRanging.py @@ -53,4 +53,4 @@ if __name__ == '__main__': # Program entrance GPIO.cleanup() # release GPIO resource - + diff --git a/Code/Python_Code/27.2.1_LightWater03/LightWater03.py b/Code/Python_Code/27.2.1_LightWater03/LightWater03.py index fc3b9ee..cf4fe9d 100644 --- a/Code/Python_Code/27.2.1_LightWater03/LightWater03.py +++ b/Code/Python_Code/27.2.1_LightWater03/LightWater03.py @@ -12,58 +12,58 @@ LSBFIRST = 1 MSBFIRST = 2 # define the pins connect to 74HC595 -dataPin = 11 # DS Pin of 74HC595(Pin14) -latchPin = 13 # ST_CP Pin of 74HC595(Pin12) -clockPin = 15 # SH_CP Pin of 74HC595(Pin11) +dataPin = 11 # DS Pin of 74HC595(Pin14) +latchPin = 13 # ST_CP Pin of 74HC595(Pin12) +clockPin = 15 # SH_CP Pin of 74HC595(Pin11) # Define an array to store the pulse width of LED pluseWidth = [0,0,0,0,0,0,0,0,64,32,16,8,4,2,1,0,0,0,0,0,0,0,0] def setup(): - GPIO.setmode(GPIO.BOARD) # use PHYSICAL GPIO Numbering - GPIO.setup(dataPin, GPIO.OUT) # set dataPin to OUTPUT mode - GPIO.setup(latchPin, GPIO.OUT) # set latchPin to OUTPUT mode - GPIO.setup(clockPin, GPIO.OUT) # set clockPin to OUTPUT mode - + GPIO.setmode(GPIO.BOARD) # use PHYSICAL GPIO Numbering + GPIO.setup(dataPin, GPIO.OUT) # set dataPin to OUTPUT mode + GPIO.setup(latchPin, GPIO.OUT) # set latchPin to OUTPUT mode + GPIO.setup(clockPin, GPIO.OUT) # set clockPin to OUTPUT mode + def shiftOut(dPin,cPin,order,val): - for i in range(0,8): - GPIO.output(cPin,GPIO.LOW); - if(order == LSBFIRST): - GPIO.output(dPin,(0x01&(val>>i)==0x01) and GPIO.HIGH or GPIO.LOW) - elif(order == MSBFIRST): - GPIO.output(dPin,(0x80&(val<>i)==0x01) and GPIO.HIGH or GPIO.LOW) + elif(order == MSBFIRST): + GPIO.output(dPin,(0x80&(val< moveSpeed): # control speed - lastMove = time.time() # Record the time point of the move - index +=1 # move to next - if(index > 15): # index to 0 - index = 0 - - for i in range(0,64): # The cycle of PWM is 64 cycles - data = 0 - for j in range(0,8): #Calculate the output state of this loop - if(i < pluseWidth[j+index]): #Calculate the LED state according to the pulse width - data |= 1< moveSpeed): # control speed + lastMove = time.time() # Record the time point of the move + index +=1 # move to next + if(index > 15): # index to 0 + index = 0 + + for i in range(0,64): # The cycle of PWM is 64 cycles + data = 0 + for j in range(0,8): #Calculate the output state of this loop + if(i < pluseWidth[j+index]): #Calculate the LED state according to the pulse width + data |= 1<