Book Image

C Programming for Arduino

By : Julien Bayle
Book Image

C Programming for Arduino

By: Julien Bayle

Overview of this book

Physical computing allows us to build interactive physical systems by using software & hardware in order to sense and respond to the real world. C Programming for Arduino will show you how to harness powerful capabilities like sensing, feedbacks, programming and even wiring and developing your own autonomous systems. C Programming for Arduino contains everything you need to directly start wiring and coding your own electronic project. You'll learn C and how to code several types of firmware for your Arduino, and then move on to design small typical systems to understand how handling buttons, leds, LCD, network modules and much more. After running through C/C++ for the Arduino, you'll learn how to control your software by using real buttons and distance sensors and even discover how you can use your Arduino with the Processing framework so that they work in unison. Advanced coverage includes using Wi-Fi networks and batteries to make your Arduino-based hardware more mobile and flexible without wires. If you want to learn how to build your own electronic devices with powerful open-source technology, then this book is for you.
Table of Contents (21 chapters)
C Programming for Arduino
Credits
About the Author
Acknowledgement
About the Reviewers
www.PacktPub.com
Preface
Index

What is electricity?


Arduino is all about electronic, and electronic refers to electricity. This may be your first dive into this amazing universe, made of wires and voltages, including blinking LEDs and signals. I'm defining several very useful notions in this part; you can consider turning down the corner of this page and to come back as often as you need.

Here, I'm using the usual analogy of water. Basically, wires are pipes and water is electricity itself.

Voltage

Voltage is a potential difference. Basically, this difference is created and maintained by a generator. This value is expressed in Volt units (the symbol is V).

The direct analogy with hydraulic systems compare the voltage to the difference of pressure of water in two points of a pipe. The higher the pressure, the faster the water moves, for a constant diameter of pipe of course.

We'll deal with low voltage all throughout this book, which means nothing more than 5 V. Very quickly, we'll use 12 V to supply motors and I'll precise that each time we do.

When you switch on the generator of closed circuits, it produces and keeps this potential difference. Voltage is a difference and has to be measured between two points on a circuit. We use voltmeters to measure the voltage.

Current and power

Current can be compared to the hydraulic volume flow rate, which is the volumetric quantity of flowing water over a time interval.

The current value is expressed in Ampères (the symbol is A). The higher the current, the higher will be the quantity of electricity moving.

A flow rate doesn't require two points to be measured as a difference of pressure; we only need one point of the circuit to make our measurement with an equipment named Ampere meter.

In all of our applications, we'll deal with direct current (DC), which is different from alternative current (AC).

Power is a specific notion, which is expressed in Watt (the symbol is W).

Following is a mathematical relationship between voltage, current, and power:

P = V x I

where, P is the power in Watt, V the voltage in V, and I the current in Ampères.

Are you already feeling better? This analogy has to be understood as a proper analogy, but it really helps to understand what we'll make a bit later.

And what are resistors, capacitors, and so on?

Following the same analogy, resistors are small components that slow down the flow of current. They are more resistive than any piece of wire you can use; they generally dissipate it as heat. They are two passive terminal components and aren't polarized, which means you can wire them in both directions.

Resistors are defined by their electrical resistance expressed in Ohms (the symbol is Ω).

There is a direct mathematical relation between voltage measured at the resistor sides, current, and resistance known as the Ohm's law:

R = V / I

where R the electrical resistance in Ohms, V the voltage in Volts, and I the current in Ampères.

For a constant value of voltage, if the resistance is high, the current is low and vice-versa. It is important to have that in mind.

On each resistor, there is a color code showing the resistance value.

There are many types of resistors. Some have a constant resistance, some others can provide different resistance values depending on physical parameters such as temperature, or light intensity for instance.

A potentiometer is a variable resistor. You move a slider or rotate a knob and the resistance changes. I guess you begin to understand my point…

A capacitor (or condenser) is another type of component used very often. The direct analogy is the rubber membrane put in the pipe: no water can pass through it, but water can move by stretching it.

