Our first circuit

To begin working with digital outputs, we are going to connect a very simple circuit to our Arduino board and write some code to deal with it.

In the rest of the book, I'll present you with different circuits that we will have to assemble and connect to the Arduino board. Regarding the external circuits assembly, nowadays we don't really have to solder all parts to a printed circuit board to get our circuit up and running. We can simply use a bunch of short wires, called jumpers, and a breadboard.

Before going on with our first circuit, let's take a look in detail at what a breadboard is and how to use it.

Using a breadboard

A breadboard is a square panel built in such a way that it allows the connection of the electronic component plugged into it without the need to solder them together or use any other form of connection among them.

Using a breadboard

A typical half size breadboard

As you can see in the preceding picture, the breadboard has a lot of holes distributed in four different areas:

  • Two horizontal rails up and down with two rows of holes
  • Two blocks for components' connections in the middle, usually with columns of five holes

You plug the components' legs into the holes. They are equipped with metallic clips inside that fit the electronic components once inserted. They are distributed in the breadboard in such a way that it connects all holes in every rail's row and every hole in every five-hole columns in the components' area.

To allow you to connect the circuit to the Arduino board or other external components not placed in the breadboard, you should use small pieces of wire that go from a hole in the breadboard to the external component leg.

For more detailed information, with very illustrative images and examples of use, you can visit the excellent Sparkfun tutorial on how to use a breadboard at https://learn.sparkfun.com/tutorials/how-to-use-a-breadboard.

At the moment, you don't have to worry about being very capable with a breadboard, because I'll give you detailed schematics and diagrams on how you should connect every one of the proposed circuits to your breadboard.

The LED circuit

The first circuit we are going to assemble is a simple LED with its current limiting resistance, and we will connect it to a digital output of our Arduino board.

Arduino has two different rows of pin headers:

  • One with the powering pins and analog inputs in the lower side of the board
  • The other in the upper side, with all digital pins

Take a look at the following screenshot:

The LED circuit

An Arduino row of digital pin headers

You can see that some of the pins in the digital row are marked with ~, which, as stated in the board serigraphy, are available for use as analog outputs through the use of Pulse Width Modulation (PWM), about which we will talk more in the next chapter. This doesn't mean that you can't use them as digital pins, but it simply means that when you are going to use analog outputs, you should use only those pins that are marked PWM.

For our example, we will connect a current limiting resistance of about 220 Ohms to the Arduino pin 12, the other leg of the resistance to the LED anode, and finally, the LED cathode will be connected to the ground of our Arduino board, available at the bottom pin header through any of the two pins marked as GND.

The LED circuit

An Arduino row of power and analog pin headers

This way, we will power the LED directly from the Arduino digital output pin in a programmatic form, and it will be our code that will determine when to turn the LED on and off by just setting that digital output pin HIGH or LOW, which will set it to 5V or 0V, respectively, thus providing or not providing current to the LED.

Circuit schematic

I'll always try to give you an electronic schematic of our assemblies so that you can understand what we are going to connect when using the breadboard or if you prefer any other method to make the necessary connections.

The complete assembly for the connection of the LED is as shown in the following schematic:

Circuit schematic

A schematic of an LED connection through a digital pin

Breadboard connections diagram

Once you have understood what we pretend to connect to the Arduino board, it's time to make the real connections using a breadboard.

Here, you have a diagram where you can clearly see the connections that should be made to implement the circuit on the breadboard. All these diagrams have been made using Fritzing, which is an excellent free application that you can find at http://fritzing.org.

Breadboard connections diagram

A diagram of a connection to the LED assembly in a breadboard

In this diagram, you can appreciate something that you should get accustomed to as a good practice when assembling circuits on a breadboard and that you will see in all the diagrams in this book.

As you can see, in the preceding diagram, I have connected a wire from the Arduino GND pin to the first hole of a rail in the breadboard, and from there, I've used another wire to connect that rail's row to the LED cathode. I haven't directly connected the LED cathode to the Arduino GND pin, although I could have done so.

This way, and given that all holes in every rail's row are interconnected, I have all the rail's connections tied to GND, which allows for a very fast and convenient way to connect the negative side of additional components to GND. This is done without the need for a wire from every component's negative side to the Arduino GND pin, which will be impossible to achieve given that there are only two GND pins in the Arduino board.

Later in the book, we will also need to power other electronic components with a positive voltage, and we will use the same technique shown here, that is, we will take a wire from the Arduino 5V pin to another row of a rail, thus getting a whole row with positive voltages ready to power additional components on the breadboard.

Asymmetric blinking code

Once we have assembled the circuit and connected it to our Arduino board, it is time to leave the physical part of our project and begin to work on the logical one: the software we will program our microcontroller with and that will allow us to command the physical side of our project.

