raspberry pi

Raspberry Pi LED control using different techniques, Complete Guide

Raspberry Pi Light Emitting Diodes (LEDs):

As a beginner you can start with the control of light-emitting diodes (LEDs) since these are easy to use and provide direct visual feedback. Light emitting diodes are an ideal starting point for electronics novices and lead to the first sense of achievement with little effort. The easiest way to do this is with a breadboard, i.e. without a soldering iron.

So, in this article, I will explain how to control the LEDs using transistors, Darlington Transistors “ULN2803”, and a push button.  In this tutorial, I will also explain how to control the brightness of an LED using PWM “Pulse Width Modulation”. I will also explain how to control RGB LEDs.

Without any further delay, let’s get started!!!

Amazon Purchase Links:

Raspberry Pi

raspberry pi 4 4gb kit

Wireless Keyboard and Mouse for raspberry pi:

Night vision Camera for Raspberry Pi:

Oled HDMI touch display for raspberry pi:

TOP10 Best Raspberry Pi Kits

Other Tools and Components:

Super Starter kit for Beginners

Digital Oscilloscopes

Variable Supply

Digital Multimeter

Soldering iron kits

PCB small portable drill machines

*Please Note: These are affiliate links. I may make a commission if you buy the components through these links. I would appreciate your support in this way!


LED in continuous operation

As a Hello World! Project, so to speak, we show you here how to use your Raspberry Pi switch an LED on and off. The LED thus serves as a signal transmitter. she shows Whether your software is working properly and the program is working the way you do wish it. But first we want to connect the LED directly to the 3.3 V power supply, so that it always shines. In the data sheet of your LED you can read how big it is, the voltage drop across the diode, and what current the diode expects – e.g. 2V and 10mA. The size of the required series resistor results from the residual voltage 3.3 V – 2 V = 1.3 V and the formula R = U / I = 1.3 V / 10mA with 130. If you use the next largest resistance you can find nothing can happen. The LED then shines correspondingly less brightly.

Since the same circuit layout later has a GPIO pin with a maximum If output current is to be controlled by 8 mA, it is better to equal the resistor to be dimensioned accordingly larger (1.3 V / 8 mA = 163 ). We have for ours Experiments with 330-Resistors worked, bringing a current of 4 mA results. Now build the circuit on a breadboard and connect the light-emitting diode with pins 1 (3.3 V) and 25 (GND) of the Raspberry Pi (see Figure1 and Figure2). Pay attention to the correct polarity of the LED. The longer wire of the LED connects the anode (plus), the shorter the cathode (minus).

Raspberry Pi Led
Figure 1: Simple LED circuit

 

Raspberry Pi Led
Figure 2: Experimental setup for LED control

Switch the Rasberry Pi LED on and off using Python

After you have made sure that the above circuit works in principle, now use a GPIO contact instead of pin 1 (3.3 V), e.g. B. Pin 26 for GPIO 7. When the Raspberry Pi is switched on, the LED will no longer light up. Much more you can now control the LED through a Python program.

#! / usr / bin / python3
import RPi. GPIO as GPIO
import time
# Use pin numbers (not GPIO numbers!)
GPIO. setmode (GPIO. BOARD)
# Use pin 26 (= GPIO 7) for data output
GPIO. setup (26, GPIO. OUT)
# Switch on pin 26
GPIO. output (26, GPIO. HIGH)
# Switch pin 26 off again after five seconds
time. sleep (5)
GPIO. output (26, GPIO. LOW)
# enable all GPIOs / pins used by the script
GPIO. cleanup ()

The program code should be easy to understand even without any Python experience. chmod makes the script file executable. Only root is allowed to control GPIO functions, therefore the script must be executed with sudo:

sudo ./ led1.py



Switch LEDs via transistors

You will learn how to use a transistor again using the example of an LED. This time do not switch the LED directly via a 3.3 V GPIO pin, but through the 5 V output controlled by a transistor.

On the one hand, this method has the advantage that it outputs far more current than 8mA the 5V pin. In this example, the choice of transistor falls on a BC547. That is what it is a “forest and meadow component” that you can buy for a few cents from almost every electronics dealer. The component is available in 3-pin design. The BC547 is dimensioned for a maximum collector / emitter current of 100mA. This is in other words, the current that flows through the LED that will later be connected – for our application so perfectly adequate.

