Led switch on/off on button press

Hi,
two posts ago i talked about switch on/off a LED by pressing on keyboard.
Looking into Raspberry Pi box i find a switch. So it's time to understand how it works.

What i want to do is switch on/off a LED by prassing switch button

First of all i want to understand why there are four pins on switch...


seems that pins A and D are the same. Same story for pins B and C. So all you need is to connect only two of this pins.. (if someone can explain better and let me understand please write me!!!)

What i need:

  • a LED
  • one switch button
  • two 330 ohms resistor
  • 1 coffee

As usually we need to connect ground pin from raspberry pi to blue track of our breadboard. Then place the switch button on breadboard and connect pin 23 from raspberry pi to the track of one of switch's pin. Then place a resistor to connect the other switch's pin and the blue track from breadboard.
Next step is to place e LED on breadboard and connect pin 24 of raspberry to ANODE (positive pin) of our LED, then use the other resistor to connect CATHODE (negative pin) of the same LED to the negative blue track of breadboard. Now all components should be placed.


Ok the schema is this:




from schema to reality



 (i love jamiroquai)

then it's time to see the code. For this project i referred to this code: http://razzpisampler.oreilly.com/ch07.html

import RPi.GPIO as GPIO
import time

GPIO.setmode(GPIO.BCM)

GPIO.setup(23, GPIO.IN, pull_up_down=GPIO.PUD_UP)

GPIO.setup(24, GPIO.OUT)
GPIO.output(24, GPIO.LOW)

check_state = False


try:
    while True:
        input_state = GPIO.input(23)
        if input_state == False:
        GPIO.output(24, GPIO.HIGH)   
        else:
        GPIO.output(24, GPIO.LOW)

except KeyboardInterrupt:
    GPIO.cleanup()


this row is important GPIO.setup(23, GPIO.IN, pull_up_down=GPIO.PUD_UP)
we are telling here to enable pin 23 to intercept the pull-up (3.3 v) or pull-down (0 v) state... so if input state of pin 23 is false then turn LED  on else turn LED off



and this is the result:


Commenti