For this first example, we will use a modified version of the Blink example you saw in the previous chapter, and will blink the LED in an asymmetrical pattern, that is, having different durations for the on and off cycle of the blinking:

void setup() {                
  pinMode(12, OUTPUT);     
}

void loop() {
  digitalWrite(12, HIGH);
  delay(500);
  digitalWrite(12, LOW);
  delay(100);
}

Although you have the complete code in the code examples accompanying this book, I'd suggest that you type it by yourself, because this is the only way to really learn how to code and try to strictly respect the C programming language syntax.

This simple code will help us to analyze and understand the common structure of an Arduino sketch.

As you can appreciate, the code is divided into two different sections called functions. To be precise, we have a function called setup() and a function called loop(), and each one has a very concrete mission in a sketch:

  • setup(): The purpose of this function is, as its name indicates, to set up the board and its peripherals in the way the sketch needs, for example, setting pins as inputs or outputs, assigning a predefined value to a variable, or initiating a serial communication with your computer. It's only executed once—right at the beginning of the program.
  • loop(): This function is where the real code execution occurs. It runs through every instruction within it in a sequential way from the top to the bottom and begins again once it has reached the last instruction. This function never finishes its execution, so the only way to stop running a sketch in Arduino is by powering the board off.

The logic of the code is quite simple. In the setup() function, we just tell Arduino that we want to use pin 12 as an output using the pinMode(12, OUTPUT) function call that, as you can see, takes two parameters:

  • The first is the pin we want to configure
  • The second is the mode we want it to be in, which is OUTPUT in our case

Once the setup is finished, Arduino enters the loop() function.

The first thing we do there is write a digital HIGH value in pin 12 using the digitalWrite(12, HIGH) function, which generates a 5V signal on the pin, making the LED turn on.

After that, we wait for 500 milliseconds with the call to the delay(500) function and go on by writing a digital LOW value on the pin with the call to the digitalWrite(12, LOW) function, thus generating a 0V signal that makes the LED turn off.

Finally, we wait again but only for 100 milliseconds with delay(100) in this case, just before repeating all the loop code again, that is, turning the LED on again, waiting for half a second, turning it off, and waiting for a tenth of a second and again forever until we power the board off. Simple, isn't it?

Here, you have a picture of the complete circuit connected to the Arduino board. Please note that for the sake of clarity in the photograph, in the final assembly I decided to save one wire by directly connecting the LED cathode to the Arduino GND pin and not connecting it through the rail, as presented in the connections diagram previously.

Asymmetric blinking code

The complete circuit for the asymmetrically blinking LED

C language syntax considerations

This being our first code, I would like to consider the syntax of the C language used in it. This, once understood, will help you minimize the syntax mistakes you could make when writing C code, and that would generate compiling errors. They are as follows:

  • The C language is case-sensitive; this means that it is not the same as a word written in uppercase or lowercase: pinMode() is correct whereas pinmode() isn't.
  • The use of functions includes the accompanying pair of parentheses that serve to specify their parameters. Even when they don't have any parameters, the parentheses have to be included.
  • Every function content or block of code requires the use of a pair of curly brackets to delimit the instructions that belong to them and separate them from the rest of the program. Missing a closing curly bracket would result in a compilation error, which is sometimes hard to detect and correct.
  • As you can see, there is a semicolon at the end of every instruction. They are required by the C language to know where every instruction ends and where the next one begins. A simple carriage return isn't enough.
  • Everything after // or between a /* … */ block is considered to be a comment and thus, it won't be compiled by the Arduino development environment. The use of comments to explain the code is a common and very desirable practice that you should adhere to.

Troubleshooting faults in the circuit

It's difficult to have any trouble with such a simple circuit, but who knows, and perhaps there is something wrong in your assembly and you don't get the expected results. In the case of problems, here is a list of things you should check:

  • Go over your connections carefully, especially in the breadboard. The clips under the plastic housing of the breadboard tend to open wide gradually and sometimes, even when the component or wire is inserted in the hole, it may not make a correct contact.
  • On the Arduino side, be sure to connect the wire going to the resistance to pin 12, which is the one you are referencing in your code to be a digital output and the one you are using to turn the LED on and off. It wouldn't be the first case, as I've spent plenty of time looking for an error in the breadboard's connections when it was just that I had connected the wrong pin in the Arduino board.
  • The LED is a polarized component. This means that its legs have different functions. The anode usually has a longer leg and the cathode has a small flat in the plastic capsule to differentiate them. Ensure that it is connected the right way, that is, the anode is connected to the resistance and the cathode to the wire going to the ground rail.
  • If it still doesn't work, try with another LED, unwire everything, and connect it once again or try with another breadboard.

