THIS CHAPTER WILL INTRODUCE YOU to the Arduino and the Raspberry Pi. First, I give a brief explanation of what the Arduino is. Then I specifically address the Arduino Uno, discussing its general features, including its capabilities and key functional components. This is followed by a discussion of the Arduino Integrated Development Environment (IDE) software, which is needed to develop programs for the Arduino. Each key function of the Arduino IDE is reviewed, followed by a hands-on example giving detailed step-by-step instructions on how to set up the Arduino for development and how to run and modify an example program using the Arduino IDE. Next comes the Raspberry Pi. I discuss what the Raspberry Pi is and the specifications for the Raspberry Pi 3. This section tells you how to set up the Raspberry Pi before using it for the first time. Raspberry Pi hardware features are addressed, including the general purpose input-output (GPiO) pin specifications. The final section includes a hands-on example of how to control a light-emitting diode (LED) using the Raspberry Pi.
The Arduino is an open-source microcontroller that uses the C and C++ languages to control digital and analog outputs to devices and electronic components and to read in digital and analog inputs from other devices and electronic components for processing. For example, an Arduino can read a signal from a sensor in a home security system that detects the heat that a human being emits. The sensor sends a signal to the Arduino indicating that a person is in the home. After receiving this information, the Arduino can send commands to a camera such as the ArduCAM Mini digital camera to start taking pictures of the intruder. There are many different Arduino models out there. However, to create the examples in this book, you will need an Arduino model with enough pins to connect the components you desire, such as a camera, Bluetooth adapter, and/or motion sensor. Figure 1-1 shows the official Arduino logo.
Figure 1-1 | Official Arduino logo. |
Note: The official website of the Arduino is www.arduino.cc.
There are a great many Arduino products out there, ranging from models that are small and can actually be worn by the user to models with many digital and analog input-output pins. For the projects in this book, I recommend the Arduino Uno, which is an open-source microcontroller that has enough digital ports to accommodate a camera, a Secure Digital (SD) card reader/writer with enough digital and analog ports for other devices, sensors, lights, and any other gadgets that you may require for your own custom projects. The official Arduino Uno board is made by a company called Arduino SRL, formerly Smart Projects, formed by one of the founders of the Arduino (Figure 1-2). The newer official Arduino Uno boards are slightly different in that they are more blue-green instead of blue in color and contain the Genuino logo under the main Arduino logo. The Genuino trademark is used outside the United States as a result of the split between Arduino founders.
Figure 1-2 | The official Arduino Uno. |
There are also unofficial Arduino Uno boards made by other companies. A good way to tell whether a board is official or unofficial is by the color of a component that is located near the Arduino’s USB port. This component on an official Arduino board is a metallic gold color. The component on an unofficial board is green. The writing on the components also differs (Figure 1-3).
Figure 1-3 | Metallic gold colored component on an official Arduino Uno board. |
A number of other companies also manufacture Arduino Uno boards. Because the Arduino is an open-source item, other companies can legally manufacture the board, and the boards vary in quality and price. Generally, an unofficial Arduino Uno costs around $10, and an official Arduino Uno costs around $20. The distinguishing parts of an official Arduino board are the golden component and the high-quality Arduino and Genuino logos printed on the board (Figure 1-4).
Figure 1-4 | Key parts of an official Arduino Uno. |
Microcontroller: ATmega328P
Operating voltage: 5 V
Input voltage (recommended): 7–12 V
Input voltage limit: 6–20 V
Digital I/O pins: 14 (of which 6 provide PWM output)
PWM digital I/O pins: 6
Analog input pins: 6
DC current per I/O pin: 20 mA
DC current for 3.3-V pin: 50 mA
Flash memory: 32 kB (ATmega328P) (of which 0.5 kB used by boot loader)
SRAM: 2 kB (ATmega328P)
EEPROM: 1 kB (ATmega328P)
Clock speed: 16 MHz
Length: 68.6 mm
Width: 53.4 mm
Weight: 25 g
This section covers the functional components of the Arduino Uno.
The Arduino Uno has a USB connector that is used to connect the Arduino to the main computer development system via standard USB A male to B male cable so that it can be programmed and debugged (Figure 1-5).
Figure 1-5 | USB connector. |
The Arduino Uno has a 9-V battery connector where you can attach a 9-V battery to power the Arduino (Figure 1-6).
Figure 1-6 | Arduino Uno 9-V battery connector. |
There is a Reset button on the Arduino Uno that you can press to reset the board. This restarts the program contained in the Arduino’s memory (Figure 1-7).
Figure 1-7 | Arduino Uno Reset button. |
The Arduino Uno has many digital pins capable of simulating analog output through the process of pulse-width modulation (PWM). For example, a LED light generally has only two modes: on (full brightness) and off (no light emitted). However, with digital PWM, the LED light can appear to have a brightness in between on and off. For instance, with PWM, a LED can start from an off state and slowly brighten until it is at its highest brightness level and then slowly dim until back to the off state. The digital pins on the Arduino Uno are pins 0 through 13. These PWM-capable digital pins are circled in Figure 1-8.
Figure 1-8 | Arduino Uno digital pins. |
The communication section of the Arduino Uno contains pins for serial communication between the Arduino and other devices, such as a Bluetooth adapter or a personal computer. The Tx0 and Rx0 pins are connected to the USB port and are used for communication between your Arduino and your computer by means of a USB cable. The Serial Monitor that can be used for sending data to the Arduino and reading data from the Arduino uses the Tx0 and Rx0 pins. Thus you should not connect anything to these pins if you want to use the Serial Monitor to debug your Arduino programs or to receive user input (Figure 1-9). I will talk more about the Serial Monitor later in this book.
Figure 1-9 | Arduino Uno serial communication. |
The I2C interface consists of an SDA pin (which is pin 4) that is used for data and an SCL pin (which is pin 5) that is used for clocking or driving the device or devices attached to the I2C interface. The SDA and SCL pins are circled in Figure 1-10.
Figure 1-10 | Arduino Uno I2C interface. |
The Arduino Uno has six analog input pins that can read in a range of values instead of just digital values of 0 or 1. The analog input pin uses a 10-bit analog-to-digital converter to transform voltage input in the range of 0 to 5 V into a number in the range between 0 and 1,023 (Figure 1-11).
Figure 1-11 | Arduino Uno analog input. |
The Arduino Uno has outputs for 3.3 and 5 V. One section that provides power is located on the side of the Arduino. You can also provide a separate power source by connecting the positive terminal of the power source to the Vin pin and the ground of the power source to the Arduino’s ground. Make sure that the voltage being supplied is within the Arduino’s voltage range (Figure 1-12).
Figure 1-12 | Arduino Uno 3.3- and 5-V power outputs. |
The ground connections on the Arduino Uno are shown circled in Figure 1-13.
Figure 1-13 | Arduino Uno ground connections. |
Arduino projects can be developed on Windows, Mac, and Linux operating systems. The software needed to develop programs that run on the Arduino can be downloaded from the main website at www.arduino.cc/en/Main/Software.
The following is a summary of the different types of Arduino IDE distributions that are available for download. You will only need to download and install one of these files. The file you choose will depend on the operating system your computer is using.
Windows Installer. This is an .exe file that must be run to install the Arduino IDE.
Windows zip file for non-administrator install. This is a zip file that must be uncompressed in order to install the Arduino IDE. 7-zip is a free file compression and uncompression program available at www.7-zip.org that can be used to uncompress this program.
An Important Note: For Windows XP, I recommend the 1.0.5 r2 version of the Arduino IDE. Later versions may not be stable and may terminate unexpectedly, behave erratically, or may not be able to compile Arduino source code.
Mac OS X 10.7 Lion or newer. This is a zip file that must be uncompressed and installed for users of the Mac operating system.
Linux 32 bits. Installation file for the Linux 32-bit operating system.
Linux 64 bits. Installation file for the Linux 64-bit operating system.
The easiest and cheapest way to start Arduino development is probably by using the Windows version on an older operating system such as Windows XP. In fact, the examples in this book were created using the Windows version of the Arduino IDE running on Windows XP. There are in fact many sellers on Ebay from whom you can buy a used Windows XP computer for around $50 to $100. If you are starting from scratch and are looking for an inexpensive development system for the Arduino, consider buying a used computer with Windows XP. The only caution is that support for Windows XP has ended in the United States and some other parts of the world. In China, Windows XP may still be supported with software updates such as security patches.
Arduino IDE is the program used to develop the program code that runs on and controls the Arduino. For example, to have your Arduino control the lighting state of a LED, you will need to write a computer program in C/C++ using the Arduino IDE. Then you will need to compile the program into a form that the Arduino is able to execute and then transfer the final compiled program using the Arduino IDE. From there the program automatically executes and controls the LED that is connected to the Arduino.
New versions of the Arduino IDE are compiled daily or hourly and are available for download. Older versions of the IDE are also available for downloading at www.arduino.cc/en/Main/OldSoftwareReleases.
This section discusses the key features of the Arduino IDE software. The IDE you are using may be slightly different from the version discussed in this section, but the general functions should still be the same. I won’t go in depth into every detail of the IDE because this section is meant as a quick-start guide and not a reference manual. I will cover the critical features of the Arduino IDE that you will need to get started on the projects in this book (Figure 1-14).
Figure 1-14 | The Arduino IDE. |
The Verify button checks to see whether the program you have entered into the Arduino IDE is valid and without errors (Figure 1-15). These uncompiled programs are called sketches.
Figure 1-15 | The Verify button. |
The Upload button first verifies that the program in the IDE is a valid C/C++ program with no errors, compiles the program into a form the Arduino can execute, and then finally transfers the program via the USB cable connected to your computer to your Arduino board (Figure 1-16).
Figure 1-16 | The Upload button. |
The New File button creates a new blank file or sketch inside the Arduino IDE, where you can create your own C/C++ program for verification, compilation, and transfer to the Arduino (Figure 1-17).
Figure 1-17 | The New File button. |
The Open File button is used to open and load the Arduino C/C++ program source code from a file or load various sample source codes from example Arduino projects that are included with the IDE (Figure 1-18).
Figure 1-18 | The Open File button. |
The Save button saves the sketch on which you are currently working to disk. A File Save dialog is brought up first, and then you will be able to save the file on your computer’s hard drive (Figure 1-19).
Figure 1-19 | The Save button. |
The Serial Monitor button brings up the Serial Monitor debug program, where you can examine the output of debug statements from the Arduino program. The Serial Monitor can also accept user input that can be processed by the Arduino program (Figure 1-20). I will discuss the Serial Monitor and how to use it as a debugger and input console later in this book.
Figure 1-20 | The Serial Monitor button. |
The main window of the Arduino IDE also includes other important features. The title bar of the IDE window contains the Arduino IDE version number. In Figure 1-21, the Arduino version number is 1.0.5 r2. The sketch name is displayed in the source code tab and is “Blink,” which is one of the sample sketches that comes with the Arduino IDE. The source code area, which is the large white area with scrollbars on the right side and bottom, is where you enter your C/C++ source code that will control the behavior of the Arduino. The bottom black area in the IDE is where warning and errors are displayed from the code verification process. At the bottom left-hand corner of the IDE is a number that represents the line number in the source code where the user’s cursor is currently located. In the lower right-hand corner of the IDE is the currently selected Arduino model and COM port to which the Arduino is attached.
Figure 1-21 | The general IDE. |
In this hands-on example, I will show you how to set up the Arduino development system on your Windows-based PC or Mac. First, you need to obtain an Arduino board and USB cable. Then you must install the Arduino IDE and Arduino hardware device drivers. Then I will show you how to load in the “Blink” example sketch. I tell you how to verify that the program is without syntax errors, how to upload it onto the Arduino, and how to tell whether the program is working. Finally, I discuss how the Blink program code works and show you how to modify it.
You can purchase an official Arduino Uno board from a distributor listed on www.arduino.cc/en/Main/Buy or www.Arduino.org. The first website is still generally considered the main website for Arduino. However, the second website is run by the people actually making Arduino boards. The split among the founders of the Arduino mentioned earlier can be seen here in terms of who is designated as a distributor of an “official” Arduino board.
A second option is to buy an unofficial Arduino Uno made by a seller not listed as an official distributor by either arduino.cc or arduino.org. These boards are generally a lot cheaper than “official” Arduino boards. However, the quality may vary widely between manufacturers or even between production runs of the same manufacturer.
Official Arduino boards generally do not come with a USB cable, but many unofficial boards do come with a short USB cable. Longer Arduino-compatible USB cables (such as 6- or 10-foot cables) can be bought on Amazon.com or eBay.com. I purchased a “Mediabridge USB 2.0 – A Male to B Male Cable (10 Feet) – High-Speed with Gold-Plated Connectors – Black” from Amazon.com for my “official” Arduino Uno, and its seems to work well. Make sure that you get the right kind of USB cable with the right connectors on each end. The rectangular end of the USB cable is connected to your computer, and the square end is connected to your Arduino (Figure 1-22).
Figure 1-22 | Arduino USB cable. |
The Arduino IDE has versions that can run on Windows, Mac, and Linux operating systems. The Arduino IDE can be downloaded from www.arduino.cc/en/Main/Software. I recommend installing the Windows-executable version if you have a Windows-based computer. Follow the directions in the pop-up windows.
Note: The Arduino website also contains links to instructions for installing the Arduino IDE for Windows, Mac, and Linux at www.arduino.cc/en/Guide/HomePage. The installation for Linux depends on the exact version of Linux being used.
The next step is to connect your Arduino to your computer using the USB cable. If you are using Windows, it will try to automatically install your new Arduino hardware. Follow the directions in the pop-up windows to install the drivers. Decline to connect to Windows Update to search for drivers. Select “Install the software automatically” as recommended. If you are using XP, ignore the pop-up window warning about the driver not passing Windows logo testing to verify its compatibility with XP.
If this does not work, then instead of selecting “Install the software automatically,” specify a specific driver location, which is the “drivers/FTDI” directory under your main Arduino installation directory.
Next, we need to load the “Blink” sketch example into the Arduino IDE. Click the Open file button to bring up the menu. Under “01. Basics,” select the “Blink” example to load (Figure 1-23).
Figure 1-23 | Loading the “Blink” sketch. |
The code that is loaded into the Arduino IDE should look like the code in Listing 1-1.
Click the Verify button to verify that the program is valid C/C++ code and is error-free (Figure 1-24).
Figure 1-24 | Verifying the “Blink” sketch. |
Before uploading the sketch to your Arduino, make sure the type of Arduino under the “Tools > Board” menu item is correct. In our case, the board type should be set to be “Arduino Uno” (Figure 1-25).
Figure 1-25 | Set the Arduino type to “Arduino Uno.” |
Next, make sure that the serial port is set correctly to the one that is being used by your Arduino. Generally, Com1 and Com2 are reserved, and the serial port to which the Arduino will be connected is Com3 or higher (Figure 1-26).
Figure 1-26 | Set the serial (Com) port. |
If you are using a Mac, then the serial port selection should be something like “/dev/tty.usbmodem” instead of a COMxx value.
Next, with the Arduino connected, press the Upload button to verify, compile, and then transfer the “Blink” example program to the Arduino. After the program has finished uploading, you should see a message that the upload has been completed in the Warnings/error window at the bottom of the IDE inside the black window (Figure 1-27).
Figure 1-27 | Upload to the Arduino. |
Note: The Upload button does the job of the Verify button and also uploads the final compiled program to the Arduino.
The final result will be a blinking light on the Arduino board near digital pin 13. By design, the Arduino board has a built-in LED connected to pin 13. So this example did not require you to connect an actual separate LED to the Arduino board (Figure 1-28).
Figure 1-28 | Built-in LED. |
The default of the program is to turn on the LED for 1 second and then turn it off for 1 second. The code that controls the timing is located in the loop()
function. The digitalWrite()
function sets the variable LED, which is pin 13, to either on, which is HIGH
, or off, which is LOW
. The delay()
function suspends execution of the program for 1,000 milliseconds, or 1 second, so that the LED is set on for 1 second and off for 1 second (Listing 1-2).
Play around with the values in the delay()
functions, lengthening or shortening the time the LED stays on and/or lengthening or shortening the time the LED stays off. For example, to have the LED flash briefly, shorten the first delay value to 100. This will shorten the time that the LED stays on. Upload the new sketch to the Arduino by pressing the Upload button. After it has finished uploading, you will see a message in the black Warnings/error message window at the bottom of the IDE. Look at the LED on the Arduino. The timing of the LED on/off pattern should have changed.
Raspberry Pi is a small, inexpensive computer based on the Linux operating system. The computer itself sells for around $35 and was originally designed as a learning tool to get young people and students interested in pursuing a career in computer programming. The official website for the Raspberry Pi is located at www.raspberrypi.org.
Many models of the Raspberry Pi have been produced, but the type of Raspberry Pi that I will use in this book is the newest and most popular Raspberry Pi: the Raspberry Pi 3 Model B. This model replaces the Raspberry Pi 2 and is recommended for use in schools and for general purpose use. For those who want to embed a Raspberry Pi as part of a larger project or require a Raspberry Pi that uses low power, then the Raspberry Pi 0 or Model A+ is recommended. The specifications of the Raspberry Pi 3 Model B are as follows:
1.2-GHz 64-bit quad-core ARMv8 CPU
802.11n wireless LAN
Bluetooth 4.1
Bluetooth Low Energy (BLE)
1-GB RAM
Four USB ports
40 GPiO pins
Full HDMI port
Ethernet port
Combined 3.5-mm audio jack and composite video
Camera interface (CSI)
Display interface (DSI)
Micro SD card slot (now push-pull rather than push-push)
VideoCore IV 3D graphics core
The Raspberry Pi 3 is manufactured as a small single board similar to the size of a credit card without a case containing all the above-mentioned components (Figure 1-29).
Figure 1-29 | Top view of the Raspberry Pi 3 hardware layout. |
The Raspberry Pi 3 consists of the following major components, which are labeled in Figure 1-29 as:
Item 1: Two USB ports stacked on top of each other
Item 2: A second set of two USB ports stacked on top of each other
Item 3: Ethernet socket for connecting to a network router
Item 4: A 3.5-mm jack for audio and video output to a monitor or television
Item 5: An MIPi camera serial interface (CSI)
Item 6: A High Definition Multimedia Interface (HDMI) port for video output to a monitor or television
Item 7: GPiO pins that will be used to connect sensor devices to the Raspberry Pi in this book
Item 8: A Display Serial Interface (DSI) that is used to connect the Raspberry Pi to a liquid-crystal display (LCD)
Item 9: A micro USB socket used for power input to the Raspberry Pi
The bottom of the Raspberry Pi 3 contains a micro SD card reader/writer that serves as a storage device like a hard drive would on a desktop computer. The micro SD stores the Raspberry Pi’s operating system, program applications, and data generated by the program applications and the user. On the Raspberry Pi 3, the micro SD card reader/writer is of the push-pull type. This means that you will need to push the SD card into the slot to have the SD card be read from and written to, and then you will need to pull the card out to remove it from the SD card slot (Figure 1-30).
Figure 1-30 | Bottom view of the Raspberry Pi 3. |
With the Raspberry Pi oriented like the one in Figure 1-29, the GPiO pin specifications are as shown in Figure 1-31.
Figure 1-31 | Raspberry Pi 2 and Raspberry Pi 3 GPiO pin numbering. |
The symbols on the pins denote the following:
5V: This is a 5-V output source from the Raspberry Pi that can be used to power your custom circuit.
3.3V: This is a 3.3-V output source from the Raspberry Pi that can be used to power your custom circuit.
G: Ground pin.
EE: EEPROM-related pin (which will not be used in this book).
Number: This is the number of the GPiO pin.
This section will tell you what you will need to set up your Raspberry Pi computer system and how to perform the actual setup. At the bare minimum, you will need
A Raspberry Pi 3 board
A USB keyboard
A USB mouse
A micro USB power adapter that can provide 2.5-A power
An HDMI-compatible monitor or TV (which I recommend) or a monitor with composite inputs or a VGA monitor and an HDMI-to-VGA adapter (I recommend an HDMI monitor because it provides sharp resolution and sound output. The composite output is of a lower-quality resolution, and using a VGA monitor with a Raspberry Pi requires you to make some changes to the Raspberry Pi’s configuration file.)
A micro SD card with new out of box software (NOOBS) on it
Preferably some kind of case for your Raspberry Pi 3 board to protect it against static electricity and small spills of liquid
If you are just beginning in Raspberry Pi development, then I recommend that you get one of the Raspberry Pi 3 starter kits, which are widely available online on such websites as Amazon.com. Many of the starter kits have all of the items listed above. In addition, if you do not have an HDMI monitor, you can usually find a small one for around US$50 on Amazon.com. These monitors are generally around 10 inches in display size and can be used as portable monitors for your Raspberry Pi 3 system.
To start using your Raspberry Pi, you should
1. Connect the keyboard, mouse, and HDMI monitor to your Raspberry Pi.
2. Insert your SD card with the NOOBS into the Raspberry Pi’s micro SD card reader/writer.
3. Turn on your Raspberry Pi by plugging in the micro USB power adapter. An important thing to note is that the Raspberry Pi does not have an on/off switch.
4. The NOOBS setup program will start running. This program will install the actual Raspberry Pi operating system, which is called Raspbian. Follow the directions that appear on the screen to install the software. You should see a pop-up window that looks like the one shown in Figure 1-32. Check the box next to the Raspbian selection, and click on the Install button.
Figure 1-32 | The NOOBS operating system installation screen. |
The programming language that we will be using in this book for projects involving the Raspberry Pi is the Python programming language. The Raspberry Pi has a Python development environment called IDLE. IDLE provides you with a read-evaluate-print-loop (REPL) that allows you to continuously enter Python statements and have them executed by the Python language. The output of these statements is also displayed within IDLE. You can start the Python IDLE program by clicking on “Python 3” under the Menu > Programming menu (Figure 1-33).
Figure 1-33 | The Python 3 development environment. |
From within the IDLE program you can also create and save new files. An alternative to using IDLE to create Python programs is to use a text editor such as Vim, Nano, or LeafPad and execute the Python program by typing “python filename.py” on the command line.
This section presents a simple hands-on example of creating a blinking LED using the Raspberry Pi 3.
For this hands-on example, you will need
One LED
One breadboard
Two wires with one end having a female plug to connect to the Raspberry Pi’s GPiO pins and the other end having a male plug to connect to the breadboard
1. Insert the short leg of the LED, which is the negative side, into a hole on the breadboard.
2. Insert the long leg of the LED, which is the positive side, into a different hole on the breadboard that is disconnected from the node in step 1. Note: Breadboards generally have horizontal rows of nodes of about five holes each that are connected together. Some breadboards have a positive row of holes that are connected together and a negative row of holes that are connected together.
3. Attach a wire from a ground pin on the Raspberry Pi to the ground node on the breadboard that contains the negative side of the LED.
4. Attach a wire from GPiO pin number 14 to the node on the breadboard that contains the positive side of the LED.
Figure 1-34 shows a simplified graphic representation of how to hook the LED up to the Raspberry Pi 3 board.
Figure 1-34 | Blinking LED on a Raspberry Pi 3 board. |
Now you will need to set up the software that will run on the Raspberry Pi itself to control the hardware you just set up. In order to control the blinking of a LED from the Raspberry Pi, you need to do the following:
1. Import the LED class from the gpiozero
library.
2. Import the sleep function from the time
library.
3. Create a new LED object that is connected to GPiO pin 14, and then assign this object to the led
variable.
4. Execute the following in an infinite loop:
a. Turn the LED on by calling the led.on()
function.
b. Wait for 1 second by calling the sleep()
function with 1 as a parameter.
c. Turn off the LED by calling the led.off()
function.
d. Wait for 1 second by calling the sleep()
function with 1 as a parameter.
See Listing 1-3.
After you finish typing in this program or downloading it from the publisher’s website, run the program by typing the command “python filename.py.” Filename.py is the filename of the program. The LED should turn on for 1 second and then turn off for 1 second (Figure 1-35).
Figure 1-35 | The final blinking LED project. |
Play around with the times that the LED turns on and off by changing the parameters to the sleep()
function.
In this chapter I introduced you to the Arduino and the Raspberry Pi. I started off by discussing the Arduino Uno and covering the details of the UNO’s hardware configuration. Then I covered the Arduino IDE, which is needed to create programs for the Arduino platform. This was followed by a simple hands-on example using the Arduino to control the built-in LED. Next, I covered the Raspberry Pi, starting with the specifications for the Raspberry Pi 3 and concluding with a detailed hardware overview, including the exact specifications for the GPiO pins. Then I showed you how to set up the Raspberry Pi and install its operating system using NOOBS. The chapter ended with another hands-on example, this time using the Raspberry Pi to blink a LED on and off.