The base is the terminal that is used to control the transistor. However, it applies here one little thing to note: with a bipolar transistor like the BC547 the base current is decisive for the degree of opening of the transistor. Too big one Current could possibly damage the output of the Raspberry Pi, and one that is too small Current does not fully open the transistor.

To prevent that from happening, use between the GPIO pin and the base of the BC547 a base resistor. With this resistor you determine the current that flows into the base. To calculate the resistance it is necessary that you take a look at the data sheet of the BC547.

The current gain of the transistor is usually specified in the data sheet (e.g. beta). In the case of the BC547, the smallest current gain has a factor of 200. This means that the collector / emitter current is two hundred times the base current can be. The required resistance can be derived from the expected collector / emitter current and the current gain can be calculated. Go at a white one LED from a current of 20mA, the following formula results:

0.02 A / 200 = 0.0001 A = 100 µA

(3.3 V – 0.7 V) / 0.0001 A = 26000Ω

In practice, however, this calculation does not have to be carried out. With normal switching tasks, such as switching an LED, the a common base resistance of 1k  be used. This is the possible one Collector / emitter current more than sufficient. On the other hand is the outcome of the Raspberry Pi limited to 3.3mA. Now you can already build the circuit (see Figure 3).

Raspberry Pi Led
Figure 3: LED transistor circuit

Remember that the series resistor of the LED has to be recalculated because you now use 5 V supply voltage for the LED and accordingly more voltage at the series resistor must drop. The Python program can simply be copied from the first example. Provided If you use the same GPIO pin as an output, nothing changes in the software.

Control LEDs with Darlington transistors

If you are designing circuits that require multiple transistors, this is a good idea a so-called Darlington array. This is an integrated Circuit (IC) in which several transistors are built into one housing. One Darlington array saves space, time and wires. It is very easy to use (see Figure 4) and is similar to the simple transistor circuit. In the following example we use the common Darlington array ULN2803.

The ULN2803 inverts the signal present at the inputs: As soon as a high Signal is present at the input, the corresponding output switches to common ground. You can see a possible application type for the ULN2803 in the circuit diagram. In terms of software, not much changes – you have to use the existing code The introductory example can only be expanded by the additional outputs used.

Raspberry Pi Led
Figure 4: LED circuit with Darlington array

Would you like inductive loads, e.g. switch a motor with the ULN2803, so connect pin 10 to the supply voltage to use the integrated freewheeling diodes to activate. Please note, however, that according to the data sheet, the module for a maximum of 500mA per output is designed. You can easily have two or more Connect outputs in parallel to increase the maximum current. You also need Do not have a base resistor in front of the inputs. There are already 2.7k Integrated base resistors.

Raspberry Pi Led


Switch LEDs on and off with a button

The simplest form of forwarding input to the Raspberry Pi is a simple one Button that closes the circuit as long as it is pressed often everything that you can press is called a “switch” distinguishes in electrical engineering between switches that maintain the state (such as a Light switch), and buttons that spring back when you let go of them (like yours Keyboard). So for this example you need a button. If you go to the test setup use a breadboard, ask your electronics store for one Print button. The goal of this section is to create a circuit that will take you through a quick press switch on an LED with a button. If you press again, the LED should go out again. The task sounds trivial, but you will see that this one Impression is deceptive.

Before you connect the push button to a GPIO pin, you need to give some thought about how the Raspberry Pi processes input. It is possible to have one Configure the GPIO pin as input. The output voltage of this pin is thus undefined. If a voltage close to 0 V is applied from the outside, this is called Low = 0 interpreted. On the other hand, if the applied voltage is close to 3.3 V, the signal becomes interpreted as high = 1. GPIOs used as input cannot be used between other Differentiate states and therefore cannot measure the created Voltage can be used.

An input pin should never be unconnected because its voltage is then undefined (floating). At the same time, it is not recommended to connect the pin directly to the ground or to be connected to the supply voltage (3.3 V): Should the GPIO pin be wrong programmed as an output pin, large currents might flow, which, with a little bad luck, destroy your Raspberry Pi. The solution to this problem are pull-up or pull-down resistors on the order of about 1 k  to 10 k to set the signal input for both possible states of the button with the ground or to be connected to 3.3 V. Background information on pull-up and pull-down You can read about resistances in Wikipedia.

