Python Code 14.1.1 Relay
First observe the project result, and then analyze the code.
1. Use cd command to enter 14.1.1_Relay directory of Python code.
cd ~/Freenove_Ultimate_Starter_Kit_for_Raspberry_Pi/Code/Python_Code/14.1.1_Relay
2. Use python command to execute code "Relay.py".
python Relay.py
After the program is executed, press the button, then the relay is opened, the Motor starts to rotate and LED
is turned on. If you press the button again, the relay is closed, the Motor stops running, and the LED is turned
off.
The following is the program code:
im port RPi. GPIO as GPIO
im port time
relayPin = 11 # define the relayPin
buttonPin = 12 # define the buttonPin
debounceTime = 50
def setup():
p rint ('Program is starting...')
GPIO. setmode(GPIO.BOARD) # Numbers GPIOs by physical location
GPIO. setup(relayPin, GPIO. OUT) # Set relayPin's mode is output
GPIO. setup(buttonPin, GPIO. IN)
def loop():
relayState = False
lastChangeTime = round( time.time()*1000)
buttonState = GPIO.HIGH
lastButtonState = GPIO. HIGH
reading = GPIO. HIGH
w hile Tr ue:
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 ... ")
e l se :