Sensing Input – Raspberry Pi

This time we’re going to detect an input signal that comes into the pin of Raspberry Pi.

Few items we’re gonna need :

  • Momentary Push Button
  • 2 Female to Male Jumper Cables
  • Raspberry Pi and required peripherals

We’ll connect them all,

  1. Stick the button in the middle of the board
  2. Connect one leg of the button to the GPIO pin 17 using the red jumper cable
  3. Connect the other leg of the button the GND pin using the black jumper cable

 

We need to do a small programming using python to check the sensing. Start Python 3, and create a new file. Put below codes in the file and save it as button.py.

##import Button from gpiozero library and import pause signal library
from gpiozero import Button 
from signal import pause 
## the button is connected to pin 17
button = Button(17) 

## wait for button press, then print
button.wait_for_press()
print(“Button is pressed”)

pause() 

Press F5 to execute the program.

Yea, button press is detected.

Now we are going to introduce a led to the board. I will move the button to pin 2 and connect the led to pin 8.

We’ll modify the coding to incorporate the led,

##import Button and LED from gpiozero library and import pause signal library
from gpiozero import Button, LED
from signal import pause
##the button is connected to pin 2
##led is connected to pi 8
button = Button(2)
led = LED(8)
##when button is pressed, the led will blink
button.when_pressed = led.blink
button.when_released = led.off

pause() 

Now press F5 to execute the script. And press the button to see how the led blinks.