2017 - Lab 2 Microcontroller and Basic I - 1
2017 - Lab 2 Microcontroller and Basic I - 1
MICROCONTROLLERS
BASIC INPUTS and OUTPUTS (I/O)
ABSTRACT
A microcontroller is an integrated circuit containing a processor and programmable
read-only memory, 1 which is widely used as an interface between hardware and
software systems. We will use the Arduino microcontroller. “Arduino is a tool for making
computers that can sense and control more of the physical world than your desktop
computer. It’s an open-source physical computing platform based on a simple
microcontroller board, and a development environment for writing software for the
board.” 2 This laboratory session pursues obtaining familiarity with the Arduino
microcontroller operation, namely installation of communication with your computer,
downloading the proper software and programming code, and gaining familiarity with
the Arduino boards to implement basic I/O tasks.
1. INTRODUCTION
About the board.
Microcontrollers are small computers designed to do real time controls. A microcontroller
is essentially a small programmable computer contained on a single integrated circuit,
consisting of a processor, read-only memory (ROM) used to store the program instructions,
and a set of input and output pins which can be used to interact with an external circuit.
The microcontroller IC is a digital device and, since the processor operates on “transistor to
transistor” logic (TTL), only two logic states are acceptable: HIGH (~ +5 V) and LOW (~0 V). The
microcontrollers come in all shapes, sizes, and layouts. Usually, they are quite small and use
less power than traditional computers. Microcontrollers are often deployed in ‘appliances’
and serve an unmodifiable dedicated purpose, such as keeping track of what spin cycle your
washing machine is on, or how much time is left before it should turn off your microwave
oven. Make no mistake, however, these are general purpose computers.
A major difference between a microcontroller and traditional computers is that they
come with an array of analog and digital inputs and outputs. These inputs and outputs
can be used to read environmental data from sensors, talk to other computers or devices
and electronically control other systems which provide environmental outputs such as a
LCD screens, mechanical switches or servo motors etc.
Getting started with microcontrollers can be a tedious process, as they can require a
number of supporting circuits, USB controllers, programmers, boot-loaders and power
supplies just to load your first program onto the microcontroller chip. Often times you will
start with a prototyping board which puts all of the necessary components in a
convenient and ready to use package.
Arduino Microcontroller and its advantages
This lab will be using the single board Arduino Leonardo Microcontroller.3 It is similar to
the Arduino Uno,4 with the major difference being that the latter uses Surface Mount
Technology (SMT)5 instead of the older “thru-hole” 6 technology. The Arduino drastically
lowers the difficulty of getting started with a microcontroller (compared to to plain
ATMEGA/PIC/ARM chips), as it provides all the necessary tools for making the
microcontroller do interesting things, which would be daunting if staring with just a plain
microcontroller chip.
The Arduino is based around an 8-bit Atmel AVR microcontroller, and has supporting
systems like a boot loader for uploading programs, a USB controller, as well as a barrel jack
for external power.
It is programmed using a language that is based off of C++.
It uses an integrated development environment (IDE) for writing, compiling and uploading
your programs to the board.
C.1 Windows
Select Toolbar → Tools → Serial Port → COM5
where COM5 is the serial port that has been assigned to your Arduino by windows.
(The computer may have assigned another port number to your Arduino, like COM4,
for example; check it out).
You may have more than one port in the list. To know which port is associated with
the Arduino, you can check the list with the Arduino unplugged, and check it again
with it plugged in. The extra port that appears in the list is the Arduino’s port.
C.2 OS X
Usually the Arduino is the first item in the Serial Port list. Another way to tell is that
it has tty in the name and does not have the world ‘bluetooth’ in it.
NOTE: Sometimes, even if the port selection has been set through the Arduino program
(as described above), the actual selection may not happens. It may be necessary
then to specify the serial port though the following sequence:
Left-click the “Start” button; right click on “Computer”, select “Properties” >> Left-
click on “Device Manager” >> “Ports”
Figure 3. Left: The “Verify” and “ Compile” buttons. Right: Successful-compile message.
A.2 Once the compiling process is completed, go ahead and upload the program to the
micro-controller board by pressing the upload button (located right next to the verify
button).
This process should provide a similar completion message after a few seconds. The
LEDs on the Arduino will blink during the upload, but should settle down after a few
seconds. Your program is now on the Arduino and running in a loop sequence.
Once the program you uploaded is running, the tiny LED labeled ‘L’ on your Arduino
should be slowly blinking in response to the uploaded “Blink” program. The LED labeled
‘L’ is wired to Pin 13 on the Arduino; this is a digital pin with a resistor built in so that an
LED can be connected directly between that pin and ground.
Go ahead and connect an LED between Pin 13 and GND. It should blink at the same
rate as the ‘L’ LED on the board.
Congratulations! You now have a working Arduino that is talking to the Arduino IDE.
B. Actual code
Arduino is based off Processing,8,9 an open source programming language that has some
similarities to C. However much of the language has been simplified from C. In this
section we will go over the basics of the language, look at some simple examples of
code, and even write some of our own.
The bare minimum code you need for an Arduino program is presented in Figure 4.
1 void setup() {
2 // put your setup code here, to run once:
3 }
4 void loop() {
5 // put your main code here, to run repeatedly:
6 }
______________________________________________________________________
Fig. 4 The minimum amount of code for an Arduino Program.
C.1 Comments
If a block of text is wrapped inside the symbols,
/* */
(such as lines 1 thru 6 in Figure 5),
or if a command line has the symbol,
//
in front of it (such as line 12), it means that the content is a comment.
Comments are little notes you leave in your code. They are not executed or interpreted by
your program in any way. It is good practice to add comments to your code. They can help
you think about your program, and will also remind you, and others that see your code,
what the program does or how it works.
Running down lines 1-9, we see a block of comments describing the function of the
program, how it works, as well as the license. The first piece of code we see is on line 10.
C.2 Variables
int led = 13;
First, notice that this code is not inside the void setup() nor the void loop(). That is because
it is a variable and variables have to be declared at the beginning of our program, outside
either loop.
Variables are incredibly useful tools. Variables store information that can be used later in
the program as many times as you need. They can be updated during run-time and can be
used to store values temporarily for repeated use.
Any variable we decide to use has to be declared at the beginning of the program. That is,
variables are declared before your void setup() or void loop() sections.
Line 10 declares a variable named led; it also declares it as an integer variable int; and then
assigns the 13 to that variable. This variable is used to reference the physical pin that we
will be using in our program. It is used as an abstraction layer, so that if we ever go back
and change which pin we want to use, we can update all the places in our program that
reference this pin number simply by updating the initial variable value.
The basic syntax of a variable declaration is:
Type variable_name = value;
The available variable types can be found on the Arduino website. 10 Please reference that
list if you want to use values other than integers.
4 void setup() {
5 pinMode(led, OUTPUT);
6 }
7
8 void loop() {
9 digitalWrite(led, HIGH);
10 delay(wait); //Wait for the amount declared in the wait variable
11 digitalWrite(led, LOW);
12 delay(wait); //Wait for the amount declared in the wait variable
13 }
_________________________________________________________________________________________
Figure 6: The modified Blink Program.
5. USING INPUTS to CONTROL OUTPUTS
5.1 Understanding Pulse Width Modulation (PWM)
Arduino cannot output true analog signals. One way to output a digital signal that reflects
the value of an analog signal is pulse-width-modulation (PWM) Compared to a square signal,
where the duty cycle is 50% (i. e. half of the period HIGH and half of the period LOW), the PWM
signal has a duty cycle in which the time during which the signal remains HIGH is proportional
to the analog signal.
For example, when driving an LED with a PWM signal one is able to vary the brightness of
the LED by writing on the PWM-pin a proper (digital) value:
An analog signal should be first read by the Arduino (which converts it to a value
between 0 and 1023).
That value has then to be converted into an 8 bit (0 to 255 range) number.
The latter is used to write the PWM pin.
The net result is the generation of a digital signals (switching on and off) that makes the
photodiode emit power proportional to the duty cycle.
From the Arduino library Load the 01.Basic → Fade example program and upload it to
your Arduino board .
Toolbar → File → Examples → 01. Basics → 0.1.Basic
(a modified version of the program is shown in Fig. 8 below). Wire up the LED to the pin that is
used in the program; if it is a digital pin other than pin 13, you will need to add a 330 Ω resistor
in series with the LED. If you increase the delay time to 80, you should be able to observe the
PWM flicker at lower brightness levels. You can leave the LED in place. Observe how the signal
looks like on your oscilloscope.
5V
D10
10 k PWM
D9
LED
D8
A0
A1 PWM 330
Analog
input
GND
Figure 7 Potentiometer and LED wired up to the Arduino. Pin 9 is a PWM output.
1 const int led = 9; // the PWM pin where the LED is attached to
2 const int pot = A0; // A0 will be the analog input channel
3 int sensorValue = 0; // sensorValue will store the value read from the pot
4 int outputValue = 0; // outputvalue will be the (duty cycle) value to be
5 // sent to the PWM pin
6 void setup() {
7 pinMode(led, OUTPUT); // Declare the PWM pin 9 to be an output
8 Serial.begin(9600); // Open a serial monitor at 9600 baud
9 }
10 void loop() {
11 sensorValue = analogRead(pot); // store pot value in sensorValue
12 outputValue = map(sensorValue, 0, 1023, 0, 255); // map sensorValue to
a 8 bit number (0 to 255)
13 analogWrite(led, outputValue); // write the analog out value to pin led
14 // outputValue specifies the “duty cycle”
15 Serial.print("sensor = " ); // print the results to the serial monitor
16 Serial.print(sensorValue);
17 Serial.print("\t output = ");
18 Serial.println(outputValue);
19
A0
GND 5V
D9
PWM
LED
330
Figure 11. Symbols that may be helpful when designing your circuits. (To modify
them, just copy and paste them into the “PAINT” application.
A. Implementation of Outputs and Inputs (when the applications are not very critical)
A1. Digital Output. (It typically constitutes a “Control” signal)
a) Let’s control the state of an LED.
We can capitalize on the Blink program, which does just that. Hence, run the Blink
program following the procedure stated above on how to hook the LED.
b) Just for testing purposes, other than digital pin 13 try, one at a time, digital pin 2, ….,
to digital 12.
A2. Digital Input. (Typically they are signals coming from a sensor; hence they are referred
as “Measurement” signals).
In non-critical application people just use a floating terminal (a hanging wire) to
connect the input pin directly to i) 5V, ii) leave it floating, or iii) GND. (Three state
inputs available).
Define the digital pin 7 to be the input, and the digital pin 4 to be the output.
Make 2 new programs:
In the first, if the input is high (Positive logic), make the LED to light up.
In the second, if the input is low (Negative logic), make the LED to light up.
Connect digital 7 to i) 5V, then ii) leave it floating, and then iii) GND. Check if the output
behaves as expected.
Figure 12.
Blow we suggest the positive logic program (where 5V implies HIGH). You have to make
the negative logic program (where GND implies HIGH).
void setup() {
// put your setup code here, to run once:
pinMode(7,INPUT);
pinMode(4,OUTPUT);
}
void loop() {
// put your main code here, to run repeatedly:
if (digitalRead(7)==HIGH) digitalWrite(4,HIGH);
else digitalWrite(4,LOW);
// modify here! for your own measurement .
delay(2);
}
Figure 13. Positive logic program.
Watch carefully what happens with the LED. Compared this procedure with the one
used in the next section.
Note: We consider the above to be “not recommended procedures” (although 99% of
practitioners do it!)
B. Recommended procedure to establish a digital input (for more critical applications)
(In the circuits of Figs. 14 and 15 only the inputs setups are good, not the outputs)
B.1 Positive input logic connection
(“Input is HIGH effective”)
Connect the circuit shown in Fig. 14. Use the positive logic program given in Fig. 13.
Sequentially connect digital 7 to: 5V, float, GND.
Compare the different results.
It turns out, negative logic implementation has advantages over positive logic, as we
illustrate below.
void setup() {
// put your setup code here, to run once:
pinMode(7,INPUT);
pinMode(4,OUTPUT);
}
void loop() {
// put your main code here, to run repeatedly:
if (digitalRead(7)==LOW) digitalWrite(4,HIGH);
else digitalWrite(4,LOW);
// modify here! for your own measure.
delay(2);
}
Figure 16 Negative logic program.
Figure 16.
void loop() {
int j;
j=analogRead(A5);
float k;
k=(float)j*5/1023;
Serial.println(k);
// modify here! for your own measure.
delay(1000);
}
Figure 17.
E. Build a counter to measure a sensor signal
E.1 Build the circuit shown in Fig. 18, and upload the program shown in Fig. 19.
Cover the photo resistor with your hands, or shine the photo resistor with your cellphone
flash. Check the readings from your monitor.
If the counter does not work, you may need to adjust a parameter value inside the program
(see comment inside the program). What is physically going on when you change that
parameter? What is the reason that a proper value of that parameter makes the counter to
work?
Figure 18.
E.2 After you find the threshold of your measurement from section E.1, use the counter to
measure how many times you swing your hand over the sensor. (This program contains
software implementation of latch, flip-flop and counters, which are sequential logic. The
details of sequential logics will be covered after the combinational logic labs. )
// This program demonstrate a digital flip-flop
// and a digital counter!
void setup() {
pinMode(A0,INPUT);
Serial.begin(9600);
}
int s=0;
void loop() {
int j;
j=analogRead(A5);
if (j<349) // change this number according to your
measurement.
{delay(3);
if (analogRead(A5)>350)
Serial.println(++s);
}
}
Figure 19.
1
A ROM associates a specific output binary number with each input binary number according to its
fixed internal logic. The fixed relationship between input and output distinguishes the ROM from
other memory circuits.
2
Arduino.cc. Introduction. http://arduino.cc/en/Guide/Introduction, 2013.
3
Arduino.cc. Arduino leonardo. http://arduino.cc/en/Main/ArduinoBoardLeonardo, 2013.
4
Arduino.cc. Arduino uno. http://arduino.cc/en/Main/ArduinoBoardUno, 2013.
5
Wikipedia. Surface-mount technology. http://en.wikipedia.org/wiki/Surface-mount_technology,
2013.
6
Wikipedia. Through-hole technology. http://en.wikipedia.org/wiki/Through-hole_technology, 2013.
7
https://www.arduino.cc/en/Main/Software
8
Processing programming language. http://processing.org/, 2013.
9
http://hello.processing.org/editor/
10
Arduino.cc. Reference page. http://arduino.cc/en/Reference/HomePage, 2013.
11
Arduino.cc. Pinmode(). http://arduino.cc/en/Reference/PinMode, 2013.
12
Arduino.cc. map(). http://arduino.cc/en/Reference/Map, 2013.