Chapter 6. LEDs

Controlling light-emitting diodes (LEDs) is likely to be near the top of any maker’s to-do list. There is a bewildering array of different types of LEDs, from simple LEDs, through to high-power, infrared, and ultraviolet devices.

LEDs (Figure 6-1) vary in their current requirements, and some will work just fine from a digital output, while others will need a transistor or other circuitry to control them.

Figure 6-1. A selection of LEDs

 

Regular LEDs

By regular LEDs, I mean those small colorful devices that often come in a 5mm diameter (sometimes 3mm or 10mm) and require a modest current to make them light, so that they can be controlled directly from the output of an Arduino or Raspberry Pi.

Figure 6-2 shows how you typically connect an LED to a digital output of an Arduino or Raspberry Pi.

Figure 6-2. Connecting an LED to a digital output

The resistor is needed to limit the current flowing through the LED for two reasons: first, so that the LED’s maximum current is not exceeded (which will shorten its life); and second, so that the output-current capability of the output pin or the cumulative total of all the output pins has not been exceeded.

Current Limiting

When an LED is connected up as shown in Figure 6-2 there will be a more or less constant voltage across the LED. This is called the LED’s forward voltage (abbreviated to Vf). Vf is different for different colors of LED. Red LEDs usually have the lowest Vf and blue and white LEDs usually have the highest Vf among LEDs producing visible light (see Table 6-1).

There are also infrared (IR) LEDs, which are used in TV remote controls, and ultraviolet (UV) LEDs, which are often used to make white clothes glow a violet color at parties or to check for fake bank notes.

In addition to its forward voltage, the other thing to know about an LED is the forward current that you want flowing through it. Most LEDs will emit some light at a current of 1mA or less, but most will reach optimum brightness at around 20mA. That’s quite a big range, and is why if you want to play it safe, a 470Ω resistor with any LED from either a Raspberry Pi or Arduino will work, although the LED will not be as bright as it could be.

