This tutorial will introduce how to use the push button switch to turn on and turn off the buzzer through Raspberry Pi.
We provide two coding examples: Initiative GPIO mode and Passive GPIO mode.:
In Initiative GPIO mode, raspberry pi will keep scanning GPIO port, once bush button signal is detected, buzzer will beep. This mode will occupy a lot of CPU resources and therefore is not a good coding example.
In Passive GPIO mode, push button signal will trigger an CPU interrupt and then make the buzzer beep. Thus CPU resources are only occupied when button switch is pushed. During other time, CPU resources can be used by other programs. This is a better coding example than Initiative GPIO mode.
Active Buzzer x1
Push button x1
10K Resistor x1
|several jumper wires|
(1)Before running Python code, the GPIO lirary needs to be installed on the Raspberry Pi. Open the termial and type the following code to install GPIO library (if you have done, please skip this step.) Please make sure the raspberry pi is connected to internet.
sudo apt-get update
sudo apt-get install python-dev
3)Install python-pip(python-pip: the Python package Index)
sudo apt-get install python-pip
sudo pip install rpi.gpio
You can use a screen or SSH to access your Raspberry Pi to edit code.
1)Creat a file named led.py in any directory (for example:/home/pi/）
sudo touch button_buzzer.py
2)Open file button_buzzer.py
sudo nano button_buzzer.py
3)Copy below code to button_buzzer.py file:
Initiative GPIO mode：
import RPi.GPIO as GPIO import time GPIO.setmode(GPIO.BCM) Button_pin = 25 #button is connected to GPIO 25 Buzzer_pin = 19 #buzzer is connected to GPIO 19 # GPIO 25 set up as input. It is pulled up to stop false signals GPIO.setup(Button_pin, GPIO.IN, pull_up_down=GPIO.PUD_UP) #GPIO 19 set up as output GPIO.setup(Buzzer_pin,GPIO.OUT) try: while True: time.sleep(0.01) if(GPIO.input(Button_pin)==0): print "Button is pressed!" print "Buzzer will be turn on!" GPIO.output(Buzzer_pin,True) else: GPIO.output(Buzzer_pin,False) except KeyboardInterrupt: pass GPIO.cleanup()
import RPi.GPIO as GPIO import time GPIO.setmode(GPIO.BCM) Button_pin = 25 Buzzer_pin = 19 GPIO.setup(Button_pin, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) GPIO.setup(Buzzer_pin, GPIO.OUT) BuzzerStatus = True def my_callback(channel): print("button pressed!") global BuzzerStatus BuzzerStatus = not BuzzerStatus if BuzzerStatus: GPIO.output(Buzzer_pin, GPIO.LOW) pass else: GPIO.output(Buzzer_pin, GPIO.HIGH) pass pass GPIO.add_event_detect(Button_pin, GPIO.FALLING, callback=my_callback,bouncetime=200) while True: try: print("I'm working...") time.sleep(5) pass except KeyboardInterrupt: break pass pass GPIO.cleanup()
Select mode and copy the corresponding code.
4)After finish the code, press “Ctrl X” and“Y” to save the code.
5)Run the code:
sudo python ./button_buzzer.py