E2 Laboratory 02


Overview of this week's lab.

The purpose of Lab 1 is to introduce basic circuits that you can make using digital input and output on the Arduino Uno. There are four parts that need to be completed.

  1. Blink an LED
  2. Add a Push button
  3. Better PushButton
  4. "Flip a Coin"
  5. To turn in (directions on what to turn in on moodle)

Materials

The Breadboard

This image shows an example of a solderless breadboard as seen from the front ant the back. There are many short horizontal metal connectors (as seen on the back view on the right), and a few longer vertical connectors near the left and right edges. These connectors will act as wires between component that we will insert into the top side. .

The image above depicts a breadboard with several components. A yellow wire comes in from the top and is inserted in a hole as shown. Now any component inserted into one of the 5 horizontal holes (highlighted in green) will be electrically connected to the yellow wire. In this case we have inserted one end of a resistor. THe other end of the resistor is attached to a hole in the fifth row down. This resistor is attached to the top lead of the LED. In the same way the bottom lead is attached to one end of a black wire. The other end of the black wire is attached to a hole in one of the vertical columns. These are somewhat different than the other connections in that each of the columns along the side extends all the way down the length of the breadboard. So any component attached to one of the highlighted holes in the vertical strip will be connected to our black wire.

You can make circuits by connecting components to different rows and collumns. This allows convenient prototyping without soldering, which you will learn how to do in a later lab.

Resistor

Resistors "resist" the flow of electricity, or current. The orientation in the circuit does not matter; they have no polarity. The resistance in Ohms can be determined by the colors of the bands. Here is a chart to see how the bands convert to the resistor's value.

LED

Light Emitting Diodes (LEDs) only let current pass in one direction, so we say they have polarity; they have a positive and negative lead. The longer lead is the anode, and it is positive. The shorter lead is the cathode, which is negative. Usually the negative side of the plastic part of the LED will be flat.

Switches

Physical Device Schematic Diagram Pinout
A pushbutton is a type of switch that closes, and makes an electrical connection, when you press the button. It can be used for digital input. Note that the switch actually has 4 leads attahced to it. Leads 1 and 2 are always connected to each other as are pins 3 and 4. The pins are all connected when you press on the switch. Pins 1 and 2 (or 3 and 4) are both on the longer side. To make sure you get it working correctly you can simply use diagonal pins on the physical switch to represent the two pins on the schematic.

Voltage Sources

The Arduino has two constant voltage sources that we will use. The first is called "ground" which is our reference for 0 volts. It has the schematic symbol shown above. The second reference we will use is called Vcc and we will represent it as a voltage source, or battery, with one side attached to ground, as shown. For the Arduino, Vcc is always at 5 Volts.

 

Task 1: Blink an LED

The first task is to understand the code and create a circuit needed to blink an LED. You will be using digital input and output to write your first Arduino progam. This may sound simple but it requires knowledge of the Arduino language and syntax to implement. All that is needed to run this code is the Arduino board since it comes with a built in LED, but to get practice with creating circuits you will create the circuit on a breadboard. To start, make sure Arduino is plugged in to the USB port on your computer and then open up the Arduino IDE. You can find this by searching for Arduino in Start.

Port Identification <click here for link to help page>

Once you have your Arduino set up, we can begin looking at the code.

Below you can find the code for "Blink" without any comments. After reading through how each line works, you will copy and paste this code into the Arduino IDE and add comments. Comments are notes in your code that explain what the code is doing without changine the program. The Arduino language uses C, so to make a one-line comment, type "//" before a line. If your comment is more than one line, you can use "/* ... */", for example:

/* This is a comment! */
/* So
is this
*/

int led = 13;       	// The LED is attached to pin 13

/*
 The statements in the "setup()" function are executed once when the 
 program starts.
*/
void setup(){
  pinMode(led, OUTPUT);   	// Make pin 13 an output.
}
  
/* The statements in "loop()" are exectuted sequentially forever. */
void loop(){ 
  digitalWrite(led, HIGH);  // Turn the LED on by making pin 13 a high voltage.
  delay(1000);				// Delay for 1 second
  digitalWrite(led, LOW);	// Turn the LED off
  delay(1000);				// Delay for 1 second
}

Line by Line

int led = 13;

Here you are declaring the name led to mean 13, which is of type "integer", meaning it is a number (integer) thatis between -32768 and 32767. When declaring variables in your code, you have to specify the type. For now the only type you will need to know is int. Every time led appears, the Arduino will write 13. Also note that the line ends in a semi-colon. When you make assignments, you have to finish them in ";" to note that you have finished a statement because spacing does not mean anything in the Arduino language.