They are also passive two-terminal components but can be polarized. Usually, small capacitors aren't.

We usually are saying that capacitors store potential energy by charging. Indeed, the rubber membrane itself stores energy while you stretch it; try to release the stretched membrane, it will find its first position.

Capacitance is the value defining each capacitor. It is expressed in Farads (the symbol is F).

We'll stop here about capacitance calculations because it involves advanced mathematics which isn't the purpose of this book. By the way, keep in mind the higher the capacitance, more will be the potential the capacitor can store.

A diode is again a two-terminal passive component but is polarized. It lets the current pass through it only in one direction and stop it in the other. We'll see that even in the case of direct current, it can help and make our circuits safer in some cases.

LEDs are a specific type of diode. While the current passes through them in the correct direction, they glow. This is a nice property we'll use to check if our circuit is correctly closed in a few minutes.

Transistor is the last item I'm describing here because it is a bit more complex, but we cannot talk about electronics without quoting it.

Transistors are semiconductor devices that can amplify and switch electronics signals and power, depending on how they are used. They are three-terminal components. This is the key active component of almost all modern electronics around us. Microprocessors are made of transistors and they can even contain more than 1 billion of them.

Transistors in the Arduino world are often used to drive high current, which couldn't pass through the Arduino board itself without burning it. In that case, we basically use them as analogue switches. When we need them to close a circuit of high currents to drive a motor for instance, we just drive one of their three terminals with a 5 V coming from the Arduino and the high current flows through it as if it had closed a circuit. In that case, it extends the possibilities of the Arduino board, making us able to drive higher currents with our little piece of hardware.

Wiring things and Fritzing

With the previous analogy, we can understand well that a circuit needs to be closed in order to let the current flow.

Circuits are made with wires, which are basically conductors. A conductor is a matter with a resistance near to zero; it lets the current flow easily. Metals are usually good conductors. We often use copper wires.

In order to keep our wiring operations easy, we often use pins and headers. This is a nice way to connect things without using a soldering iron each time!

By the way, there are many ways to wire different components together. For our prototyping purpose, we won't design printed circuit board or even use our soldering iron; we'll use breadboards!

A breadboard with its buses blue and red and its numerous perforations

Breadboards are the way to rapid prototyping and this is the way to go here.

Basically, breadboards consists of a piece of plastic with many perforations in which there are small pieces of conductors allowing to connect wires and components' leads inside.

