Publ ished: 20 .02.2019 Copyright by Joy-IT 9
Joy-Pi
In our examples we use Python language to control the GPIO pins. In Python there is a library called
"RPi.GPIO". This is a library that helps to control the pins programmacally with Python.
Take a look at the following example and the comments in the code to beer understand how it works.
The rst step will be to import the library by typing the command "RPi.GPIO as GPIO", then the "me"
library comes with the command "import me".
Then we set the GPIO mode to GPIO.BOARD. We declare the input pin as pin number 11 for our example
and the output pin as pin 12 (the input is the touch sensor and the output is the buzzer). We send a signal
to the output pin, wait 1 second and then turn it o. Then, to conrm the input, we go through a loop
unl the GPIO.input input signal is received. We print "Input Given" to make sure that the click was
conrmed, clean up the GPIO with GPIO.cleanup () and nish the script.
To learn more about the purpose and use of GPIO, we recommend that you read the ocial
documentaon on the topic of GPIO pins wrien by the Raspberry Pi foundaon.
hps://www.raspberrypi.org/documentaon/usage/gpio/
import RPi.GPIO as GPIO
import time #import lybraries
import signal
TOUCH = 11 #Declaring variables
BUZZER = 12 #and connecting pins
def setup_gpio(): #Definition of in and outputs
GPIO.setmode(GPIO.BOARD)
GPIO.setup(TOUCH, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(BUZZER, GPIO.OUT)
def do_smt(channel): #class for buzzer output and
print("Touch detected") #detected touch
GPIO.output(BUZZER, GPIO.HIGH) #Signal output
time.sleep (1) #Wait 1 second
GPIO.output(BUZZER, GPIO.LOW) #Stop signal Output
def main():
setup_gpio()
try: #Checking if touch is detected
GPIO.add_event_detect(TOUCH, GPIO.FALLING, callback=do_smt, bouncetime=200)
signal.pause()
except KeyboardInterrupt: #CTRL+C is closing the script
pass
finally:
GPIO.cleanup()
if __name__ == '__main__':
main()