When wiring the Raspberry Pi, you can use pull-up and pull-down resistors save under certain circumstances: On the one hand are pins 3 and 5 of the P1 header standard with 1.8 k  external pull-up resistors connected to the other all GPIOs can be programmed in input mode so that CPU-internal pull-up or Pull-down resistors are activated.

Nevertheless, it is recommended to always use an external signal input To provide a pull-up or pull-down resistor (see Figure 13.6). You avoid thus problems if a GPIO pin is accidentally misconfigured or during the initialization of the Raspberry Pi assumes a different state than Your circuit assumes. You can only do without pull-up resistors without risk if when you connect your button to pins 3 or 5. These two pins but are only freely available if your circuit does not have any I2C components contains.

Raspberry Pi Led
Figure 5 LED circuit with input button

As far as the light emitting diode is concerned, there is no change compared to the previous section – if you ignore the fact that this time pin 23 is used for control is used. The button is directly connected to the ground and via the pull-up Resistor R2 connected to the supply voltage 3.3 V. In normal condition the signal state on pin 21 is high, when pressed it is low. The resistor R3 is an additional safety measure. He prevents you Short circuit in the admittedly unlikely event that pin 21 was mistaken is programmed as output, set to high and at the same time the button is pressed. Without R3 there would be a direct connection between 3.3 V on pin 21 and the mass, and more current would flow than the Raspberry Pi can supply. Thanks to R3, the current is limited to 3.3mA even in this case. Before you start programming, you should briefly check whether the Circuit construction works. First, try turning the LED on / off:

gpio -1 mode 23 out
gpio -1 write 23 1       # LED on
gpio -1 write 23 0        # LED off

Then test the signal input on pin 21, holding down the button once:

gpio -1 mode 21 in
gpio -1 read 21     # normal state
1
gpio -1 read 21    # key pressed
0

If you want direct feedback you can pin 21 with a small one Query Python script continuously:

#! / usr / bin / python3
import RPi. GPIO as GPIO
import time
# Use pin numbers (not GPIO numbers!)
GPIO. setmode (GPIO. BOARD)
# GPIO 21 = input
GPIO. setup (21, GPIO .IN)
while True:
input = GPIO. input (21)
print ("State:" + str (input))
time. sleep (0.01)

As soon as you start this program, there is the current signal input from pin 21 regularly in the terminal – until you stop the program with (Ctrl) + (C). The monitoring of signal states through a loop is seldom optimal Concept. When the time is short, the program causes a lot of unnecessary CPU load. If you use a longer time, the response time of the program increases, and in In the worst case scenario, it overlooks a brief pulse entirely. It is much more intelligent it is to formulate the Python program in such a way that it simply responds to a signal change waits and only then becomes active through an event.

The following Python program demonstrates this procedure: With def, defines a callback function that should always be called when the Button is pressed. This is exactly what add_event_detect takes care of: It becomes Pin 23 monitors; whenever its signal level falls from high to low, the function

switch_on called. The program should run until it is terminated with (Ctrl) + (C) becomes. That is the purpose of the infinite loop at the end of the program.

#! / usr / bin / python
import RPi. GPIO as GPIO
import time, sys
# Use pin numbers (not GPIO numbers!)
GPIO. setmode (GPIO. BOARD)
ledStatus = 0
# GPIO 21 = input, 23 = output
GPIO. setup (21, GPIO .IN)
GPIO. setup (23, GPIO. OUT)
GPIO. output (23, ledStatus)
# Define function to activate the
# Change LED status
def switch_on (pin):
global ledStatus
ledStatus = not ledStatus
GPIO. output (23, ledStatus)
return
# switch_on - call function when signal
# changes from HIGH to LOW
GPIO. add_event_detect (21, GPIO.FALLING)
GPIO. add_event_callback (21, switch_on)
# with minimal CPU load at the end of the program
# wait with Ctrl + C
try:
while True:
time. sleep (5)
except KeyboardInterrupt:
GPIO. cleanup ()
sys. exit ()

If you try the circuit and program now, you will find that switching it on and off works quite unreliably. This is due to behavior all mechanical buttons and switches: these bounce, i. i.e., a metal flake hits a contact point several times and therefore releases very quickly one after the other several level changes at the input pin.

There are two simple solutions to the problem: Either you build into your circuit a capacitor that prevents bouncing during its charging time, or You decide on a software solution and wait after each input event 200ms before you accept inputs again. The software solution is in the GPIO library for Python already provided. You just give in to the function add_event_detect as an additional parameter the desired debounce time in milliseconds on:

