Switch on/off a led by button press

Ok, the story is this: my brother gave me a Raspberry B+. I don't know nothing about Raspberry, eletronic, python (and my english sucks). Maybe one or two beers can make me do something good..

Let's go.

This isn't my first experiment with Raspberry but this one seems to work...

What i want to do is turn on/off LEDs by pushing buttons on my keyboard

What i need:

  • Raspberry 
  • 2 LEDs 
  • 1 beer

This is the scheme of the project:


I connect male-female brown cable (i don't know the correct name...) from ground pin (on raspberry) to the negative track on breadboard.

Then i use GPIO port 23 and 24 and connect them on breadboard on positive LED poles (or legs ??) .Then i put  2 resistors from negative LED poles (legs?) to negative track on breadboard
From schema to real:



ok now open youtube and copy this link https://www.youtube.com/watch?v=KV2ixprDrK8

well, now enter into your Raspberry. We  need Xorg (the desktop interface) because we need a window to capture the button press event. I use Remmina to connect my ubuntu to raspberry with RDP (Remote Desktop Protocol).

Create a new python script (for example led_button.py) with this code:

import Tkinter as tk             # for window
import time                           # for time duration of led ligth
import RPi.GPIO as GPIO     # GPIO library

GPIO.setmode(GPIO.BCM)

GPIO.setup(24, GPIO.OUT)   
GPIO.output(24, GPIO.LOW)    # switch off led on port 24

GPIO.setup(23, GPIO.OUT)
GPIO.output(23, GPIO.LOW)     # turn off led on port 23

def keypress(event):
        if event.keysym == 'Escape':         # With ESC button  we close the window
        GPIO.cleanup()
                root.destroy()                          # exit from this script
        x = event.char
        if x == "w":                                           # on W button press
                print "Hai premuto il tasto w"
        GPIO.output(23, GPIO.HIGH)               # turn on led on 23
        time.sleep(0.5)
        GPIO.output(23, GPIO.LOW)                 # turon off led on 23
        elif x == "s":
                print "Hai premuto il tasto s"        # on S button press
        GPIO.output(24, GPIO.HIGH)                # turn on led on 24
        time.sleep(0.5)
        GPIO.output(24, GPIO.LOW)                 # turn off led on 24
        else:
                print x


root = tk.Tk()
print "Press a key (Escape to exit)"
root.bind_all('<Key>', keypress)

#root.withdraw()
root.mainloop()                                                # wating for some input



and finally that's how this thing works:



fiuuu ... seems to work...

Commenti