The easiest way to calculate the value of series resistor is to use a web service that will do the math for you. One such service (http://led.linear1.org/1led.wiz) is shown in Figure 6-3.

Figure 6-3. Series resistor online calculator

In this case, the source voltage is 3.3V because a Raspberry Pi is being used and the Raspberry Pi’s maximum current of 16mA for any one pin is used. The calculator tells us that we should use an 82Ω resistor for an LED with a Vf of 2.2V.

If you are interested in making the calculation for yourself, you’ll need to first subtract the Vf (2.2V) value for the LED from the logic-level voltage (3.3V). That makes 1.1V. Then use Ohm’s law to calculate the resistor value R = V / I = 1.1V / 16mA = 68.75Ω.

You can also use Table 6-1 to help you pick a resistor. This table indicates the approximate range of Vf for different colors of LED as well.

Table 6-1. Current limiting resistors for LEDs
  IR Red

Orange/

Yellow/

Green

Blue/

White

Violet UV
Vf 1.2-1.6V 1.6-2V 2-2.2V 2.5-3.7V 2.7-4V 3.1-4.4V

Pi 3.3V

3mA

X 680Ω 470Ω 270Ω 220Ω 68Ω

Pi 3.3V

16mA

150Ω 120Ω 82Ω 56Ω 39Ω 15Ω

Arduino

5V 20mA

220Ω 180Ω 150Ω 150Ω 120Ω 100Ω

Note that the resistance values are adjusted to the nearest readily available standard resistor value.

There is an X in the IR column at 3mA because IR LEDs for remote controls generally require at least 10mA to do anything much and most are designed to operate at 100mA or more to obtain a decent range for the remote control.

Project: Traffic Signal

Having such a great selection of LED colors to choose from for this project (shown in Figure 6-4), you will use a red, orange, and green LED to make a traffic signal controlled by Arduino or Raspberry Pi.

Figure 6-4. An Arduino traffic signal

The sequence of LEDs displayed is:

  1. Red
  2. Red and orange together
  3. Green
  4. Orange

Parts List

Whether you are using a Raspberry Pi or Arduino (or both), you are going to need the following parts to build this project:

Name Part Sources
LED1 Red LED 

Adafruit: 297

Sparkfun: COM-09590

LED2 Orange LED Sparkfun: COM-09594
LED3 Green LED

Adafruit: 298

Sparkfun: COM-09650

R1-3 150Ω resistors Mouser: 291-150-RC
  400-point solderless breadboard Adafruit: 64
  Male-to-male jumper wires

Adafruit: 758

  Female-to-male jumper wires (Pi only) Adafruit: 826

Over time, you will probably find yourself collecting resistors of many different values. In this case, I have suggested a compromise value of 150Ω resistors for the LEDs for both Arduino and Raspberry Pi and for all three colors of LED. If you wanted to fine-tune this for maximum brightness, you could use Table 6-1 to pick the optimum resistor values. 

Design

The three LEDs are each connected to a separate output pin of either the Arduino or Raspberry Pi. 

Arduino Connections

Figure 6-5 shows the breadboard layout and connection to the Arduino.

Figure 6-5. Breadboard layout for the Arduino traffic signal

Remember that the long LED lead is the positive lead and these go to the left of the breadboard and one end of the LED’s resistor. The shorter negative lead of the LEDs all go to the negative supply column that runs down the righthand side of the breadboard.

Arduino Software

The Arduino sketch for this project can be found in arduino/projects/traffic_signals, which you’ll find in the place where you downloaded the book’s code (see “The Book Code” in Chapter 2). Let’s take a look at it:

const int redPin = 11;           // 1
const int orangePin = 10;
const int greenPin = 9;

void setup() {                    // 2
  pinMode(redPin, OUTPUT);
  pinMode(orangePin, OUTPUT);  
  pinMode(greenPin, OUTPUT);  
}

void loop() {                 // 3
  setLEDs(1, 0, 0);
  delay(3000);
  setLEDs(1, 1, 0);
  delay(500);
  setLEDs(0, 0, 1);
  delay(5000);
  setLEDs(0, 1, 0);
  delay(500);
}
  
void setLEDs(int red, int orange, int green) {   // 4
 digitalWrite(redPin, red);
 digitalWrite(orangePin, orange);
 digitalWrite(greenPin, green);
}

The sketch has much in common with the original blink sketch, except that instead of controlling a single LED, three LEDs are being controlled.  

1

Constants are defined for each of the Arduino pins connected to an LED.

2

In the setup() function, the pins are set to be outputs.

3

The loop() function calls a setLEDs() function to set the three LEDs on or off (1 or 0). The delay between each call to setLEDs() determines how long the lights stay in that phase.

4

The setLEDs() function really just makes the loop function shorter and easier to read, allowing all three digitalWrites() to be condensed into one line. 

Raspberry Pi Connections

For the Raspberry Pi version of this project, the male-to-male jumpers are swapped for female-to-male jumpers and the same breadboard layout is connected to GPIO pins 18, 23, and 24, as shown in Figure 6-6.

Figure 6-6. Breadboard layout for the Raspberry Pi traffic signal

Raspberry Pi Software

The Python program for this project can be found in the traffic.py file in the python/projects/ directory (for information on installing the Python programs for the book, see “The Book Code” in Chapter 3):

import RPi.GPIO as GPIO
import time

GPIO.setmode(GPIO.BCM)

red_pin = 18
orange_pin = 23
green_pin = 24

GPIO.setup(red_pin, GPIO.OUT)
GPIO.setup(orange_pin, GPIO.OUT)
GPIO.setup(green_pin, GPIO.OUT)

def set_leds(red, orange, green):    # 1
    GPIO.output(red_pin, red)
    GPIO.output(orange_pin, orange)
    GPIO.output(green_pin, green)

try:         
    while True:
        set_leds(1, 0, 0)
        time.sleep(3)
        set_leds(1, 1, 0)
        time.sleep(0.5)
        set_leds(0, 0, 1)
        time.sleep(5)
        set_leds(0, 1, 0)
        time.sleep(0.5)
          
finally:  
    print("Cleaning up")
    GPIO.cleanup()
1

Just like the Arduino version, a function (set_leds) is used to keep the main loop uncluttered by too many GPIO.output functions.

PWM and LEDs

If you try controlling the brightness of an LED by adjusting the voltage across it, it generally doesn’t work so well, because there is a big dead-zone until the voltage gets high enough for the LED to emit any light at all.

PWM analog outputs (see “Pulse-Width Modulation”) are perfect for controlling the brightness of the LED. LEDs can turn on and off very quickly, certainly less than a millionth of a second, so when using PWM with LEDs, they are actually flashing at the PWM frequency, but the eye sees them as on but with a brightness that varies as the proportion of the time that the LED is actually on changes.

RGB LEDs

Red, green, and blue LEDs (RGB LEDs) are a single LED case that contains three actual LEDs. The three LEDs are red, green, and blue. By using PWM to control the brightness to each of the LED colors, you can make the LED appear any color.

Although an RGB LED contains three normal, two-pin LEDs, this does not mean that the LED body has to have six pins, because one terminal of each LED can be connected together as a common pin (Figure 6-8).

Figure 6-8. The schematic diagram for a common cathode RGB LED

If the negative connections to each LED are connected together, the resulting lead is called a common cathode and if the positive connections are common, the lead is called a common anode. 

The RGB LED package will either be described as clear or diffuse. If it’s clear you will be able to see the red, green, and blue LEDs inside the package, and the color will not mix together so well. The diffuse packages mix together the light from the three LEDs much better. 

In Chapter 14, you will work with displays made up of RGB LED ICs that contain a chip that both limits the current to the red, green, and blue LEDs, in addition to providing them with a serial data interface that allows an Arduino or Raspberry Pi to control large numbers of them with a single output pin.

Experiment: Mixing Colors

In this experiment, you can use both Arduino and Raspberry Pi to control the color of an RGB LED. In the Raspberry Pi version of the project, a graphical user interface with three sliders is used to control the color. Figure 6-9 shows the Raspberry Pi version of the experiment.

Hardware

Figure 6-10 shows the schematic diagram for the experiment. 

Figure 6-9. Mixing colors with a Raspberry Pi
Figure 6-10. The schematic diagram for the RGB LED experiment

For optimum brightness and best color balance, you should choose your resistor values carefully. However, it’s easier to buy your components if you use the same value resistor for all three channels. In this case, I suggest 470Ω resistors as a “universal” option that will work with Raspberry Pi or Arduino.

The brightness and efficiency of an RGB LED is such that even with only 3mA (6mA on an Arduino), the LED will still look pretty bright.

Parts List

Whether you are using a Raspberry Pi or Arduino (or both), you are going to need the following parts to carry out this experiment:

Name Part Sources
LED1 RGB LED diffused common cathode Sparkfun: COM-11120
R1-3 470Ω resistor Mouser: 291-470-RC
  400-point solderless breadboard Adafruit: 64
  Male-to-male jumper wires

Adafruit: 758

  Female-to-male jumper wires (Pi only) Adafruit: 826

If you are planning to try this experiment with a Raspberry Pi, you will need female-to-male jumper wires to connect the Raspberry Pi GPIO pins to the breadboard.

All the components in the list are included in the MonkMakes Electronic Starter Kit for Raspberry Pi (see Appendix A).

Arduino Connections

The Arduino version of this experiment uses the Serial Monitor to set the proportion of red, green, and blue.

Figure 6-11 shows the breadboard layout and connections to the Arduino.

Figure 6-11. Arduino breadboard layout for RGB color mixing

The longest lead of the LED is the common cathode lead that is connected to GND in Figure 6-11. The order of the other leads may not be the same as I have shown, so you might have to do some lead swapping if you find your colors mixed up.

Arduino Software

The Arduino sketch for this experiment uses three PWM channels to control the brightness of each of the three colors. The sketch is in the ex_12_mixing_colors file, which you’ll find in the place where you downloaded the book’s code):