The distance between two perforations is 2.54 mm (equal to 0.1") that is a standard; for instance, dual in-line package integrated circuits' leads are all separated by this particular distance and thus, you can even put IC on breadboards.

As we saw on the previous screenshot, there are buses and terminals strips.

Buses are series of five perforations in the central part and put in column for which the underlying conductors are connected. I have surrounded one bus with a green stroke.

Terminals are special buses usually used for power supplying the circuit and appear in between blue and red lines. Usually, we use blue for ground lines and red for voltage source (5 V or 3.3 V in some cases). A whole line of terminals has its perforations all connected, providing voltage source and ground easily available on all the breadboard without having to use a lot of connection to the Arduino. I surrounded 2 of the 4 terminals with red and blue strokes.

Breadboards provide one of the easiest ways of prototyping without soldering. It also means you can use and reuse your breadboards throughout the years!

What is Fritzing?

I discovered the open source Fritzing project (http://fritzing.org) when I needed a tool to make my first master classes slideshows schematic around the Protodeck controller (http://julienbayle.net/protodeck) I built in 2010.

Fritzing is defined as an open source initiative to support designers, artists, researchers and hobbyists to work creatively with interactive electronics. It sounds as if it had been made for us, doesn't it?

You can find the Fritzing's latest versions at http://fritzing.org/download/.

Basically, with Fritzing, you can design and sketch electronic circuits. Because there are many representations of electronic circuits, this precious tool provides two of the classic ones and a PCB design tool too.

Considering the first practical work we are going to do, you have to take your breadboard, your Arduino, and wire the lead and the resistor exactly as it is shown in the next screenshot:

The breadboard view showing our first circuit

The breadboard view is the one that looks the most like what we have in front of us on the table. You represent all wires and you connect a virtual breadboard to your Arduino and directly plug components.

The magic lies in the fact that the schematic is automatically build while you are sketching in the breadboard view. And it works both ways! You can make a schematic, and Fritzing connect components in the breadboard view. Of course, you'd probably have to place the part in a more convenient or aesthetical way, but it works perfectly fine. Especially, the Autorouter helps you with making all wires more linear and simple.

In the next screenshot, you can see the same circuit as before, but shown in the schematic view:

The schematic view representing the circuit diagram

There are a lot of components already designed especially for Fritzing and you can even create yours quite easily. The page to visit for this purpose is http://fritzing.org/parts/.

The native library contains all parts required in all schematics of this book from all Arduino boards, to any discrete components and IC too. Indeed, all schematics of this book have been made using Fritzing!

Now that you know how to wire things without any soldering iron, and how to quietly sketch and check things on your computer before you do it for real on your desktop, let's learn a bit about power supply.

Power supply fundamentals

We learned a bit more about electricity before, but how can I supply all my circuits in real life?

Arduino boards can be supplied in three different ways:

  • By our computer via the USB cable (5 V is provided)

  • By a battery or a direct external Power Supply Unit (PSU) / Adapter

  • By attaching a regulated 5 V to the +5 V pin

The USB cable contains four cables: two for data communication purpose and two for power supply. Those latter are basically used to supply Arduino when you are connecting it to the computer via USB.

USB is a special communication bus that provides 5 V but no more than 500 mA. (0.5 A) It means we have to use another supply source in special projects where we need a lot of LED, motors, and other devices that drive a lot of current.

Tip

What adapter can I use with my Arduino?

Arduino Uno and Mega can be directly supplied by DC Adapter but this one has to respect some characteristics:

  • The output voltage should be between 9 V and 12 V

  • It should be able to drive at least 250 mA of current

  • It must have a 2.1 mm power plug with center positive

Usually, if you ask yourself about the fact whether to use an adapter or not, it means you need more current than the USB's 500 mA (Practically, ask yourself this question whether you need around 400 mA).

Using USB or the 2.1 mm power plug with an adapter are the safest ways to use Arduino boards for many reasons. The main one is the fact that those two sources are (hopefully) clean, which means they deliver a regulated voltage.

However, you have to change something on the board if you want to use one or the other source: a jumper has to be moved to the right position:

On the left, the jumper is set to USB power supply and on the right, it is set to external power supply

Usually, an idle Arduino board drains around 100 mA and, except in specified cases (see Chapter 9, Making Things Move and Creating Sounds), we'll use the USB way of supply. This is what you have to do now: plug in the USB cable both in the Arduino and your computer.

Launch the Arduino IDE too, and let's move further to the hardware Hello World of our system, I call that the Hello LED!

Hello LED!

If your Arduino doesn't contain any firmware, the LED probably does nothing. If you check the built-in LED on the Arduino board itself, that one should blink.

Let's take the control over our external cute LED plugged in the breadboard right now.

What do we want to do exactly?

If you remember correctly, this is the first question we have to ask. Of course, we bypassed this step a bit especially about the hardware part because I had to explain things while you were wiring, but let's continue the prototyping process explained in part by checking the code and uploading it.

We want to make our LED blink. But what blink speed ? How much time? Let's say we want to make it blink every 250 ms with a one second pause between the blinks. And we want to do that infinitely.

If you check the schematic, you can understand that the LED is put between the ground, and the line to the digital output pin number 8.

There is a resistor and you now know that it can consume a bit of energy by resisting to the current flowing to the LED. We can say the resistor protects our LED.

In order to make the LED light up, we have to create a flow of current. Sending +5 V to the digital output number 8 can do this. That way, there will be a potential difference at the two leads of the LED, driving it to be lighted. But the digital output shouldn't be at +5 V at each time. We have to control the moment when it will provide this voltage. Still okay?

Let's summarize what we have to do:

  1. Put the 5 V to the digital output 8 during 250ms.

  2. Stop to drive the digital output 8 during 1s.

  3. Restart this every time the Arduino is powered

How can I do that using C code?

If you followed the previous page correctly, you already have your Arduino board wired to the computer via your USB cable on one side, and wired to the breadboard on the other side.

Now, launch your Arduino IDE.

Start with a new blank page

If you already tested your IDE by loading some examples, or if you already wrote some piece of code, you have to click on the New icon in order to load a blank page, ready to host our Blink250ms code:

A nice and attractive blank page

Setting up the environment according the board we are using

The IDE has to know with which board it will have to communicate. We will do it in the following steps:

  1. Go to the Tools menu and choose the correct board. The first one is Arduino Uno:

    Choose the board you are using

  2. Once we have done that, we have to choose the correct serial port. Go to the Tools menu again and choose the correct serial port:

    • On OS X, the correct one begins with /dev/tty.usbmodem for both Uno and Mega 2560 and with /dev/tty.usbserial for older boards.

    • On Windows, the correct port is usually COM3 (COM1 and COM2 are often reserved by the operating system). By the way, it can also be COM4, COM5, or whatever else. To be sure, please check the device manager.

    • On Linux, the port is usually /dev/ttyUSB0:

    Choose the serial port corresponding to your board

Now, our IDE can talk to our board. Let's push the code now.

Let's write the code

The following is the complete code. You can find it in the zip file in the Chapter01/Blink250ms/ folder:

Tip

Downloading the example code

You can download the example code files for all Packt books you have purchased from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

/*
  Blink250ms Program
  Turns a LED connected to digital pin 8 on for 250ms, then off for 1s, infinitely.
  Written by Julien Bayle, this example code is Creative Commons CC-BY-SA
 */
 
// Pin 8 is the one connected to our LED
int ledPin = 8;                // ledPin is an integer variable initialized at 8

// --------- the setup routine runs once when you power up the board or push the reset switch
void setup() {                
  pinMode(ledPin, OUTPUT);     // initialize the digital pin as an output because we want it to source a current
}

// --------- the loop routine runs forever
void loop() {
  digitalWrite(ledPin, HIGH);   // turn the LED on (HIGH is a constant meaning a 5V voltage)
  delay(250);                   // wait for 250ms in the current state
  digitalWrite(ledPin, LOW);    // turn the LED off (LOW is a constant meaning a 5V voltage)
  delay(1000);                  // wait for 1s in the current state
}

Let's comment it a bit. Indeed, we'll learn how to code our own C code in the next chapter, then I'll only describe this one and give you some small tips.

First, everything between /* and */, and everything after // are just comments. The first form is used for comments more than one line at a time, and the other one is for one line commenting only. You can write any comments like that and they won't be considered by the compiler at all. I strongly advice you to comment your code; this is another key to succeed.

Then, the first part of the code contains one variable declaration and initialization:

int ledPin = 8;                

Then, we can see two particular structures between curly braces:

void setup() {                
  pinMode(ledPin, OUTPUT);     
}
void loop() {
  digitalWrite(ledPin, HIGH);   
  delay(250);                   
  digitalWrite(ledPin, LOW);    
  delay(1000);                  
}

The first one (setup()) is a function that is executed only one time when the Arduino board is started (or reseted); this is the place where we are telling the board that the pin where the LED is connected is an output, that is, this pin will have to drive current while activated.

The second one (loop()) is a function executed infinitely when the Arduino board is supplied. This is the main part of our code in which we can find the steps we wanted to light up the LED for 250 ms and switch off the LED for 1 s, repeatedly.

Let's upload the code, at last!

If you correctly followed and manipulated the hardware and the IDE as explained before, we are now ready to upload the code on the board.

Just click on the Upload button in the IDE. You'll see the TX and RX LEDs blinking a bit and … your LED on your breadboard should blink as expected. This is our very first HELLO LED! example and I hope you liked it.

If you want to tweak the code a bit, you can replace the following line:

delay(1000);

With the following line, for instance:

delay(100);

Now upload this new code again and see what happens.