Lab-AR-2-Jueves 24

Download as pdf or txt
Download as pdf or txt
You are on page 1of 11

Microcontroladores LAB 2 Martes 22/Nov/2016

Lab 2 Microcontrollers I
Group Name: .

Group Members: , , .

Grade (max = 10, no pre-lab): .

Lab report is due one week from the completion of the lab.
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
Reading: Practical Electronics for Inventors Chapter 13.

Objective: Introduction to microcontrollers, setting the Arduino IDE, simulations with


123d.circuits.io, programming structures, reading and writing digital and analog signals.

NOTE:
Lab work to be done is in almost all Sections
Remember to read ALL SECTIONS!

a) Arduino pinouts.

Recall what we learned last class: the Arduino is a one-chip microcomputer capable of
performing numerous internal operations (which can be programmed in assembler or C
language), but also that can read or write data to each of the input/output pins (see
Figs. 1 and 2). This capability to directly manipulate these lines allows for interesting in-
teraction with the physical world, and this is much easier than in a regular computer where
there are numerous layers between the programming and the actual computer ports.

Fig. 1. Arduino nano. See Fig. 2 for a description of each pins function.

2016 Carlos Wexler Page 1 of 11


Microcontroladores LAB 2 Martes 22/Nov/2016

Fig. 2. Arduino nano pinout digram. Notice that each pin, typically, has multiple functions.
The actual port names and bits (e.g., PD1) are useful to do fast in/out operations.

2016 Carlos Wexler Page 2 of 11


Microcontroladores LAB 2 Martes 22/Nov/2016

b) Setting up the Arduino IDE (integrated development environment).

To install the Arduino software (and perhaps device drivers), please follow the instructions
here to download and configure the software (follow the instructions for your operating
system):

http://arduino.cc/en/Guide/HomePage

c) Arduino Simulator.

Yes! There is a FREE online Arduino simulator (which also includes a lot of neat additional
components such as transistors, LEDs, 7 segment displays, Servo Motors, OpAmps, logical
gates, even a simulated oscilloscope!). This awesome simulator can be found here:

http://123d.circuits.io/

You will need to create a FREE Autodesk account to create or edit circuits.

Within the simulator, you are able to add various types of Arduinos, and other things. You
may also edit the programming of the Arduinos and make them run! It works very well but
obviously cant do things as fast as the real hardware (i.e., things that blink once per second
work well, things that need to switch at MHz frequencies will not work).

The first code example we will analyze is a sketch that blinks an LED (most Arduinos come
with this code already programmed from the factory, but possibly yours will be already
erased). We will analyze this code in the next section, but if you want to check it out first,
open the following URL (you do not need an account for this):

http://123d.circuits.io/circuits/632232-blink/embed#breadboard

Fig. 3. A blink sketch. I captured the screenshot just as the LEDs were on! You can also
access the program code (Code Editor) and change it (you may need an account for this).

2016 Carlos Wexler Page 3 of 11


Microcontroladores LAB 2 Martes 22/Nov/2016

d) Programming structure.

All programs in the Arduino IDE (integrated development interface) must contain this
bare minimum (the sketch below does not do anything really). The structure inside
setup() runs only once (at the start of the program), whereas the loop runs continuously
and non-stop afterwards.

Listing 1. BareMinimum.ino. Obviously this program does nothing


void setup() {
// put your setup code here, to run once:
}

void loop() {
// put your main code here, to run repeatedly:
}

More interesting programs can be built-up from there. For example, Listing 2 makes the
internal LED (wired internally to Pin 13 in most arduino boards) blink once every two sec-
onds (a similar code can be found in the 123d.circuits simulation listed above).

Listing 2. Blink.ino (this can be loaded from FILEEXAMPLES01.BASICS)


/*
Blink
Turns on an LED on for one second, then off for one second, repeatedly.
This example code is in the public domain.
*/

// Pin 13 has an LED connected on most Arduino boards.