void setup(){ 

setup() is a specific block of code that runs at the beginning of your program. It will define certain behviours once when loaded onto the board or the reset button is pressed, and then it will not run again until the board is reloaded or reset. Every Arduino program has a setup() section. Blocks of code have to be contained in braces "{ ... }". When you declare a function you also have to give it a type for when it returns, which you won't have to worry about yet. For now, the only type you will use is void, meaning that the function does not return a value.

pinMode(led, OUTPUT);

If you look at your Arduino Uno board, you will see that it has rows of small holes that are numbered on each side. These are called "pins". The pins on the side that range from 0 - 13 are digital pins, which can be either INPUT or OUTPUT. We are going to label pin 13 (led = 13) as an output, which will light up our LED. There is built in LED on the Arduino board that is attached to pin 13, and you will also connect an external LED.

}

This is the end of the setup() function.

void loop(){

This is where we define the loop function, which repeats over and over on your device. The main behavior of your code is in the loop() function

digitalWrite(led, HIGH);

digitalWrite() can turn on or off an OUTPUT pin. The first argument (inside of the parenthesis) is the pin to be turned on or off, and the second argument can turn the pin on HIGH or LOW . This command turns the voltage on pin 13 to 5 V, which is the HIGH > voltage for an Arduino Board. Turning up the voltage is like turning on the pin.

delay(1000);

The delay() function serves to make the board sit and wait for the amount of time that you give it in milliseconds. Making the Arduino delay for 1000 millisecond will cause the light to stay on for 1 second.

digitalWrite(led, LOW);

LOW means 0 V, which will turn the led off.

delay(1000);

This is the same delay as before, but it will keep the pin off for 1 second.

 } 

This is the end of the loop() function. The loop function will keep repeating itself until you load another program onto the board.

Setting up the Circuit

After you add comments you can save your code as "Blink" and click on the right-pointing arrow to upload it onto your Arduino board. The yellow LED (labeled "L") next to pin 13 should blink because of your program. The image below shows an example of a circuit that you can add to light up an external LED. There is more than one way to set up this circuit.

Recall that each row on the center of the board has its own voltage, as well as the long columns on the sides. Connect a wire from pin 13 to a 220 Ω resistor (note: resistors have 4 color bands. If you put the gold band to the right, the color bands on a 220 Ω resistor read: red, red, brown, gold. This is shown in the diagram below). Then connect the resistor to the anode, or positive side, of the LED. Connect the negative end of the LED to "ground" (0 V) by plugging a wire into the row that of the short lead of the LED and connecting that to GND on the Arduino. Note that actual color of the wires is not important, but black is traditionally used for ground.

The figure above shows the breadboard Layout. Before continuing, take the wire shown in yellow above (you may use a different color) and remove it from pin 13 and connect to the the pin labeled 5V. The LED should go on. If it doesn't there is something wrong, and you should work to fix it. Once the circuit works, Reconnect the wire to pin 13
Schematic
Made with Fritzing

The Circuit needs a resistor before the LED to limit the current to aan appropriate value for the LED and the arduino.

Try changing the amount of time in the delay functions and re-uploading your program to see how your program responds. Also try using a 2200 Ω resistor (or 2.2 kΩ; color bands read red, red, red, gold) instead of the 220 Ω resistor. Does the circuit do what you expect?


Task 2: Pushbutton

The last task made an LED blink at a specified rate, but that's all it could do. To add some interaction with your device you will add a pushbutton that will light up the LED when you press it. The circuit that you set up for Blink program can be used for this, but you need to add the pushbutton to it.

Back to the Code

For this task you will also copy and paste the following code into the Arduino IDE and add comments after reading through a summary of what the new code does..

int led = 13;
int buttonPin = 2;
int buttonState = 0;

void setup(){
   pinMode(led, OUTPUT);
   pinMode(buttonPin, INPUT);
}
      	
void loop(){ 
   buttonState = digitalRead(buttonPin); 
   if(buttonState == HIGH){
      digitalWrite(led, HIGH);
   }
   else{
      digitalWrite(led, LOW);
   }
}

The New Stuff

Note that not every line of the code is described below

int buttonState = 0;

This line is defining a new variable, buttonState. It is an INPUT rather than an OUTPUT because it will change when the button is pressed.

pinMode(buttonPin, INPUT);