Dealing with multiple outputs

Once we have our first real circuit up and running, or blinking if you prefer, and once you are a little bit acquainted with the structure of a typical sketch and the C language syntax, why don't we try to make something a little more complicated?

It isn't hard to connect two more LEDs and their corresponding current limiting resistances and build a traffic light and modify our sketch to make it operate like a real one.

Here, you have the schematic of such a circuit:

Dealing with multiple outputs

A traffic light circuit

As you can see, I have connected the resistances to pins 10, 11, and 12. Pins 10 and 11 are marked as PWM capable, but for the purpose of this circuit, this doesn't really matter to us, because we are going to use them digitally by calling the digitalWrite() function later in the code.

In the following breadboard connections diagram, you can see what we talked about previously regarding the creation of a ground rail that would allow us to connect every ground in the circuit in a convenient way. You can see how I've taken different wires from the cathode of every LED to the common ground rail at the bottom.

Dealing with multiple outputs

A breadboard connections diagram for the traffic light circuit

Current limit per pin

There is a very important consideration to be made before going into connecting bigger external circuitry to our Arduino boards.

The Arduino board is only capable of delivering a maximum current of approximately 40 mA per pin and always under a total current delivery of 200 mA for all of them at the same time. Above these limits, your Arduino board could be seriously damaged and get burnt.

In this circuit, with a total of three LEDs and with a power consumption of around 20 mA each, we are sure we won't get into any trouble.

If you have to deal with devices that require higher power consumption, you should consider using a relay or a transistor as an intermediation between the Arduino board and an external power source for the device. In Chapter 4, Controlling Outputs Softly with Analog Outputs, I'll show you how to use a transistor to control a DC motor for this very reason.

Coming back to our example, the code for this circuit won't be much harder than the blinking example used previously, but I'll use it to introduce a very important concept of any programming language: the use of variables to store values that we will use later in the code. In this case, I'll use these variables just to make the code easier to read, but for the purpose of our example, it will be enough.

I'll insert three lines of code before the setup() function that will allow us to declare three variables that we will use to store the pin numbers we will reference later in the rest of the program:

int redLED = 12;
int yellowLED = 11;
int greenLED = 10;

In the setup() function, we are going to configure the pins we want to use by making them all outputs:

pinMode(redLED, OUTPUT);                     
pinMode(yellowLED, OUTPUT);                     
pinMode(greenLED, OUTPUT);

Finally, in the loop() function, we are going to just repeat three times what we have done before, but we'll modify the code so that it turns a different LED on and off each time:

digitalWrite(redLED, HIGH);
delay(500);
digitalWrite(redLED, LOW);
delay(100);
  
digitalWrite(yellowLED, HIGH);
delay(500);
digitalWrite(yellowLED, LOW);
delay(100);
 
digitalWrite(greenLED, HIGH);
delay(500);
digitalWrite(greenLED, LOW);
delay(100);

Here, you have the complete code including some comments so that you can clearly read what is going on:

/*
 Chapter 03 - Interacting with the environment the digital way
 Multiple digital outputs to simulate a traffic light
 By Francis Perea for Packt Publishing
*/

// Global variables
int redLED = 12;
int yellowLED = 11;
int greenLED = 10;

// Configuration of the board.
// All pins are going to be used as outputs
void setup() {                
  pinMode(redLED, OUTPUT);                     
  pinMode(yellowLED, OUTPUT);                     
  pinMode(greenLED, OUTPUT);     
}

// Sketch execution loop
// We repeat the single blink for every LED
void loop() {
  // blink the red LED
  digitalWrite(redLED, HIGH);
  delay(500);
  digitalWrite(redLED, LOW);
  delay(100);
  
  // blink the yellow LED
  digitalWrite(yellowLED, HIGH);
  delay(500);
  digitalWrite(yellowLED, LOW);
  delay(100);
  
  // blink the green LED
  digitalWrite(greenLED, HIGH);
  delay(500);
  digitalWrite(greenLED, LOW);
  delay(100);
  // do it all again
}

Finally, here, you have a photograph of a real assembly, where, once again, I made use of a little trick to save some wires and electronic components—resistances, in this case. Given that we are not going to turn on more than one LED at a time, I've just used a single resistance connected to the cathode of every LED. All LEDs will use it, but they'll use just one at a time, so we can save two resistances. On the other hand, having just a single connection to ground on the opposite leg of the single resistance, I can also save some wires to connect it to the Arduino ground—once again, just for the clarity of the picture.

Current limit per pin

A complete assembly of the traffic light example

Now that you are beginning to master digital outputs, will you be able to make the LED in the middle blink a couple of times before turning it off and prior to turning the lower one on like we usually see in our streets' real traffic lights?

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

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