const int redPin = 11;
const int greenPin = 10;
const int bluePin = 9;

void setup() {
  pinMode(redPin, OUTPUT);
  pinMode(greenPin, OUTPUT);
  pinMode(bluePin, OUTPUT);  
  Serial.begin(9600);
  Serial.println("Enter R G B (E.g. 255 100 200)");
}

void loop() {
  if (Serial.available()) {
    int red = Serial.parseInt();   // 1
    int green = Serial.parseInt();
    int blue = Serial.parseInt();
    analogWrite(redPin, red);     // 2
    analogWrite(greenPin, green);
    analogWrite(bluePin, blue);
  }
}
1

Each of the three PWM values that should be between 0 and 255 are read into variables.

2

The PWM output is then set for each channel.

Arduino Experimentation

After uploading the sketch, open the Serial Monitor on the Arduino IDE. Then type three numbers, each between 0 and 255 and separated by a space, and click the Send button.

The LED should then change color to match the red, green, and blue numbers that you just entered. 

You can check each channel separately by entering 255 0 0 (red), then 0 255 0 (green), and finally, 0 0 255 (blue).

Raspberry Pi Connections

Rather than just use commands to change color, the Raspberry Pi version of this project creates a small user interface window on the Raspberry Pi that has three sliders, one for each color channel.

