Replace tab with space

Replace all tab with space, to adapt to different editors.
This commit is contained in:
Suhayl
2020-01-13 11:23:16 +08:00
parent abb1b0907a
commit 68793bed42
29 changed files with 819 additions and 819 deletions
+1 -1
View File
@@ -7,6 +7,6 @@
########################################################################
def Hello():
print('Hello World!')
print('Hello World!')
Hello()
+18 -18
View File
@@ -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()
+1 -1
View File
@@ -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 <<<')
+19 -19
View File
@@ -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()
@@ -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
@@ -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
@@ -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()
@@ -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)
@@ -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()
@@ -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()
+13 -13
View File
@@ -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()
@@ -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
+31 -31
View File
@@ -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()
+22 -22
View File
@@ -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()
+29 -29
View File
@@ -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()
+29 -29
View File
@@ -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()
@@ -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()
+35 -35
View File
@@ -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()
@@ -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):
@@ -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)==0x80) and GPIO.HIGH or GPIO.LOW)
GPIO.output(cPin,GPIO.HIGH);
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)==0x80) and GPIO.HIGH or GPIO.LOW)
GPIO.output(cPin,GPIO.HIGH);
def loop():
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)
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()
@@ -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)==0x80) and GPIO.HIGH or GPIO.LOW)
GPIO.output(cPin,GPIO.HIGH);
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)==0x80) and GPIO.HIGH or GPIO.LOW)
GPIO.output(cPin,GPIO.HIGH);
def loop():
while True:
for i in range(0,len(num)):
GPIO.output(latchPin,GPIO.LOW)
shiftOut(dataPin,clockPin,MSBFIRST,num[i]) # Send serial data to 74HC595
GPIO.output(latchPin,GPIO.HIGH)
time.sleep(0.5)
for i in range(0,len(num)):
GPIO.output(latchPin,GPIO.LOW)
shiftOut(dataPin,clockPin,MSBFIRST,num[i]&0x7f) # Use "&0x7f" to display the decimal point.
GPIO.output(latchPin,GPIO.HIGH)
time.sleep(0.5)
while True:
for i in range(0,len(num)):
GPIO.output(latchPin,GPIO.LOW)
shiftOut(dataPin,clockPin,MSBFIRST,num[i]) # Send serial data to 74HC595
GPIO.output(latchPin,GPIO.HIGH)
time.sleep(0.5)
for i in range(0,len(num)):
GPIO.output(latchPin,GPIO.LOW)
shiftOut(dataPin,clockPin,MSBFIRST,num[i]&0x7f) # Use "&0x7f" to display the decimal point.
GPIO.output(latchPin,GPIO.HIGH)
time.sleep(0.5)
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()
@@ -37,13 +37,13 @@ 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)
mcp = PCF8574_GPIO(PCF8574_address)
except:
try:
mcp = PCF8574_GPIO(PCF8574A_address)
except:
print ('I2C Address Error !')
exit(1)
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)
+64 -64
View File
@@ -7,73 +7,73 @@
import smbus
import time
class PCF8574_I2C(object):
OUPUT = 0
INPUT = 1
def __init__(self,address):
# Note you need to change the bus number to 0 if running on a revision 1 Raspberry Pi.
self.bus = smbus.SMBus(1)
self.address = address
self.currentValue = 0
self.writeByte(0) #I2C test.
def readByte(self):#Read PCF8574 all port of the data
#value = self.bus.read_byte(self.address)
return self.currentValue#value
def writeByte(self,value):#Write data to PCF8574 port
self.currentValue = value
self.bus.write_byte(self.address,value)
OUPUT = 0
INPUT = 1
def __init__(self,address):
# Note you need to change the bus number to 0 if running on a revision 1 Raspberry Pi.
self.bus = smbus.SMBus(1)
self.address = address
self.currentValue = 0
self.writeByte(0) #I2C test.
def readByte(self):#Read PCF8574 all port of the data
#value = self.bus.read_byte(self.address)
return self.currentValue#value
def writeByte(self,value):#Write data to PCF8574 port
self.currentValue = value
self.bus.write_byte(self.address,value)
def digitalRead(self,pin):#Read PCF8574 one port of the data
value = readByte()
return (value&(1<<pin)==(1<<pin)) and 1 or 0
def digitalWrite(self,pin,newvalue):#Write data to PCF8574 one port
value = self.currentValue #bus.read_byte(address)
if(newvalue == 1):
value |= (1<<pin)
elif (newvalue == 0):
value &= ~(1<<pin)
self.writeByte(value)
def digitalRead(self,pin):#Read PCF8574 one port of the data
value = readByte()
return (value&(1<<pin)==(1<<pin)) and 1 or 0
def digitalWrite(self,pin,newvalue):#Write data to PCF8574 one port
value = self.currentValue #bus.read_byte(address)
if(newvalue == 1):
value |= (1<<pin)
elif (newvalue == 0):
value &= ~(1<<pin)
self.writeByte(value)
def loop():
mcp = PCF8574_I2C(0x27)
while True:
#mcp.writeByte(0xff)
mcp.digitalWrite(3,1)
print ('Is 0xff? %x'%(mcp.readByte()))
time.sleep(1)
mcp.writeByte(0x00)
#mcp.digitalWrite(7,1)
print ('Is 0x00? %x'%(mcp.readByte()))
time.sleep(1)
mcp = PCF8574_I2C(0x27)
while True:
#mcp.writeByte(0xff)
mcp.digitalWrite(3,1)
print ('Is 0xff? %x'%(mcp.readByte()))
time.sleep(1)
mcp.writeByte(0x00)
#mcp.digitalWrite(7,1)
print ('Is 0x00? %x'%(mcp.readByte()))
time.sleep(1)
class PCF8574_GPIO(object):#Standardization function interface
OUT = 0
IN = 1
BCM = 0
BOARD = 0
def __init__(self,address):
self.chip = PCF8574_I2C(address)
self.address = address
def setmode(self,mode):#PCF8574 port belongs to two-way IO, do not need to set the input and output model
pass
def setup(self,pin,mode):
pass
def input(self,pin):#Read PCF8574 one port of the data
return self.chip.digitalRead(pin)
def output(self,pin,value):#Write data to PCF8574 one port
self.chip.digitalWrite(pin,value)
OUT = 0
IN = 1
BCM = 0
BOARD = 0
def __init__(self,address):
self.chip = PCF8574_I2C(address)
self.address = address
def setmode(self,mode):#PCF8574 port belongs to two-way IO, do not need to set the input and output model
pass
def setup(self,pin,mode):
pass
def input(self,pin):#Read PCF8574 one port of the data
return self.chip.digitalRead(pin)
def output(self,pin,value):#Write data to PCF8574 one port
self.chip.digitalWrite(pin,value)
def destroy():
bus.close()
bus.close()
if __name__ == '__main__':
print ('Program is starting ... ')
try:
loop()
except KeyboardInterrupt:
destroy()
print ('Program is starting ... ')
try:
loop()
except KeyboardInterrupt:
destroy()
+96 -96
View File
@@ -1,7 +1,7 @@
#!/usr/bin/env python3
#############################################################################
# Filename : Freenove_DHT.py
# Description : DHT Temperature & Humidity Sensor library for Raspberry
# Description : DHT Temperature & Humidity Sensor library for Raspberry
# Author : freenove
# modification: 2018/08/03
########################################################################
@@ -9,100 +9,100 @@ import RPi.GPIO as GPIO
import time
class DHT(object):
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
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()
+9 -9
View File
@@ -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"],
)
+187 -187
View File
@@ -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)
else:
x &=(~(1<<n))
return x
def bitRead(self,x,n):
if((x>>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)
else:
x &=(~(1<<n))
return x
def bitRead(self,x,n):
if((x>>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()
+17 -17
View File
@@ -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()
@@ -53,4 +53,4 @@ if __name__ == '__main__': # Program entrance
GPIO.cleanup() # release GPIO resource
@@ -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)==0x80) and GPIO.HIGH or GPIO.LOW)
GPIO.output(cPin,GPIO.HIGH);
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)==0x80) and GPIO.HIGH or GPIO.LOW)
GPIO.output(cPin,GPIO.HIGH);
def outData(data):
GPIO.output(latchPin,GPIO.LOW)
shiftOut(dataPin,clockPin,LSBFIRST,data)
GPIO.output(latchPin,GPIO.HIGH)
GPIO.output(latchPin,GPIO.LOW)
shiftOut(dataPin,clockPin,LSBFIRST,data)
GPIO.output(latchPin,GPIO.HIGH)
def loop():
moveSpeed = 0.1 # moveSpeed works like a relay, the larger, the slower
index = 0 # array index starts from 0
lastMove = time.time() # record the start time
while True:
if(time.time() - lastMove > 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<<j # Calculate the data
outData(data) # Send the data to 74HC595
moveSpeed = 0.1 # moveSpeed works like a relay, the larger, the slower
index = 0 # array index starts from 0
lastMove = time.time() # record the start time
while True:
if(time.time() - lastMove > 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<<j # Calculate the data
outData(data) # Send the data to 74HC595
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()