The code is exactly the same to using button to control LED logically. You can try to use the PNP transistor to
achieve the function of his circuit once again.
Python Code 6.1.1 Doorbell
First observe the project result, then analyze the code.
1. Use cd command to enter 06.1.1_Doorbell directory of Python code.
cd ~/Freenove_Ultimate_Starter_Kit_for_Raspberry_Pi/Code/Python_Code/06.1.1_Doorbell
2. Use python command to execute python code “Doorbell.py”.
python Doorbell.py
After the program is executed, press the button, then buzzer sounds. And when the button is released, the
buzzer will stop sounding.
The following is the program code:
im port RPi. GPIO as GPIO
buzzerPin = 11 # define the buzzerPin
buttonPin = 12 # define the buttonPin
def setup():
p rint ('Program is starting...')
GPIO. setmode(GPIO.BOARD) # Numbers GPIOs by physical location
GPIO. setup(buzzerPin, GPIO. OUT) # Set buzzerPin's mode is output
GPIO. setup(buttonPin, GPIO. IN, pull_up_down=GPIO.PUD_UP) # Set buttonPin's mode is
input, and pull up to high level(3.3V)
def loop():
w hile Tr ue:
if GPIO.input(buttonPin)==GPIO.LOW:
GPIO.output(buzzerPin,GPIO.HIGH)
print ('buzzer on ...')
else :
GPIO.output(buzzerPin,GPIO.LOW)
print ('buzzer off ...')
def destroy():
GPIO. output(buzzerPin, GPIO. LOW) # buzzer off
GPIO. cleanup() # Release resource
if __name__ == '__main__': # Program start from here
setup()
try:
loop()