This declares the pin 2 (buttonPin = 2) to be an INPUT pin. The voltage at the input pin, here labelled D2, will change when the button is pushed. When the button is closed, D2 is connected directly to Vcc (5V) so the pin will be at a HIGH value. When the switch is open, there is no current flowing through R1, so there is no voltage across it so the voltage at D2 will be 0V (i.e., ground) or a LOW value.

Note: the 10kΩ resistor is very important. If the resistor was left out of the circuit (i.e., imagine it was just erased), then the pin D2 would not be connected to anything when the switch was open. Since D2 has no electrical connection to either Vcc or ground, its voltage is undefined and it might be read as either HIGH or LOW (or read HIGH sometimes and LOW sometimes). The resistor keeps the voltage at D2 LOW when the switch is open.

The next line shows where the input from pressing the button is initialized.

buttonState = digitalRead(buttonPin); 

Next we determine whether the button is being pressed or not by using digitalRead which is used for digital inputs. A digital value can be either HIGH or LOW (i.e. "on" or "off", "true" or "false", 0V or 5V, logic 1 or 0). If the button is being pressed, then buttonState will be HIGH. If it is not being pressed, it will be LOW. Recall that you labeled buttonState to be an int, but it is now being labeled as HIGH or LOW. This is because HIGH and LOW are thresholds for voltage amounts on a board and may differ for different boards. For example, a 5V board like the Arduino Uno recognizes a voltage greater than 3 volts as HIGH and a voltage less than 3 volts as LOW.

if  (buttonState == HIGH){
   digitalWrite(led, HIGH);
} 
else {
   digitalWrite(led, LOW);
}

We call this and "if ... then ... else ..." block. An "if" statement is exactly what it sounds like. If a certain condition is true, then the block inside of the braces will be executed. Otherwise, the program will skip that block of code. The condition has to be written inside of parenthesis after the "if". To test whether two things are equal, use the conditional operator "==". If the button is being pressed, then this statement is true and pin 13 will be turned on in the same way that you saw in Task 1.

An else statement follows an if statement to include any cases that weren't covered by the previous if statement(s). The last block tested if the button was being pressed by testing if buttonState was HIGH, so the else statement will cover the other case where the button is not being pressed. digitalWrite turns on and off the LED like you saw in Task 1.

Setting up the Circuit

The following circuit shows how to add the push button to the circuit that you made for the LED.

Connect the 5V power source to the long column with the red stripe along it (shown with the long red wire). Connect a wire from the power line to one side of the push button. The other side of the push button will have two connections coming from it:

  1. The digital line, that sends a signal to pin 2
  2. 10 kΩ resistor (color bands read brown, black, orange)attached to ground
Breadboard Circuit Made with Fritzing. Note that the switch in this diagram is physically different from the switch you will be using.
Schematic made with Fritzing

Task 3: More Functional Pushbutton

In the previous task, you lit up the LED when you were actively pushing the pushbutton. The next step is to light up the LED and have it stay on until you turn it off. Again you will comment your code after reading through the next section. You do not need to change your circuit from Task 2.

int led = 13;
int buttonPin = 2;

int val = 0;
int old_val = 0;
int state = LOW;

void setup(){ 
   pinMode(led, OUTPUT);
   pinMode(buttonPin, INPUT);
}
      	
void loop(){ 
   val = digitalRead(buttonPin); 
        
   if  ((val == 1) && (old_val == 0)){ 
      if (state == LOW) {
          state = HIGH;
      } 
      else {
          state = LOW;
      }
   } 
   
   old_val = val;
        
   if (state == LOW){
      digitalWrite(led, HIGH);
   } 
else { digitalWrite(led, LOW); } delay(10); }

More New Stuff

Before looking at each line, think about exactly what we want our program to accomplish. Like a typical "on/off" button, when pressed the LED should turn ON if it was OFF or vice versa. This means we have to know whether the LED is currently ON or OFF and when the Arduino senses that the button is being pressed, it needs to change states accordingly.

int val = 0;

val will be used to store the state of the button input

int old_val = 0;

old_val will be used to store the state of the button pin on the last round. Recall that the loop() function cycles through the code over and over again.

int state = LOW;

state is different from the last example's buttonState. State will determine whether the LED should light up or not but it is not entirely dependent on the button pin. "ON" = 1 (or HIGH) and "OFF" = 0 (or LOW).

val = digitalRead(buttonPin);