// Pin 11 has the LED on Teensy 2.0
// Pin 6 has the LED on Teensy++ 2.0
// Pin 13 has the LED on Teensy 3.0
// give it a name:
int led = 13;

// the setup routine runs once when you press reset:


void setup() {
// initialize the digital pin as an output.
pinMode(led, OUTPUT);
}

// the loop routine runs over and over again forever:


void loop() {
digitalWrite(led, HIGH); // turn the LED on (HIGH is the voltage level)
delay(1000); // wait for a second
digitalWrite(led, LOW); // turn the LED off by making the voltage LOW
delay(1000); // wait for a second
}

2016 Carlos Wexler Page 4 of 11


Microcontroladores LAB 2 Martes 22/Nov/2016

It is worth noticing that:

1) All lines of code end with a semicolon ;


2) Anything after // is a comment.
3) Anything between /* and */ is a comment.
4) All named variables and constants must be declared. If a variable is declared outside
a subroutine (e.g., led is declared that way) then its scope is global. If led had been
declared inside, e.g., setup(), then its scope would be local and it would be unknown
to loop().
5) The variable led has been declared as an int (this is a two-byte signed integer, range
is 32768 to 32761, see http://arduino.cc/en/Reference/Int).
6) It is always advisable to use names rather than simply 13 when doing operations.
For example, if one wanted to run this sketch on a Teensy 2.0, writing int led = 11 is
all that is needed (rather than having to change it in all places where led appears.
7) Since led is not supposed to change in this program, I would recommend to declare
it a constant: const int led = 13; this makes sure it cannot be changed by accident!
8) The function delay(1000) makes for a delay of 1000 ms. I personally would have
used a variable name for it (i.e., int tdelay = 1000; delay(tdelay); etc.).

Task 1: put an arduino on a breadboard and attach a 220-330 resistor to Pin 9. Then
attach the long leg of an LED (the positive leg, called the anode) to the resistor. Attach the
short leg (the negative leg, called the cathode) to ground. Then plug your Arduino board
into your computer, start the Arduino program, open the Example Blink and modify it to
work with this pin. Also change the blinking frequency at will. Recommendation: create a
variable tdelay and give it a number so you can change it at will in one single spot. Show
your work to the instructor. Save your code and attach to the report.

Change tdelay to 5 ms and observe the voltage at Pin 9 with the oscilloscope.

What is the frequency?

Answer: ______________ Hz.

Is this what you expect?

You have just made a simple oscillator that is quite precise (because the timing is based on
a crystal oscillator) and easy to tune! Capture the screen, print and attach to the report.

2016 Carlos Wexler Page 5 of 11


Microcontroladores LAB 2 Martes 22/Nov/2016

e) Analog read and write, serial I/O.

Task 2: Lets make it more interesting now. Connect a 10k trimpot/potentiometer be-
tween +5V and ground, and the center connector to the Pin A0. We will use the
analogRead(A0) function to convert the voltage (between 0 and +5V) to a 10 bit integer
(0V 0, 5V 1023). We will then convert the integer to a voltage and output the results
to the computer via the serial line (you will need to open the ToolsSerial Monitor, or
the corresponding button to see this). Open the Example ReadAnalogVoltage, as shown
in Listing 3.

Listing 3. ReadAnalogVoltage.ino (this listing is available for you to load)

/*
ReadAnalogVoltage
Reads an analog input on pin 0, converts it to voltage, and prints the result to the serial monitor.
Attach the center pin of a potentiometer to pin A0, and the outside pins to +5V and ground.

This example code is in the public domain.


*/

// the setup routine runs once when you press reset:


void setup() {
// initialize serial communication at 9600 bits per second:
Serial.begin(9600);
}

// the loop routine runs over and over again forever:


