In our first attempt at doing the Traffic Lights, we are getting our supply for the LEDs from the GPIO pins, there are two issues with doing this:
What we want to do is to drive the LEDs from the same 5V rail that is powering the Pico (or whatever board you are using). To turn on the LEDs (and protect the GPIO pins from over-current) we can use some Transistors. Transistors are generally associated with amplifier circuits, but you can use them as a simple switch.
See below for a diagram of what we want to achieve.
Below is a view in a more circuit diagram format.
This is just the Red LED circuit, the Amber and Green are identical except for the LED Colour and they come from different GPIO Pins.
The Transistor has 3 Pins:
The amount of current that each LED gets is control by Ohms Law. So the current limiting resistor is calculated using the Voltage (5v) and the required current (20mA).
The Resistance (R) is the Voltage (V) divided by Current (A) so R=V/I
So 5V divided by 20mA (0.02) = 250 (Ohms), closest resistor to this would be a 220 Ohm.
If you connect your Traffic Light LEDs using this circuit, rather than directly to the GPIO pins you will:
Other than this connection difference, the rest of the project is the same, we can use the same GPIO Pins and the Micro Python code remains unchanged.
For the LED, I wanted to supply 20mA to get some nice illumination, so this means I need to current limit the supply to 20mA, but we also need to turn on the Transistor enough to get those 20mA through the Transistor.
The LED is quite simple, you can account for the voltage drop across the LED and Transistor, but you can also ignore this, as it makes little difference to the resistor.
For the Transistor it is a bit more complicated, you need to look at the spec sheet for the transistor to understand it's hFE (how much input current drives how much output current).
To allow 20mA through the Transistor, in this example with this NPN Transistor we need R=1.2K Ohms.
My first calculation worked on only needing 10mA, and that came out at 2.2K Ohms.
Compared to running the LEDs at 3.3v directly from the Micro Controller, you will see now your LEDs are much brighter.