As you change the position of the sliders, the LED color will change. This software uses a graphical user interface, so you will need to have a keyboard, mouse, and monitor attached to your Raspberry Pi, as SSH does not have a graphical interface.

The breadboard layout for the Raspberry Pi (Figure 6-12) is just the same as for the Arduino, except that for the Raspberry Pi you need to use female-to-male jumper wires. The GPIO pins 18, 23, and 24 are used as PWM outputs.

Figure 6-12. Raspberry Pi breadboard layout for RGB color mixing

Raspberry Pi Software

The Python program for this experiment uses a framework called Tkinter that allows you to make applications that run in a window and have user interface controls, rather than the simple command line that you have used so far. This makes the program a bit longer than normal. It also makes use of some more advanced programming.

Let’s take a look at the program code (which you can find in the file mixing_colors.py):

from Tkinter import *       
import RPi.GPIO as GPIO
import time


GPIO.setmode(GPIO.BCM)  # 1
GPIO.setup(18, GPIO.OUT)
GPIO.setup(23, GPIO.OUT)
GPIO.setup(24, GPIO.OUT)


pwmRed = GPIO.PWM(18, 500) # 2
pwmRed.start(100)

pwmGreen = GPIO.PWM(23, 500)
pwmGreen.start(100)

pwmBlue = GPIO.PWM(24, 500)
pwmBlue.start(100)

class App:
    
    def __init__(self, master): # 3
        frame = Frame(master)  # 4
        frame.pack()
        
        Label(frame, text='Red').grid(row=0, column=0) # 5
        Label(frame, text='Green').grid(row=1, column=0)
        Label(frame, text='Blue').grid(row=2, column=0)
        
        scaleRed = Scale(frame, from_=0, to=100,     # 6
              orient=HORIZONTAL, command=self.updateRed)
        scaleRed.grid(row=0, column=1)
        scaleGreen = Scale(frame, from_=0, to=100,
              orient=HORIZONTAL, command=self.updateGreen)
        scaleGreen.grid(row=1, column=1)
        scaleBlue = Scale(frame, from_=0, to=100,
              orient=HORIZONTAL, command=self.updateBlue)
        scaleBlue.grid(row=2, column=1)

    def updateRed(self, duty):     # 7
        # change the led brightness to match the slider
        pwmRed.ChangeDutyCycle(float(duty))

    def updateGreen(self, duty):
        pwmGreen.ChangeDutyCycle(float(duty))
    
    def updateBlue(self, duty):
        pwmBlue.ChangeDutyCycle(float(duty))


root = Tk()  # 8
root.wm_title('RGB LED Control')
app = App(root)
root.geometry("200x150+0+0")
try:
    root.mainloop()
finally:  
    print("Cleaning up")
    GPIO.cleanup()
1

Configure the Pi to use the Broadcom (BCM) pin names, rather than the pin positions.

2

Start pulse-width modulation (PWM) on the red, green, and blue channels to control the brightness of the LEDs.

3

This function gets called when the app is created.

4

A frame holds the various GUI controls.

5

Create the labels and position them in a grid layout.

6

Create the sliders and position them in a grid layout. The command attribute specifies a method to call when a slider is moved.

7

This method and the similar methods for the other colors are called when their slider moves.

8

Set the GUI running, and give the window a title, size, and position.

Raspberry Pi Experimentation

Run the program as superuser using the following command:

$ sudo python mixing_colors.py

After a moment or two, the window shown in Figure 6-13 will appear.

Figure 6-13. Move the sliders to change the LED color

When you move the sliders around, the color of the LED will change.

Summary

In this chapter you have learned how to switch an LED on and off and also control its brightness using an Arduino and Raspberry Pi. Now that you can control light with the Arduino and Raspberry Pi, the next chapter will focus on movement. We’ll explore DC motors, which are the most common type, and how we can control them.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.91.252