Sie sind auf Seite 1von 12

BME 201: Arduino Lab 2

Section 2.3: Serial Communication

Purpose:
While using a microcontroller, it is often necessary for the microcontroller to
communicate with a computer or other device. There are many different forms of inter-
device communication; however, we will only focus on one during this course: UART.
UART stands for Universal Asynchronous Receiver/Transmitter. UART is commonly
used to communicate with a computer using a simple USB connection.

Terms:
UART (Universal Asynchronous Receiver/Transmitter): Form of device-device
communication. Supports sending and receiving from both devices involved.

Serial Communication: Data is sent one bit at a time (e.g. 100110001)

Baud Rate: Number of bits sent or received per second. This value needs to be
the same for the receiver and the transmitter or else they will not be able to
understand each other.

Serial Monitor (Terminal Window): Window used to view serial communications


from the microcontroller as well as send commands to the microcontroller.

Materials:
Arduino Board
USB A-B cable

Procedure:
Setting up Serial communication on Arduino is extremely simple. Listing 2.3 A
demonstrates the classic beginner program known as Hello World with a few small
changes made to illustrate a few points.
Listing 2.3 A
////////////////////////////////////////////////////////////////////////////////
// Basic Serial
// Author: R Scott Carson
// BME 201
// Spring 2014
////////////////////////////////////////////////////////////////////////////////

void setup(){
// Set up serial to transmit at 9600 bits/sec
Serial.begin(9600);
}

void loop(){
// Print "Hello" using print()
Serial.print("Hello\n");
// Print "World" using println()
Serial.println("World");
// Wait for 1 second
delay(1000);
}
Listing 2.3 A

The following section traverses through the code in Listing 2.3A step-by-step so to
illustrate how it works.
First we initialized Serial communication in the setup() function.
We wanted to initialize the Serial interface to transmit and receive with a
baud rate of 9600 bits/sec. We did this using the Serial.begin() function.
Serial.begin() - Sets the baud rate to the number passed in as an
argument.
Second we wrote data out over Serial in the loop() function.
To write the data, we are going to use the print() and println() functions.
print() - prints the arguments over Serial.
println() - prints the arguments and then creates a new line.
Theres a tiny difference between print() and println(). The special \n
character in the argument to the print() function (following the word Hello
above). This special character simply tells the device on the receiving end
of the message to create a new line. This is the equivalent of pressing
return on a keyboard. In the println() function, the ln stands for line.
This function automatically adds the new-line character at the end of the
message.

The next step is to compile and upload the code. If you experience difficulties
with this do not be afraid to ask for help.

Now that we are transmitting data to the computer, how do we see it? As seen
before, the Arduino IDE comes with a built in serial monitor that we can use to see the
incoming data.

Figure 2.3.1

Pressing the button circled in Figure 2.3.1 will open up another window known as
the Serial Monitor. Check with an SA at this point before continuing.

We can also print a variable out over serial. This is useful for many reasons, such
as debugging code at a specific point in the program, viewing a functions output, or
viewing readings from a sensor. This exercise will demonstrate how simple it is to print
out a variables value, a task that will be used in your final design project.

Listing 2.3 B
//////////////////////////////////////////////////////////////////////
// Variables Over Serial
// Author: R Scott Carson
// BME 201
// Spring 2014
//////////////////////////////////////////////////////////////////////

// Declare and initialize an integer, a float, and a char variable


int i = 5;
float f = 3.3;
char c = 'B';

void setup() {
// Set up serial to transmit at 9600 bits/sec
Serial.begin(9600);
}

void loop() {
Serial.println(i); // Print the integer variable
Serial.println(f); // Print the float variable
Serial.println(c); // Print the char variable
Serial.println("****"); // Print a separation
delay(1000);
}
Listing 2.3 B

The code in Listing 2.3A is very similar to the code in Listing 2.3B. The difference
is that we directly print the variable instead of printing a static number or character. This
allows us to print a value out without knowing exactly what it is beforehand.

Exercise:
Using the information presented in this section and previous sections, write a
program that takes an integer variable named x and prints it out in a loop, incrementing
the value each time. When the value is greater than 9 you should set it back to 0. There
should also be a one second (1000 ms) delay between each print statement. The output
should look like the following:

0
1
2
3
4
5
6
7
8
9
0
1
2
.
.
.

HINT: Increment the variable x each time through the loop function, and check if it is
greater than 9 using an if statement. Feel free to ask questions!

Check with an SA when you have completed the exercise.


Section 2.4: Analog Input

Background
Analog Vs. Digital
An analog signal is continuous in amplitude and time; that is, it can take on any
value at any point in time, as shown on the curve in the left portion of Figure 2.4.1. A
digital signal, on the other hand, is discrete in both amplitude and time, and it can have
only a finite range of values it can take on, as shown on the right in Figure 2.4.1.

Figure 2.4.1: An analog signal on left is continuous in both time and amplitude, and a
digital signal on right has discrete values for both time and amplitude.

Analog to Digital Conversion


