THIS CHAPTER DISCUSSES the basic electrical components common to many Arduino and Raspberry Pi projects. The chapter starts by showing you a basic electric circuit. Then the difference between a series and a parallel connection is illustrated, followed by a definition of a resistor and the introduction of some key concepts such as Ohm’s law. Then the chapter shows you how to read the color bands on a resistor to determine the resistor’s value. Next, light-emitting diodes (LEDs), the red-green-blue (RGB) LEDs, the Piezo buzzers, potentiometers, push buttons, and breadboards are described. The remainder of this chapter provides hands-on example projects involving the Arduino and Raspberry Pi and using the basic electrical components discussed earlier.
The basic electric circuit consists of a voltage source, a switch to activate or deactivate the circuit, and an electrical component that uses the voltage source to operate. The voltage induces an electric current to flow from the positive terminal to the negative terminal of the voltage source through the electrical component
(Figure 3-1).Figure 3-1 | Basic electric circuit. |
Traditionally, a mechanical switch was used to activate an electric circuit. However, in this book, instead of a mechanical switch, we will use an Arduino or Raspberry Pi to activate and deactivate the circuit and to provide the voltage to the circuit. A digital pin on the Arduino or Raspberry Pi will turn the circuit on or off by supplying a voltage to a pin. The pin is connected to the positive terminal of the component, and the negative terminal of the component is connected to the ground (also known as negative or common) on the Arduino or Raspberry Pi (Figure 3-2).
Figure 3-2 | Arduino or Raspberry Pi electric circuit controller. |
Electrical components can be connected in parallel or series configurations. In a parallel connection, all the positive terminals are connected together, and all the negative terminals are connected together. When a voltage source is connected in parallel with the components, all the components have the same voltage as the voltage source. In Figure 3-3, node A contains all the positive terminals, and node B contains all the negative terminals.
Figure 3-3 | A parallel connection of electrical components. |
In a series connection between two components, one component’s positive terminal is connected to the negative terminal of the other component. In a circuit where the voltage is placed across two components connected in series, the total voltage across both components equals the input voltage. This can be expressed as:
Vsource = v1 + v2
where Vsource is the voltage source, v1 is the voltage across the first component connected in series, and v2 is the voltage across the second component connected in series with the first component (Figure 3-4).
Figure 3-4 | A series connection of electrical components. |
A resistor is a basic electrical component that obeys Ohm’s law. The current goes through the resistor from the positive terminal to the negative terminal (Figure 3-5).
Figure 3-5 | Symbol for a resistor. |
Ohm’s law can be stated as:
The voltage across a resistor is equal to the current going through the resistor multiplied by the resistance value, or
A resistance equals the voltage across the resistor divided by the current going through the resistor, or
The current going through a resistor equals the voltage across the resistor divided by the resistance (Figure 3-6).
Figure 3-6 | Ohm’s law. |
A resistor has a value displayed on the component that is coded with bands of color. The color band closest to the end of the resistor represents the first or leftmost digit, the next band represents the second digit, and the next band represents the number of zeros to add to the first and second digits to create the resistance value. The next color band represents the tolerance of the resistor, which is the range of values that the actual resistor could have. If no color band is present, then the tolerance is 20 percent (Figure 3-7). Figure 3-8 illustrates the color banding method.
Figure 3-7 | Reading resistor color codes. |
Figure 3-8 | Resistor color code chart. |
For example, if a resistor has the color bands of green, brown, red, and yellow, then the first digit of the resistance value is 5, the next digit is 1, the number of zeros after is two, and the tolerance is plus or minus 5 percent. The final value of the resistor thus is 5,100 ohms (Ω) plus or minus 5 percent of that value.
If two resistors are connected in series, then the total resistance of the two resistors is the sum of each of the individual resistors, such as:
Rtotal = R1 + R2
More generally speaking, the total resistance of a group of resistors connected in series is
Rtotal = R1 + R2 + R3 + R4 + ∙∙∙ + RN
If two resistors are connected in parallel, then the total resistance of the two resistors is
Rtotal = (R1 * R2)/(R1 + R2)
The term LED stands for light-emitting diode, and LEDs are commonly used as indicators
or light sources. A LED has one short leg that is the negative terminal and one longer leg that is the positive terminal. The LED lights up when a voltage is applied across the terminals (Figure 3-9).Figure 3-9 | A light-emitting diode (LED). |
Red-green-blue (RGB) LEDs are a type of LED that produces a color based on red, green, and blue inputs to the component. The longest leg of the LED is the negative side or ground terminal. On one side of the ground leg there is another leg that is the red color input to the LED. On the other side are two more legs. The leg closest to the ground leg is the green color input, followed by the leg for the blue color input (Figure 3-10).
Figure 3-10 | An RGB LED. |
A piezo buzzer has two terminals, one positive and one negative. If you put a voltage across the terminals, the buzzer makes a clicking sound. If you do this many times per second, then you get a tone (Figure 3-11).
Figure 3-11 | Top and side views of a piezo buzzer. |
A potentiometer can output a varying voltage based on the position of the knob. This component has a knob that can be used to set the voltage output. On the back of the component, there are three pins. The outermost pins are connected to the positive and negative terminals of a voltage source. The middle pin outputs a voltage value based on the position on the potentiometer’s knob and the input voltage source. Output voltage values can range from a maximum voltage value to 0 in smooth analog increments (Figure 3-12).
Figure 3-12 | A potentiometer. |
Push buttons can be used as user input devices. A button acts like a switch. When the button is not pressed, the two terminals on the button are open and do not conduct electricity. When the button is pressed, the two terminals are connected and can conduct electricity. For example, the user can push a button to turn a LED on and off (Figure 3-13).
Figure 3-13 | A push button. |
To build the circuits in this book, you will need a breadboard, which can be used for rapid prototyping of electronics projects without the need for soldering components. A breadboard has rows of about five holes each that are connected together. This node can be used to connect many different items together. On some breadboards, there are also vertical columns of holes that represent either positive or negative terminals of the voltage source (Figure 3-14).
Figure 3-14 | A breadboard. |
In this hands-on example, you will learn how to turn on and turn off an actual LED using your Arduino. Previously, in Chapter 1, you learned how to use the built-in LED on the Arduino board. You also learned how to use the Serial Monitor to print out debug messages as the LED is turned on and off.
The parts you will need for this hands-on example project include
2 male-to-male wires
1 breadboard
1 LED
(Optional) 1 resistor (10 kΩ recommended) (used to reduce the brightness of the LED)
Set up the hardware for this hands-on example by:
Connecting pin 8 on the Arduino to the positive terminal of the LED.
Connecting the negative terminal of the LED to one end of a resistor (10 kΩ is suggested). This resistor lowers the brightness of the LED because it lowers the voltage across the LED (see Figure 3-4 for more information about this type of connection which is called a series connection).
Connecting the other end of the resistor to a ground (GND) pin on the Arduino.
You may need to use a breadboard and groups of nodes on the breadboard to construct the circuit (Figure 3-15).
Figure 3-15 | Schematic of the project. |
Now you need to set up the software on the Arduino that will be used to control the hardware circuit. The Arduino program, or sketch, will need to be either downloaded from the publisher’s website or typed in. The program does the following:
1. It assigns pin 8 to the variable LED pin that will be used to turn the LED on and off.
2. In the one-time initialization, the function setup()
:
a. Sets the pin assigned to the LED as an output pin so that voltage can be provided to that pin by calling the pinMode()
function.
b. Initializes the Serial Monitor debug interface by calling the Serial.begin()
function with 9,600 baud, which sets the baud transfer rate.
c. Prints out to the Serial Monitor a message that initialization has begun.
3. The main loop
function, which executes continuously:
a. Prints out a message to the Serial Monitor that the LED is on.
b. Sets the voltage to the pin connected to the LED to HIGH by calling the digitalWrite(LEDPin, HIGH)
function with the pin number as the first parameter and the pin state as the second parameter.
c. Suspends execution of the program for half a second by calling the delay(500)
function with the parameter 500 milliseconds. This leaves the LED light on.
d. Prints out a message to the Serial Monitor that the LED is off.
e. Sets the voltage to the pin connected to the LED to LOW or 0 by calling the digitalWrite(LEDPin, LOW)
function with the pin number as the first parameter and the voltage state as the second parameter.
f. Suspends execution of the program for half a second by calling the delay(500)
function with 500 milliseconds as a parameter. This has the effect of leaving the LED off for half a second. See Listing 3-1.
Upload the program to the Arduino, and click on the Serial Monitor button to bring up the Serial Monitor. After a few seconds, you should see a debug message displayed within the Serial Monitor window such as that shown in Figure 3-16.
Figure 3-16 | Debug Serial Monitor output. |
You should also see the LED light blink on and off at half-second intervals. The brightness of the LED can be adjusted by raising or lowering the value of the resistor that is attached in series. Try to operate the circuit without the resistor, and you will notice that the LED is much brighter without it.
In this hands-on example, you will learn how to set up and use an RGB LED that can generate red, green, and blue colors.
The parts you will need for this hands-on example project include
1 RGB LED
1 breadboard
5 male-to-male wires
To set up the hardware for this hands-on example, you will need to:
Connect a wire from the Arduino’s pin 11 to the leg of the LED that handles the blue color input.
Connect a wire from the Arduino’s pin 10 to the leg of the LED that handles the green color input.
Connect a wire from the Arduino’s pin 9 to the leg of the LED that handles the red color input.
Connect a wire from one of the Arduino’s GND pins to the leg of the LED that serves as the GND or common.
Note: You can stick the RGB LED into a breadboard and use the male-to-male wires to connect the Arduino’s pins to the correct nodes on the breadboard representing the red, green, blue, and ground terminals (Figure 3-17).
Figure 3-17 | Arduino RGB LED. |
Now you need to set up the software that controls the RGB LED hardware. For this example, we will use pulse-width modulation (PWM) to simulate the generation of voltage output values between 0 and the maximum output voltage the Arduino supports, which is 5 V. This will give an appearance of a continuous range of analog voltage outputs using a digital method. PWM generates square waves that have values of either 0 or 5 V. The amount of time that the value is at 5 V determines the brightness of the LED. The analogWrite(PinNumber, Value)
function uses PWM to output square-wave voltage values. The first parameter is the Arduino pin number, and the second parameter is a value between 0 and 255. A value of 0 means that the LED color component is completely off, and a value of 255 means that the LED color component is always on. A value of 127 means that the LED color component is half the maximum brightness. The pins on most Arduinos that support PWM are pins 3, 5, 6, 9, 10, and 11.
The program that controls the RGB LED:
1. Sets the Arduino pins that will output color information to the red, green, and blue inputs on the RGB LED.
2. Uses the setup()
function to initialize the Serial Monitor, which prints a message indicating that the program has started to run.
3. Uses the Reset()
function to clear the values being output to all the color component pins to 0, which is completely off.
4. Uses the FadeLED(int PinNumber, int MinValue, int MaxValue, int Increment, int Delay)
function to increase or decrease the brightness of the RGB LED component using PWM. The first parameter is the pin number on the Arduino to use, and the next two parameters are the minimum and maximum value range to use when fading the LED up or down. The next parameter is the increment by which to increase or decrease the LED brightness, and this value can be either positive or negative. The final parameter is the value in milliseconds between each increase or decrease in the PWM value.
5. The main loop()
function:
a. Resets the RGB LED to off by calling the Reset()
function.
b. Fades the red component of the RGB LED upward to full brightness and then fades it down until it is off.
c. Fades the green component of the RGB LED upward to full brightness and then fades it down until it is off.
d. Fades the blue component of the RGB LED upward to full brightness and then fades it down until it is off. See Listing 3-2.
When you run the program, you should see something similar to what is shown in Figure 3-18.
Figure 3-18 | Demonstration of an RGB LED fading up and down in red, green, and blue colors. |
In this hands-on example, you will learn how to use a buzzer in combination with a LED to produce a flashing red indicator with a buzzer whose pitch increases as the brightness of the LED increases and decreases with decreasing light intensity.
The parts you will need for this hands-on example project include
1 LED
1 buzzer
1 breadboard
6 wires (approximately)
Set up the circuit for this project by:
Connecting pin 9 on the Arduino to the positive terminal of the LED.
Connecting pin 7 on the Arduino to the positive terminal of the buzzer.
Connecting the negative terminal of the LED to a GND pin on the Arduino.
Connecting the negative terminal of the buzzer to a GND pin on the Arduino (Figure 3-19).
Figure 3-19 | Schematic for the LED buzzer siren. |
Now you need to set up the software that controls the circuit for this example project. To generate sounds with the buzzer, you need to use the built-in tone()
function. This function, which is defined as tone(pin, frequency, duration)
, generates a square wave. The first parameter is the pin number on which to generate the square wave. The second parameter is the frequency of this wave, and the third parameter is the optional duration in milliseconds to generate the square wave. The tone()
function interferes with pulse-width modulation (PWM) on pins 3 and 11 of Arduino boards other than the Arduino Mega, so it is not recommended to use PWM when using these pins on an Arduino Uno.
In the LED buzzer siren program:
1. Pin 9 on the Arduino is set to control the LED.
2. Pin 7 on the Arduino is set to control the buzzer.
3. The setup()
function initializes the Serial Monitor and prints out a message indicating that the program has started.
4. The FadeLED()
function is defined as FadeLED(int PinNumber, int MinValue, int MaxValue, int Increment, int Delay, int StartFrequency, int FreqIncrement)
. This function fades the LED up or down as well as increases or decreases the pitch of the tone emitted by the buzzer. The first parameter is the pin number to which the LED is connected. The next two parameters specify the fading range for the LED. The fourth parameter indicates the increment by which to increase or decrease the brightness of the LED. The fifth parameter specifies the delay in milliseconds between increments or decrements in brightness. The sixth parameter is the beginning frequency from which the pitch will either rise or fall. The last parameter is the amount the frequency will change each time the brightness of the LED is changed. This function also returns the ending frequency after the LED’s fade-up or fade-down is completed. This is helpful in executing a smooth, continuous tone between one fade-up/down and the next fade-up/down.
5. The loop()
function:
a. Fades the LED up by calling the FadeLED()
function. The starting frequency for the buzzer is set to 300. After the fade-up is completed, the final value for the frequency of the buzzer is saved in the EndFreq
variable.
b. Fades the LED down by calling the FadeLED()
function. The starting frequency for the buzzer is set to the last frequency generated by the previous FadeLED()
function, which was stored in the EndFreq
variable. See Listing 3-3.
Now upload the program to your Arduino. You should see the LED grow brighter as the tone generated by the buzzer increases in pitch. The LED will eventually reach its maximum and then start to fade down. At this point, the buzzer should start decreasing in pitch until the LED is fully off. Then the cycle will start again.
This hands-on example project shows you how to build a circuit that generates random colors that are displayed using an RGB LED. You can control the rate that the colors are generated with a potentiometer. The potentiometer allows you to gradually decrease or increase the rate that the colors change and are displayed using the LED.
The parts you will need for this hands-on example project include
1 potentiometer
1 RGB LED
1 breadboard
8 wires (approximately)
Set up the hardware for this project by:
Connecting a wire from pin 11 on the Arduino to the leg of the LED that handles the blue color input.
Connecting a wire from pin 10 on the Arduino to the leg of the LED that handles the green color input.
Connecting a wire from pin 9 on the Arduino to the leg of the LED that handles the red color input.
Connecting a wire from one of the GND pins on the Arduino to the leg of the LED that serves as the GND or common.
Connecting a wire from one of the outermost pins on the potentiometer to the 5-V output on the Arduino.
Connecting a wire from the other of the outermost pins on the potentiometer to the GND on the Arduino.
Connecting a wire from the center pin of the potentiometer to pin A0 on the Arduino (Figure 3-20).
Figure 3-20 | Random RGB color generator. |
This hands-on example project requires you to use the built-in random(MaxColor)
function that returns a random number between 0 and 1 less than the MaxColor
input parameter. For example, calling random(256)
returns a random value between 0 and 255. Another built-in Arduino function you will need is the analogRead(SensorPin)
function, which maps an input voltage between 0 and 5 V to a number between 0 and 1,023. For example, the function analogRead(A0)
reads the voltage at pin A0 on the Arduino and returns a number between 0 and 1,023.
The setup()
function initializes the Serial Monitor for use in debugging Arduino programs and prints out a message indicating that the program has started. The GenerateRandomRGBColor(int MaxColor)
function generates a random color by using the random()
function to select a number between 0 and MaxColor
for the red, green, and blue values of the LED. The SetRGBLEDColor()
function is used to write the red, green, and blue values for the LED that were obtained by calling the GenerateRandomRGBColor()
function to the actual RGB LED by calling the analogWrite()
function. The PrintOutRGBColors()
function prints out the current red, green, and blue values for the RGB LED to the Serial Monitor.
The main program function loop:
1. Reads the voltage value present at pin A0 from the potentiometer and converts the voltage to a number between 0 and 1,023.
2. Prints out this value to the Serial Monitor.
3. Generates a random RGB value between 0 and 255 by calling the GenerateRandomRGBColor()
function with 256 as a parameter.
4. Sets the RGB value of the LED to the red, green, and blue values generated in step 3 by calling the SetRGBLEDColor()
function.
5. Prints out the red, green, and blue values of the LED to the Serial Monitor by calling the PrintOutRGBColors()
function.
6. Suspends execution of the program by calling the delay(CurrentSensorValue)
function. This has the effect of displaying the current color on the LED for CurrentSensorValue
milliseconds. See Listing 3-4.
Upload the program to the Arduino, and start the Serial Monitor. The Serial Monitor should display the current value of the potentiometer and the current red, green, and blue values of the LED. Turn the knob on the potentiometer clockwise as far as it will go. This should be one extreme where the LED blinks very rapidly and changes colors very fast or blinks very slowly and changes colors very slowly. Turn the knob from one extreme to the other, and note how fast the colors change. There should be a smooth transition from one extreme to the other. That is, the colors should gradually start to change faster or slower as you turn the knob from one extreme to the other.
In this hands-on example project, you will learn how to construct a circuit that controls an RGB LED like a light switch, but instead of turning a light on and off, it generates random colors every time you press and then release the button.
The parts you will need for this hands-on example project include
1 push button
1 10,000-Ω resistor
1 RGB LED
1 breadboard
8 male-to-male wires (minimum)
Setting up the hardware for this project consists of:
Connecting a wire from pin 11 of the Arduino to the leg of the LED that handles the blue color input.
Connecting a wire from pin 10 of the Arduino to the leg of the LED that handles the green color input.
Connecting a wire from pin 9 of the Arduino to the leg of the LED that handles the red color input.
Connecting a wire from one of the GND pins of the Arduino to the leg of the LED that serves as the GND or common.
Connecting one of the pins on the push button to the 5-V source on the Arduino.
Connecting the other pin on the push button to a node that contains pin 7 of the Arduino and one end of a 10,000-Ω, or 10-kΩ, resistor.
Connecting the other end of the resistor to a GND pin on the Arduino (Figure 3-21).
Figure 3-21 | RGB LED switch schematic. |
For this hands-on example project, you will need to read the digital input from a push button, and to do this, you will need to use the digitalRead(pin)
function. This function reads the voltage value at the pin specified. It returns a 1 if the voltage is HIGH
, which means that it is 3 V or more, or a 0 if the voltage is LOW
, or 2 V or less. The pin you use to read the voltage will also need to be declared as INPUT
using the pinMode
function, such as pinMode(ButtonPin, INPUT)
. The first parameter is the pin number, and the second parameter is set to INPUT
to indicate that this pin will be used to read the voltage value at that pin. Most of the code in this example project is reused from the preceding example project involving the potentiometer.
The main program loop:
1. Reads the voltage value at the pin connected to the push button.
2. If the result is low and the previous result was high, then the push button was just released. If this is true, then generate a random color, set this color as the color for the RGB LED, and then print out the red, green, and blue values of the color to the Serial Monitor. See Listing 3-5, and also note that the new code for this example is highlighted in bold.
Now upload the program to your Arduino, and start the Serial Monitor. You should see the message initializing the program. Press and release the button, and a random color should be displayed on the LED. You should also see a message in the Serial Monitor that displays red, green, and blue values of the color. Each time you press and release the button, a new random color will be generated and displayed on the LED.
In this hands-on example project, you will learn how to set up a blinking LED on a Raspberry Pi that will blink on and off for a specified number of times before stopping. As each blink by the LED finishes, a message is printed to the Raspberry Pi’s output terminal.
The parts you will need for this hands-on example project include
1 LED
1 10,000-Ω resistor
1 breadboard
You can set up the circuit by:
Connecting a ground (GND) pin of the Raspberry Pi to the negative terminal of the LED.
Connecting the positive terminal of the LED to one end of a 10,000-Ω resistor.
Connecting the other end of the 10,000-Ω resistor to GPIO pin 14 on the Raspberry Pi (Figure 3-22).
Figure 3-22 | Blinking an LED on a Raspberry Pi. |
This example project uses the Rpi.GPIO library, which should be included by default with the Raspberry Pi 3 operating system. The code for this example project:
1. Imports the RPi.GPIO library as GPIO
so that the module can be accessed with a reference to GPIO instead of the full name.
2. Imports the time module so that the sleep()
function can be used in the program.
3. Sets the pin on the Raspberry Pi that will be connected to the LED to GPIO pin 14.
4. Sets the Counter
variable, which keeps track of how many LED blinks have occurred, to 0.
5. Sets the Target
variable, which holds the number the Counter
variable needs to reach before the LED stops blinking.
6. Sets the RPi.GPIO library to recognize BroadCom or BCM pin numbering by calling the GPIO.setmode(GPIO.BCM)
function with GPIO.BCM
as the input parameter. BCM pin numbering for the GPIO pins is what this book uses to identify the pins you will need to use for the example projects for the Raspberry Pi.
7. Sets the LEDPin
pin as an OUTPUT
pin that will be used to provide a voltage to the attached LED by calling the GPIO.setup(LEDPin, GPIO.OUT)
function. The first parameter is the pin number that will be set. The second parameter sets the pin mode to an OUTPUT
pin.
8. While the value of the Counter
variable is less than or equal to the value of the Target
variable, the program:
a. Turns on the LED by calling the GPIO.output(LEDPin, GPIO.HIGH)
function, which sets a high voltage to the pin connected to the LED. The program then suspends execution for half a second by calling the time.sleep(0.5)
function. This has the effect of leaving the LED on for half a second.
b. Turns off the LED by calling the GPIO.output(LEDPin, GPIO.LOW)
function, which sets a 0 voltage value to the pin connected to the LED. The program then suspends execution for half a second by calling the time.sleep(0.5)
function. This has the effect of leaving the LED off for half a second.
c. Prints a message in the Raspberry Pi’s terminal window indicating the number of blinks that have occurred, starting at 0, by calling the print("Number Blinks: ", Counter)
function.
d. Increases the Counter
variable by 1.
9. After the program finishes blinking the light, the GPIO pins need to be reset and resources related to setting the pins need to be reallocated by calling the GPIO.cleanup()
function. See Listing 3-6.
Start up a terminal window on your Raspberry Pi desktop, and change the directory to where you have saved the program. Run the program by typing in “python filename.py” where “filename.py” is the program shown in the preceding listing. You should see the LED light blink on and off, and you should also see a new message printed in the terminal window after each light blink cycle. When there have been six cycles of the light blinking on and off, then the light will stop blinking and the program will exit.
In this hands-on example project, you will learn how to control the brightness of a LED using a Python program on the Raspberry Pi 3.
The parts you will need for this hands-on example project include
1 LED
1 10,000-Ω resistor
1 breadboard
The resistor is used to limit the brightness of the LED. If you want a brighter LED, then use a lower-value resistor or no resistor at all.
You can set up the circuit by:
Connecting a ground pin on the Raspberry Pi to the negative terminal of the LED.
Connecting the positive terminal of the LED to one end of a 10,000-Ω resistor.
Connecting the other end of the 10,000-Ω resistor to GPIO pin 14 on the Raspberry Pi (Figure 3-23).
Figure 3-23 | LED fading up and down. |
This example project uses PWM to simulate analog output using digital methods. In PWM, a square wave is generated that consists of digital 1s and 0s. The voltage output is always high or low, but when it is turned on and off very fast, this can simulate an analog output with a varying voltage output from 0 to 3.3 V. The duty cycle is the time that the voltage is high. By changing the duty cycle, we can change the LED’s brightness. A duty cycle of 100 percent means that the LED is on all the time. A duty cycle of 50 percent means that the LED is on half the time, and a duty cycle of 0 percent means that the LED is always off.
The program in this example project:
1. Imports the RPi.GPIO and time modules so that we can use them in our program.
2. Connects GPIO pin 14 on the Raspberry Pi to the LED.
3. Sets the Freq variable that represents the frequency of the PWM for the LED to 50 hertz.
4. Sets the pin numbering to BCM numbering.
5. Sets the pin going to the LED to be an OUTPUT
pin so that voltage can be output to the LED.
6. Sets up PWM using the Freq variable from step 3 (which is set at 50 hertz) on the pin connected to the LED.
7. Sets the PWM to 0 percent, or completely off.
8. Fades the LED up to full brightness and then down to completely off for six cycles. Prints a message to the terminal after each cycle is completed.
9. Stops the PWM.
10. Performs cleanup relating to the GPIO pin that was initialized. See Listing 3-7.
After you type in or download this program from the publisher’s website, run the program by going to the directory where the file is located and typing “python filename.py.” This will run the program. You will see the LED fade up and then down, and after each cycle, you should see a message printed to the screen.
In this hands-on example project, you will learn how to build a Raspberry Pi circuit that allows you to manually set the color of the RGB LED with the standard Raspberry Pi terminal using keyboard input.
The parts you will need for this hands-on example project include
1 RGB LED
1 breadboard
Male-to-female wires
To build the circuit for this example project, you will need to:
Connect the red terminal of the LED to GPIO pin 14 on the Raspberry Pi.
Connect the ground terminal of the LED to a GND terminal on the Raspberry Pi.
Connect the green terminal of the LED to GPIO pin 15 on the Raspberry Pi.
Connect the blue terminal of the LED to GPIO pin 18 on the Raspberry Pi (Figure 3-24).
Figure 3-24 | RGB LED color selection circuit. |
The program in this example project sets the RGB color of the RGB LED by:
1. Importing the RPi.GPIO and time modules into the program for use.
2. Defining pin 18 of the Raspberry Pi as the pin to connect to the blue terminal of the RGB LED.
3. Defining pin 15 of the Raspberry Pi as the pin to connect to the green terminal of the RGB LED.
4. Defining pin 14 of the Raspberry PI as the pin to connect to the red terminal of the RGB LED.
5. Initializing the variables that hold the user input values for the red, green, and blue colors to 0.
6. Setting the frequency used for the PWM for the RGB LED to 50 hertz.
7. Setting the pin numbering system to BCM.
8. Setting the pins on the Raspberry Pi that are connected to the red, green, and blue inputs on the RGB LED to output a voltage by calling the GPIO.setup()
function.
9. Initializing the PWM functions on the Raspberry Pi pins connected to the red, green, and blue inputs on the LED by calling the GPIO.PWM()
function for each pin.
10. Setting the PWM duty cycle on the Raspberry Pi pins connected to the red, green, and blue input pins on the LED to 0 percent, which means that they are turned completely off, by calling the start(0)
function for each pin and setting the input parameter to 0.
11. Continuously asking the user to input an RGB value for the LED and then setting that color by:
a. Asking the user to input a red value using the keyboard by calling the input("Enter Red Value (0-100): ")
function and storing the returned user input. The input prompt message is sent as a parameter. If the returned value is less than 0, then the input while
loop is exited.
b. Repeating step 1 for green and blue, with the only difference being the input prompt message.
c. Changing the duty cycle and thus brightness of the red, green, and blue components of the LED by calling the ChangeDutyCycle(pinnumber)
function with the pin numbers of the pins connected to the red, green, and blue terminals on the RGB LED.
d. Printing out the current color of the LED in red, green, and blue components to the terminal by using the print()
function.
12. Discontinuing the PWM on the Raspberry Pi pins that provide the modulation by calling the stop()
function.
13. Finally, freeing the resources related to the GPIO pins and resetting the pins that were used by calling the GPIO.cleanup()
function. See Listing 3-8.
After you have typed the program in or downloaded it from the publisher’s website, start the program using Python. The program will ask you to enter red, green, and blue values for the LED. After you enter them, the values will be set on the LED. This loop continues until you enter a negative number for a color value, and then the program exits.
In this hands-on example, you will learn how to use a button to fade a LED up and down using pulse-width modulation.
The parts you will need for this hands-on example project include
1 LED
2 10,000-Ω resistors
1 push button
To set up the hardware for this example project, you will need to:
Connect the negative terminal of the LED to GND on the Raspberry Pi.
Connect the positive terminal of the LED to one end of a 10,000-Ω resistor.
Connect the other end of the resistor to GPIO pin 14 on the Raspberry Pi.
Connect one side of the push button to a 3.3-V pin on the Raspberry Pi.
Connect the other end of the push button to a node that includes a 10,000-Ω resistor and GPIO pin 15 on the Raspberry Pi.
Connect the other end of the resistor from the node to GND on the Raspberry Pi (Figure 3-25).
Figure 3-25 | The push button LED fader. |
The program for this example project:
1. Imports the RPi.GPIO and time modules into the program so they can be used.
2. Assigns pin 14 of the Raspberry Pi to the LED.
3. Assigns pin 15 of the Raspberry Pi to the push button.
4. Resets the Brightness
variable, which is used to keep track of the duty cycle of the LED, to 0.
5. Sets the Delta
variable, which is the amount of change in the duty cycle per update, to 1.
6. Sets the frequency of the PWM for the LED to 50.
7. Sets the Raspberry Pi pin numbering system to BCM.
8. Sets the pin on the Raspberry Pi that is connected to the LED as an output pin to provide voltage to the LED.
9. Sets pin 15 on the Raspberry Pi, which is connected to the push button, as an input pin in order to read the voltage generated by a button press. A high reading indicates that the button is pressed, and a low reading indicates that the button is not pressed.
10. Initializes PWM on the Raspberry Pi pin connected to the LED and setting the duty cycle to 0, which means that the LED is turned completely off.
11. Reads the status of the push button by the Raspberry PI by calling the GPIO.input(ButtonPin)
function, which returns the voltage level at the pin ButtonPin
.
12. Updates the Brightness
variable based on the value read from the push button.
13. Clamps the Brightness
variable within the range of 0 (which is fully off) to 100 (which is fully on).
14. Changes the actual brightness of the LED by changing the duty cycle by calling the LEDPWM.ChangeDutyCycle(Brightness)
function with the level of brightness as the input parameter.
15. Prints out the current brightness level of the LED to the terminal.
16. Suspends execution of the program for one-tenth of a second by calling the time.sleep(0.1)
function with 0.1 as an input parameter. This has the effect of slowing down the changes in the brightness of the light. If this statement were left out, the changes in brightness would occur so rapidly that no fading up or down would be seen.
17. Returns program execution to step 11 until there is a keyboard exception such as the user pressing CTRL-C to halt execution of the program.
18. Stops PWM.
19. Resets the GPIO pins by calling the cleanup()
function, and prints out a message to the terminal verifying that program execution has been halted. See Listing 3-9.
Now you need to run the program. Either type the program in and save it or download it from the publisher’s website. Run the program by typing “python filename.py” where the filename is the name of the program. The current brightness of the LED should be continuously displayed on the Raspberry Pi terminal. The brightness should start off as 0. Press the button to increase the brightness. You should see an increase in brightness of the LED. Release the button to decrease brightness. Press CTRL-C to exit the program.
This chapter has discussed basic electrical components and concepts relating to the Arduino and the Raspberry Pi. You learned basic concepts such as the circuit, series and parallel connections, resistors, and Ohm’s law. Next, the color coding of resistors was presented, and you were given a chart that shows how to read a resistor’s value. This was followed by a discussion of LEDs, RGB LEDs, piezo buzzers, potentiometers, push buttons, and breadboards. The rest of the chapter consisted of various hands on example projects involving the Arduino or Raspberry Pi using the components discussed earlier.