Controlling LED with Raspberry Pi
LED is shorter for Light Emitting Diode. It requires current 5-20 mA and voltage 3.3 V to turn the LED on.
To protect the LED, we also need to add a resistor to our setup. The resistor should be: R = U/I = 3.3V/~15mA = 220 Ohm.
Wire the LED setup according to picture below.
Physical PIN 17 (3.3 V) ----- Resistor (220 ohm) ----- LED ----- PIN 29 (GPIO 21)
Remark: LED can as well be powered from PIN 1, which is also 3.3 V power supply and you can use almost any other GPIO pin than 29 (GPIO 21).
Now we need software to drive the LED. We'll prepare two Python scripts, one that turns LED on, the other that turns LED off.
This is the script to turn LED on:
#!/bin/python
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BOARD)
GPIO.setup(29,GPIO.OUT)
GPIO.output(29,False)
This is the script to turn LED off:
#!/bin/python
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BOARD)
GPIO.setup(29,GPIO.OUT)
GPIO.output(29,True)
GPIO.cleanup
A few remarks:
- set GPIO in GPIO.BOARD mode, then you can address pins by their physical position instead of GPIO or BCM labels
- the turn off script releases all GPIO resources by calling GPIO.cleanup method
- this is also valid: True=GPIO.HIGH and False=GPIO.LOW
Execute the first python script to see if LED turns on:
$ sudo python turnOn.py
Execute the second python script to see if LED turns off:
$ sudo python turnOff.py