A computer is only able to work with discrete (digital) signals. However, almost all
physical, real-world values are actually continuous (analog) signals. For example, when
a microphone records a sound, the sound is a continuous or analog signal. As the
sound propagates through air it manifests in changes to air pressure, these changes are
converted to the movements of a diaphragm within the microphone. Various methods
are then used to turn the vibrations into electrical signals (variant currents or voltages).
However, before a computer can read this signal, the signal must be formatted so that it
is a quantized, discrete valued function (readable by a computer). This process is done
by an analog to digital converter (ADC).
The ADCs used in this lab require a voltage range in which an analog value will
be found. This range is known as the voltage references of the ADC and is dependent
of the type of microcontroller (information found in a data sheet). In the case of Arduino
the minimum voltage that can be converted is 0 V. This is referred to as V REF-, thus in
the case of Arduino VREF- = 0 V. Similarly, the maximum value that can be converted is
VREF+ which is 5 V for Arduino (VREF+ = 5 V).
As mentioned before a microcontroller (and any computer) operates using a
binary number system. This means that when an ADC digitizes a signal (voltage value
within the voltage reference range) it must be represented on the same binary system.
An analog value is represented in its digital format by dividing the voltage reference
range by number of possible values the ADC can resolve. The number of values is
determined by the bit size of the ADC. An ADC can resolve 2 n different values where n
is the bit size of the ADC.
The Arduino is has a 10-bit ADC and a voltage reference from VREF- = 0 V to
VREF+ = 5 V. Thus the ADC can represent 210 values or 1024 values. By mapping the
values 0 to 1023 from 0 to 5 V, the Arduino ADC has a resolution of 5 V / 1024 units or
0.0049 V per division. Formally the resolution of an ADC can be represented with the
following equation:

The higher the bit size of the ADC, the better the resolution becomes and the
more accurate the digitized reading becomes. However, an ADC with a higher bit size is
also more susceptible to noise, more expensive and slower. The bit size of an ADC is
an important consideration when choosing a microcontroller and all aspects of the ADC
must be taken into account in order to pick the best choice for a given application.
When digitizing a signal, the time at which samples are taken as well as the
amplitude are converted to discrete values. This means that it is important to consider at
what speed samples will be taken. For example, in figure 2.4.1 above, a sine wave can
be sampled at discrete time points to yield the image on the right. However, if the
sampling rate were to decrease to 0.25 seconds, there would only be five samples
taken. In this case, only the five samples at 0, 0.25, 0.5, 0.75 and 1 seconds would be
taken. There are a multitude of different signals that could match this down sampled
version of the signal and a computer would have no way to distinguish which to use.
This concept is illustrated in figure 2.4.2 below.

Figure 2.4.2: An analog signal sampled adequately is shown above. The down sampled
(less frequent sampling) is shown below with a secondary wave (not the original signal)
that could also be extrapolated form the results.
As shown above, if a signal is not sampled fast enough, it can be aliased (look
like another signal). To avoid this, the Shannon-Nyquist sampling theorem is used. The
Shannon-Nyquist sampling theorem states that in order reconstruct a signal from
samples taken, the sampling rate must be two times that of the highest frequency
component in the signal. For example, say a sine way with frequency 40 Hz is being
sampled. This 40 Hz wave must be sampled at a rate of at least 80 Hz (40 Hz * 2 = 80
Hz). Often times a sampling rate of about five times the highest frequency component of
a signal is used.

Purpose:
A microcontroller must convert the analog signals measured from the
environment in to usable digital data via the use of and ADC. This section will focus on
utilizing the Arduinos ADC to read in data from the environment and illustrate the
benefits and shortfalls of this particular hardware.

Terms:
ADC (Analog to Digital Converter): A device that converts continues signals into
discrete signals.
ADC Resolution: The level to which the ADC can distinguish one analog input
from another. The resolution is a function of the number of parts the maximum
signal value can be divided. Usually measured in volts.
Voltage Reference Range: The range in which the ADC can convert.

Materials:
Arduino Board
USB A-B cable
Hookup wire

Procedure:
Set up circuit
o Turn power supply output down to zero; turn off the power supply by
pressing the Output on/off toggle button.
o Connect the GND of the power supply unit to a GND pin of the Arduino.
o Connect the 6 V rail to Analog pin 0 of the Arduino. See figure 2.4.3 below
Analog input 0

Figure 2.4.3
Write code
o Use the sketch below in the code listing as a guide on how to take an
Analog reading:
Listing 2.4 A
/////////////////////////////////////////////////////////////////////////////
// AnalogRead to Serial
// Author: Gustavo Zach Vargas
// BME 201
// Spring 2014
/////////////////////////////////////////////////////////////////////////////

// initialize aIn to analog pin 0 of Arduino


int aIn = A0;

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