void loop() {
// read the input on analog pin 0:
int sensorValue = analogRead(A0);
// Convert the analog reading (which goes from 0 - 1023) to a voltage (0 - 5V):
float voltage = sensorValue * (5.0 / 1023.0);
// print out the value you read:
Serial.println(voltage);
}

Note in the setup() the initialization of the serial device via Serial.begin(9600). The 9600
is the baud rate (roughly speaking bits per second). For communicating with the com-
puter, use one of these rates: 300, 600, 1200, 2400, 4800, 9600, 14400, 19200, 28800,
38400, 57600, or 115200. You can, however, specify other ratesfor example, to com-
municate over pins 0 and 1 with a component that requires a particular baud rate. The
value of 9600 is a pretty standard one and reasonably fast so it is commonly used. If you
need faster communication use 115200 (I personally like that one since I am quite impa-
tient). You can write to the computer with Serial.print() and Serial.println(); the latter
ads a new line to the output. Note that some variables were declared locally within
loop(). Vary the input (rotate the trimpot) and see what happens. Show your working sys-
tem to the instructor.

2016 Carlos Wexler Page 6 of 11


Microcontroladores LAB 2 Martes 22/Nov/2016

Task 3: now combine your work of the previous two tasks (Listing 2 and Listing 3) to
vary the blinking rate of the LED by means of the potentiometer. Show your work to the
instructor and attach your program list to the report.

Task 4: instead of making your LED blink, vary its intensity using the PWM (pulse width
modulation) functionality that Pin 9 has (this is why we wired the LED to Pin 9!). The func-
tion analogWrite(pin, value), where value is an integer between 0 and 255 (8-bit), is
what one should use. The example program Fade gives you some ideas (Listing 4). Load it,
modify as needed and show your work to the instructor.

Listing 4. Fade.ino (this listing is available for you to load)

/*
Fade

This example shows how to fade an LED on pin 9


using the analogWrite() function.

This example code is in the public domain.


*/

int led = 9; // the pin that the LED is attached to


int brightness = 0; // how bright the LED is
int fadeAmount = 5; // how many points to fade the LED by

// the setup routine runs once when you press reset:


void setup() {
// declare pin 9 to be an output:
pinMode(led, OUTPUT);
}

// the loop routine runs over and over again forever:


void loop() {
// set the brightness of pin 9:
analogWrite(led, brightness);

// change the brightness for next time through the loop:


brightness = brightness + fadeAmount;

// reverse the direction of the fading at the ends of the fade:


if (brightness == 0 || brightness == 255) {
fadeAmount = -fadeAmount ;
}
// wait for 30 milliseconds to see the dimming effect
delay(30);
}

2016 Carlos Wexler Page 7 of 11


Microcontroladores LAB 2 Martes 22/Nov/2016