Instead of reading the input from the button pin to buttonState like in the last example, the input is read into val. This is the current input value.

 if  ((val == 1) && (old_val == 0)){

This if statement checks for two conditions with paranthesis around each one for clarity. The "&&" symble means "and". The block inside of the if statement will only be executed if both of these values are true . The purpose of this block of code is to check whether a transition has occured. If val equals 1, then the pushbutton is being pressed. If old_val is 0 then the pushbutton was not previously pressed. This means the button was just pressed.

    if (state == LOW) {
        state = HIGH;
    } 
else
{ state = LOW; }

This is a calculation to toggle the value of state. If state is LOW, it is set to HIGH, and vice versa. If this code is executing then the conditions of the previous if statement has been met, so you know that a transition has just occured (the button was just pressed).

Note also the indenting of the code; each time we get to a new opening brace, the code is indented more. You are expected to indent your code in the same way.

old_val = val;

Assign old_val to equal val for the next round

if (state == HIGH){
   digitalWrite(led, HIGH);
}
else { digitalWrite(led, LOW); }

If state is 1 then light the LED, otherwise state must be 0, so turn off the LED. The code was written this way to give you another example of the if ... then ... else construct. A better way to write this section would be:

digitalWrite(led, state);

The last statement in the loop is simply a delay.

delay(10);

This delay is added to prevent bouncing, which is when unpredictable signals are sent due to a button not being fully pressed which can cause rapid on and off signals while the loop code keeps recomputing. The delay allows the signal to come to a steady value before continuing. Switch bounce is depicted in the diagram below. The vertical axis is voltage, the horizontal axis is time.


image from http://rsrelectronics.com/t_bounc.htm

Initially the switch has a low voltage (0), but when it is pushed there can be several transitions before it remains high (1)_as the switch contacts physically bounce agains each other. The contact bounce period is very short (typically milliseconds or less), so we put in a dely of 10 mS to ensure that all the bouncinge has stopped before we continue. If we didn't delay, the computer might register more than one switch closure because of the bouncind.

Task 4: "Flip a Coin"

For this task you can use any of the previous code for help. You will have two LED's and your job is to create a "random" output that either lights one LED or the other but not both, except for when the pushbutton is being pressed. Use the following guidelines as a way to think through how to set up the program:

  1. Set up two LED's to be output pins and connect LED's and resistors to both.
  2. Set up a push button to be an input pin. Don't forget the resistor.
  3. Set up some variable, called i, that can keep track of whether LED 1 or LED 2 will stay lit after your finger is removed from the push button.
  4. If the button is being pressed, alternate quickly between i = 0 and i = 1 (or LOW and HIGH) with the LED's both off. Remember that the loop() function cycles so quickly, so the "random" outcome will come the idea that when you take your finger off the push button you will not know whether i=1 or i=0.
  5. When the button is released light up the corresponding LED depending on the value of the variable i.

You might want to talk over your ideas with somebody else in the class before you write your code so you know exactly where to put all of your if...then...else blocks

To turn in:

To complete this lab you should create a single file (preferably pdf) that has two clearly labeled sections. Whenever you include code you should make sure it is well commented and properly indented.If you go to Tools→Auto Format, the code will be properly indented for you. You can cut an paste code from the Arduino program, but you should also change the font in your final document to one in which all characters are equal width such as "Courier" or "monospace". The first example shows improper indenting with a variable width font, the second example shows peroper indenting and font. The second one is much easier to read and understand, though they are equivalent to the compiler.

int led = 13; // The LED is attached to pin 13

/* The statements in the "setup()" function are executed once when the program starts.
*/ void setup(){ pinMode(led, OUTPUT); / / Make pin 13 an output.
}

/* The statements in "loop()" are exectuted sequentially forever. */
void loop(){
digitalWrite(led, HIGH);       // Turn the LED on by making pin 13 a high voltage.
    delay(1000); // Delay for 1 second
digitalWrite(led, LOW); delay(1000); }


int led = 13;                  // The LED is attached to pin 13

/*
 The statements in the "setup()" function are executed once when the 
 program starts.
*/
void setup(){
   pinMode(led, OUTPUT);       // Make pin 13 an output.
}
  
/* The statements in "loop()" are exectuted sequentially forever. */
void loop(){    
   digitalWrite(led, HIGH);    // Turn the LED on by making pin 13 a high voltage.
   delay(1000);                // Delay for 1 second
   digitalWrite(led, LOW);     // Turn the LED off
   delay(1000);                // Delay for 1 second
}