void loop() {
// read the input on analog pin 0:
int sensorValue = analogRead(aIn);

// print out the value to serial port:


Serial.println(sensorValue);

delay(10);
// delay in between reads for stability
}
Listing 2.4 A
o Note that most of the steps should familiar as they were covered in the
Arduino lab exercise on serial communication.
o The novel code is the following:
//read the input on analog pin 0:
int sensorValue = analogRead(aIn);
o This statement tells the Arduino to take a reading from the pin number
stored in the variable aIn. Note that the value stored in this value is A0. A0
is not a typically acceptable value for an integer but this is an exception for
Arduino as the A indicates that that pin is an analog input.
o The value of the voltage at pin A0 will be converted by the Arduinos ADC
to a value between 0 - 1023 and stored in the variable called sensorValue.
o Make your own Analog Read sketch and upload it to your Arduino.
Analog Read Testing
o Connecting the power supply to the Arduino
Connect a wire to A0 from the +6V power rail.
Connect a wire from the power supply GND rail to a GND pin
(labeled GND) on the Arduino.
This assures that the voltage reading is from the same
reference as the power supply uses to generate the signal.
o Turn on the power supply output
The output should read 0V
o Open the Arduino serial monitor
Confirm the baud rate is consistent with the value in code
Observe a reading and scrolling output (should be zeroes)
Leave the serial monitor open
o Vary voltage input
SLOWLY change the input by turning the knob on the power supply
DO NOT exceed 5V this can damage the Arduino input pin
Note how the output on the serial monitor changes proportionally to
the input voltage
o Convert the value from analogRead to a voltage using the following
information:
REF+
= ( )
2
Where n is the bit size of the ADC. Recall that the VREF+ for Arduino
is 5V and it has a bit size of 10.
Implement this equation in the sketch to provide the analog
reading as a voltage. Check this equation with an SA.
Now we are going to look at an example that is closer to what will be used in your
design project. We are going to build a voltage divider using a 10k potentiometer and
a 1k resistor. A potentiometer is simply a variable resistor that can change from a
resistance of about 0 to 10k in this case, but there are potentiometers with all sorts
of resistance ranges.

One thing to note is that potentiometers are a 3-terminal device, meaning they
have 3 leads. The outside two leads are for Vcc and GND, respectively. The central
lead is the output of the variable resistance generated by the swiper. Take one of the
potentiometers and measure the resistance across it as you change the swiper. Record
the values.

Rmin =
Rmax =

Using Rmin and Rmax found above, what is the expected output voltage range of
the potentiometer circuit?

The circuit you need to construct is shown below in Figure 2.4.4. The
potentiometer is denoted in circuit schematics as a resistor with an arrow pointing to it
(the arrow represents the adjustable swiper on the potentiometer).

Figure 2.4.4
The code below will takes the raw ADC reading, converts it to the corresponding
voltage, and prints it out to the computer. Build the circuit above, load the code onto the
Arduino, and change the potentiometer output. Hook up the oscilloscope to the output
as well and see how closely the readings from the Arduino match the actual voltage
displayed by the oscilloscope. Take at least five different readings by changing the
potentiometers resistance. Average these readings and find the percent error of the
ADC.
Listing 2.4 B
//////////////////////////////////////////////////////////////////////
// AnalogRead - Potentiometer
// Author: R Scott Carson
// BME 201
// Spring 2014
//////////////////////////////////////////////////////////////////////

int potentiometer = A0; // Declare Potentiometer pin


float voltageReading = 0;

void setup(){
Serial.begin(9600);
}

void loop(){
// Read the analog pin
float raw = analogRead(potentiometer);

// Convert the ADC reading to a voltage


voltageReading = (raw/1023) * 5;

// Print out the voltage read by the Arduino


Serial.print("Poteniometer Voltage: ");
Serial.println(voltageReading);

// Sets the sampling rate to be 4 Hz


delay(250);
}
Listing 2.4 B

Make sure you understand this code, how an ADC works, and how to extract a
physical voltage from the ADC reading. The next section builds on these ideas and the
ones presented in previous sections.

Exercise DONE AS A GROUP


Now you have enough knowledge to complete tasks directly related to the design
project. Ultimately, your group will have a microcontroller that reads in an analog
temperature and then controls a heating element depending on whether the
temperature of the solution needs to go up or down. The analog temperature reading
will be a voltage that corresponds to some temperature in degrees Celsius (or Kelvin).
To determine the relationship between temperature and voltage in your system you will
need to create a calibration curve. This calibration curve will be a graph of temperature
vs. voltage for multiple known temperatures. Your group will need to build the circuit
that you are planning to use for your final design and then measure the voltage output
at 10 different known temperatures. Use MS Excel to generate a plot of the data points
and fit a line (or other function) to the data. Save this function because it will be used in
your final design.

For the post-lab assignment, each group should submit ONE copy of the graphed
calibration data, along with the function that you chose to approximate your calibration
curve. This should include a small justification of why the chosen function is the optimal
one and what other functions were tried. Compare the function you generated to the
values listed in the datasheet and comment on any differences. Also include the code
you wrote to determine the calibration data points.

Also, each pair should upload their completed sign-off sheets as a scanned PDF. The
dropbox for the documents are located on moodle.

Das könnte Ihnen auch gefallen