Observe the output of Pin 9 with an oscilloscope to see how the fading works (you may
need to change the delay so that it does not change so fast.

Task 5: Modify the code to fix the brightness of the LED at each of 0, 64, 128, 192 and
255, observe the output of Pin 9, capture print and attach to report.

Task 6: Write a program that varies the intensity of the LED depending on the value read
in the potentiometer. Remember that analog.Read() gives a number between 0 and 1023
so you will need to divide by 4 to use the full range of the potentiometer. Show your work
to the instructor and attach the program to the report.

Task 7: We will now change the colors of an RGB LED by means of a command given from
the computer! Open the example ReadASCIIString, see Listing 5 and Figs. 4 & 5. Do not
worry too much if you do not understand all the details on how the serial communication
works (I dont, I play with it until it works!), just figure out what the basic structure means
and how to borrow things if you need to modify the code for your own use.

Fig. 4 RGB pinout (common cathode)

Listing 5. ReadASCIIString.ino.
(can be loaded from FILEEXAMPLES04.COMMUNICATION)
/*
Reading a serial ASCII-encoded string.

This sketch demonstrates the Serial parseInt() function.


It looks for an ASCII string of comma-separated values.
It parses them into ints, and uses those to fade an RGB LED.

Circuit: Common-cathode RGB LED wired like so:


* Red anode: digital pin 3 (via 220 resistor)
* Green anode: digital pin 5 (via 220 resistor)

2016 Carlos Wexler Page 8 of 11


Microcontroladores LAB 2 Martes 22/Nov/2016

* Blue anode: digital pin 6 (via 220 resistor)


* cathode: GND

created 13 Apr 2012


by Tom Igoe

This example code is in the public domain.


*/

// pins for the LEDs:


const int redPin = 3;
const int greenPin = 5;
const int bluePin = 6;

void setup() {
// initialize serial:
Serial.begin(9600);
// make the pins outputs:
pinMode(redPin, OUTPUT);
pinMode(greenPin, OUTPUT);
pinMode(bluePin, OUTPUT);

void loop() {
// if there's any serial available, read it:
while (Serial.available() > 0) {

// look for the next valid integer in the incoming serial stream:
int red = Serial.parseInt();
// do it again:
int green = Serial.parseInt();
// do it again:
int blue = Serial.parseInt();

// look for the newline. That's the end of your


// sentence:
if (Serial.read() == '\n') {
// constrain the values to 0 - 255 and invert
// if you're using a common-cathode LED, just use "constrain(color, 0, 255);"
red = constrain(red, 0, 255);
green = constrain(green, 0, 255);
blue = constrain(blue, 0, 255);

// fade the red, green, and blue legs of the LED:


analogWrite(redPin, red);
analogWrite(greenPin, green);
analogWrite(bluePin, blue);

// print the three numbers in one string as hexadecimal:

2016 Carlos Wexler Page 9 of 11


Microcontroladores LAB 2 Martes 22/Nov/2016

Serial.print(red, HEX);
Serial.print(green, HEX);
Serial.println(blue, HEX);
}
}
}

Please ask the instructor for help as needed and show your working system to the instruc-
tor.

Fig. 5 RGB connections.

f) More fun with Arduino.

Task 8: Now lets have some fun. Do you remember Knight Rider with David Hasselhoff?
His ride was a souped-up Pontiac Trans Am with very cool red lights in the front of the
car in a sequence 1-2-3-4-5-6-7-8-7-6-5-4-3-2-1 (rinse and repeat!). Your mission is to
create the same effect using an Arduino, 8 LEDs (and obviously 8 resistors!). Please get
your hardware set-up and start your program. Ask for help from your instructor as need-
ed.

You may find useful to understand the following commands/sequences/structures:

for (int i = 2; i<=9 ; i++)


{
pinMode(i, OUTPUT);
} // end of for loop

2016 Carlos Wexler Page 10 of 11


Microcontroladores LAB 2 Martes 22/Nov/2016

It loops the variable i between 2 and 9 (i++ means increment it by 1). Think how you can
wire your LEDs and set-up a sequence of events turning the LEDs on and off in the Knight
Rider way (i.e., not writing 8 or 16 independent pieces)! Note: you may need to put some
delay(tdel) instructions in various strategic points. Making the Knight Rider sequence at
kHz or MHz frequencies is not visually appealing. Suggestion: use the potentiometer input
analog.Read(A0) to set the time delay tdel, so you can change it on the fly (or you may
need to re-program tdel it each time, or read from the serial port, it is up to YOU).

Ask your instructors for assistance as needed!

Write the code and include a printout with your report. It would be useful if you also in-
cluded either a nice PHOTO (make sure it is in focus and connections are clear) and/or a
circuit diagram (you may use paper/pencil or 123d.circuits).

NOTE: given the accelerated nature of THIS COURSE, you may ask your instructor for
the code.

Fig. 6. A Knight Rider implementation using Arduino Uno. We will use the nicer bread-
boardable Nano (I simply dont want to make it too easy for you!).
Do not disassemble this circuit! You will use it again in the next lab.

2016 Carlos Wexler Page 11 of 11

You might also like