www.joy-it.net
Pascalstr. 8 47506 Neukirchen-Vluyn
In our examples, we use the programming language
Python
to control
the GPIO pins. In Python exists a library which is known as RPi.GPIO. This
library is necessary to control the pins with Python.
The following example and comments in the code should help you to un-
derstand the program.
First, you have to import the required library with the import command.
The variable TOUCH and BUZZER references to the pins of the touch
sensor and the buzzer. Aerwards, you define the connection with
GPIO.setmode(GPIO.BOARD)
as the used GPIO schemata. As the next
step, you configurate the earlier set variables with the command
GPIO.setup()
as input or rather output. Pin 11 (TOUCH) is set as input and
pin 12 (BUZZER) as output.
The main function queries if a touch has been detected by the touch sen-
sor. If this is the case, the function do_smth will be executed.
This function prints the text
Touch detected
and sets the buzzer
HIGH
and one second later
LOW
again(buzzer will sum one second):
import RPi.GPIO as GPIO
import time #import libraries
import signal
TOUCH = 11 #declaring variables
BUZZER = 12
def setup_gpio(): #definition of inputs 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): #function for the output if touch was dected
print(“Touch detected“) #and output that touch was detected
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)
except KeyboardInterrupt: #CTRL + C exists the script
pass
finally:
GPIO.cleanup()
if _name_==‘_main_‘:
main()
To learn more about the purpose and usage of GPIO, we recommend that
you read the oicial documentation on that topic of GPIO pins which is
written by the Raspberry Pi Foundation.
https://www.raspberrypi.org/documentation/usage/gpio/