GPIO. add_event_detect (21, GPIO.FALLING, bouncetime = 200)

In the current RPi.GPIO version it is not possible to use this method to generate an input to monitor for a rising and falling edge at the same time. A non-working example is the following:

GPIO. add_event_detect (21, GPIO.FALLING)
GPIO. add_event_callback (21, switch_on)
GPIO. add_event_detect (21, GPIO.RISING)
GPIO. add_event_callback (21, switch_off)
You will get the following error message here:
Edge detection already enabled for this GPIO channel Instead, proceed as in this correct example:
GPIO. add_event_detect (21, GPIO. BOTH)
GPIO. add_event_callback (21, switch_on)

In the callback function that is now called, you can determine whether a rising or falling edge was recognized:

def switch on (pin):
if GPIO. input (pin) == True:
print "rising edge"
else:
print "falling edge"

As mentioned at the beginning, it is possible to use the internal pull-up or Activate pull-down resistors. Simply add the following lines To your Python code:

GPIO. setup (11, GPIO .IN, pull_up_down = GPIO. PUD_DOWN)

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

The first line activates the pull-down resistor on pin 11, the second the pull-up resistor Resistance. These functions then replace the external resistors.


LEDs with software PWM dimming

Due to the character of the diode characteristic, an LED is very difficult to work with dimming via current or voltage. The ideal solution is to have a Apply PWM signal (PWM = pulse width modulation). This is where the tension pulsed quickly. The voltage level always remains the same in the high phases. The well-known Python library RPi.GIPO offers in the latest version 0.5.6 the possibility generate a software PWM signal on all freely available GPIO pins.

When working with a PWM signal there are two factors that are influenced with RPi.GPIO can be: the frequency and the duty cycle. The frequency determines how the voltage level often changes from low to high every second. The duty cycle sets determines how long a high phase lasts and is usually given as a percentage (see Figure 6 to 8). The brightness of the LED is influenced by the duty cycle. The frequency is only set to a value at which the human eye no longer flickers perceives. We could no longer detect any flickering from a value of 100 Hz. The circuit structure corresponds to that of the transistor circuit (see Figure3).

Raspberry Pi Led
Figure 6 PWM signal with a duty cycle of 50% and a frequency of 1 Hz
Raspberry Pi Led
Figure 7:PWM signal with a duty cycle of 80% and a frequency of 1 Hz
Raspberry Pi Led
Figure 8: PWM signal with a duty cycle of 80% and a frequency of 5 Hz

A suitable Python program can look like this:

#! / usr / bin / python3
from time import sleep
import RPi. GPIO as GPIO
# Use the physical designation of the pins
GPIO. setmode (GPIO. BOARD)
GPIO. setup (26, GPIO. OUT)
# Create a PWM instance for pin 16 with a frequency of 100 Hz
pwm = GPIO. PWM (26, 100)
# PWM start with duty cycle of 50%
pwm. start (50)
# Manual input of the duty cycle in a continuous loop
while True:
dc = input ("Enter DC from 0 to 100:")
pwm.ChangeDutyCycle (dc)
GPIO. cleanup

Once you run the program, you will be after entering the duty cycle asked. Change this a few times and observe the behavior of the LED.


Dimming LEDs with hardware PWM

Hardware PWM means that the PWM cycle is not calculated by the CPU, but is generated directly by the hardware. The disadvantage with software side generated PWM signals is that the processor must calculate the signal and is therefore also charged. Especially at the several pins that have a software PWM signal at the same time, this can lead to unclean signals or high CPU utilization to lead. The disadvantage of hardware PWM is that only pin 12 and pin 35 the Raspberry Pi plug connector J8 can master this mode.

So far this function has only been supported by the wiringPi library. The current RPi.GPIO version does not offer this function. To install wiringPi, the following steps are necessary:

sudo apt – get install python3 -dev python3 -pip

sudo pip -3.2 install wiringpi2

After the installation you can already import wiringPi into your Python code:

import wiringpi2 as wiringpi

The following example for a Python program generates a PWM signal on the Hardware PWM capable pin 12:

#! / usr / bin / python3
import wiringpi2 as wiringpi
# Use the physical designation of the pins
wiringpi. wiringPiSetupPhys ()
# Set pin 12 to PWM mode
wiringpi. pinMode (12, 2)
# Generate PWM signal
# 0 = no signal, 1024 = duty cycle 100%
wiringpi. pwmWrite (12, 500)

Control RGB LEDs using Raspberry Pi:

LEDs come in different colors – red, green, blue etc. However, it is also possible all these colors and those colors that result from the mixing of red, green and blue result in uniting in one LED. Such LEDs are called RGB LEDs. Already the The first visual impression indicates a difference: The RGB LED has four instead of four two legs. Inside the LED there are three chips very close to each other. Each chip produces one of the three colors. Thus the cathode of each of the three is Chips designed as legs. The longest leg is the common anode (+) the chips. When buying an RGB LED you should make sure that you have a version with Choose a diffuse or matt housing. With crystal-clear housings, the Later you can tell the individual chips apart very well, and you see instead a mixed color three individual colors.

Raspberry Pi Led
Figure 9: Connection of an RGB LED to the Raspberry Pi

On the circuit diagram (see Figure 10) you can see that the series resistors of the LEDs are not placed in front of the anode, but behind the cathode of each one Crisps. In addition, each color has a different resistance value. That arises from the fact that each chip color has a different forward voltage. The red LED has one Operating voltage of approx. 2.1V, the green LED of 3.3 V, and the blue LED required 3.2V. Each LED requires approx. 20mA at this voltage. With these values ​​you can You can calculate the appropriate resistance for each chip. One A common series resistor on the anode would lead to different brightnesses of the colors. See the data sheet for your LED for the exact values ​​for your model Experienced.

Raspberry Pi Led
Figure 10: RGB LED on a breadboard


The following Python program serves as an example for controlling the RGB LED. You have a choice between a mode that allows manual mixing of the colors and a mode for the automatic color change of the LED.

#! / usr / bin / python3
from time import sleep
import RPi. GPIO as GPIO
GPIO. setmode (GPIO. BOARD)
# GPIO pins with the corresponding LED color
red = 3
green = 5
blue = 7
GPIO. setup (green, GPIO .OUT)
GPIO. setup (blue, GPIO. OUT)
GPIO. setup (red, GPIO. OUT)
# Function to switch all used pins to low
def all_off ():
GPIO. output (red, false)
GPIO. output (green, false)
GPIO. output (blue, false)
Return
# Mode selection
selection = eval (input ("[1] Mix [2] Auto \ n"))
# Set PWM with a frequency of 100 Hz
pwm_g = GPIO .PWM (green, 100)
pwm_b = GPIO .PWM (blue, 100)
pwm_r = GPIO .PWM (red, 100)
# PWM start with a frequency of 0% duty cycle
pwm_g. start (0)
pwm_b. start (0)
pwm_r. start (0)
try:
if selection == 1:
while True:
# Values from 0 -100 are permitted
dcr = eval (input ("Red component [0 -100]: \ n"))
dcb = eval (input ("Blue component [0 -100]: \ n"))
dcg = eval (input ("Green share [0 -100]: \ n"))
# Change duty cycle according to the entry
pwm_g. ChangeDutyCycle (dcg)
pwm_b. ChangeDutyCycle (dcb)
pwm_r. ChangeDutyCycle (dcr)
# Color change in "Auto" mode
if selection == 2:
while True:
for i in range (100):
pwm_g. ChangeDutyCycle (i)
sleep (0.05)
if i == 99:
for i in xrange (100, 0, -1):
sleep (0.05)
pwm_g. ChangeDutyCycle (i)
for i in range (100):
pwm_r. ChangeDutyCycle (i)
sleep (0.005)
if i == 99:
for i in xrange (100, 0, -1):
sleep (0.05)
pwm_r. ChangeDutyCycle (i)
except KeyboardInterrupt:
all_off ()

Play around with the values ​​and observe the behavior of the LED. Think you can also choose your own processes for the automatic color change. If you have internalized the principle of the RGB-LED, so you can e.g. several status LEDs Replace with an RGB LED.

 

Engr Fahad

My name is Shahzada Fahad and I am an Electrical Engineer. I have been doing Job in UAE as a site engineer in an Electrical Construction Company. Currently, I am running my own YouTube channel "Electronic Clinic", and managing this Website. My Hobbies are * Watching Movies * Music * Martial Arts * Photography * Travelling * Make Sketches and so on...

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button