Arduino Lab w24 - 2

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

Arduino Programming Lab

GNG1103 – Engineering Design

Objective
To utilize the Arduino IDE Software platform to write simple control logic commands. This code
will be used to control a variety of inputs and outputs connected to an Arduino Uno
microcontroller. This lab will also expose students to simple control codes, and online resources
available for the Arduino software.

Background
In conjunction with the different models of microcontrollers, the Arduino Company provides an
open-source Arduino Integrated Development Environment (IDE). This programming
environment is written in Java and has been designed to introduce programming to an audience
that is less familiar with coding. Programs written in this environment are called ‘sketches’, and
the language used is a simple one with support for C and C++ programming languages.

A basic Arduino sketch consists of at least two functions: a ‘setup’ function and a ‘loop’ function.
The setup function executes once only at the start of the program execution. It performs any
actions that are initially required to run the rest of the program, such as initializing any external
components and setting the communication frequency between the Arduino board and PC. The
loop function acts as the program's driver and runs in a continuous loop (i.e. “loop forever’). This
loop specifies the order of operations that the microcontroller will perform on an ongoing basis.

Arduino boards, as well as many Arduino-compatible external components, contain hardware for
serial communication. This form of communication can send data at a high rate, but transmits data
bits serially (i.e. one after another, a single bit at a time). This allows the components of the system
(or a PC) to communicate larger and more complex sequences of data much more easily, with less
demands on physical input or output pins.

Because of Arduino’s open-source nature, third party companies, as well as end users are free to
take the software and tailor it to their individual needs. This means that for almost any application,
sketches are available for download online. Companies making external devices (such as a motor
shield or sensors) for use with Arduino boards often have example sketches and sketch libraries
available for specific use for their products. These resources can be used to create a custom sketch
that can use many different peripherals at once, by combining aspects of many different example
sketches. Before writing your own code, like we will be doing here, it is worth looking online to
determine if something similar is available online.

1
Resistor

A resistor is an electrical component which creates electrical impedance, or resistance to current


flow. The amount of resistance a resistor provides can be read from the bands of colour on the
resistor, which are read left to right. For four bands resistors, the first and second bands represent
digits, while the third band represents a multiplier to multiply the digits of the first and second
band by. The fourth band is the tolerance, it represents how much the resistor may deviate from
the value indicated by the bands. The value of the resistor can also be determined using the ohmic
function of a multimeter. The table and image below shows how to read the colours.

Figure 1 : Resistor colour codes

2
Resistors are often used in series with components to reduce the amount of current flowing through
a circuit, often to protect components rated for lower current amounts.
Pull-up and pull-down resistors are used to bias an input on the Arduino to be either HIGH or
LOW respectively. This needs to be done as the resting level of the input isn’t necessarily 0. This
is especially useful when working with sensors that have an analog output.

Photoresistor

A photoresistor is a resistor that changes its resistance to current in response to the amount of light
it is exposed to. As the level of light the resistor is exposed to increases, its resistance decreases,
conversely, as the level of light the resistor is exposed to decreases, its resistance increases.

Downloads
This lab utilizes the Arduino Integrated Development Environment (IDE) which is a software that
you will need to download.
This should already be installed on the lab computers, but may have to be installed if a student is
using their personal computer or if the lab PCs have been corrupted or altered (e.g. by other
students).

The Arduino IDE can be downloaded from here: https://www.arduino.cc/en/Main/Software

The CH340 driver (choose the windows or MAC version) can be downloaded from here:
http://www.wch-ic.com/downloads/CH341SER_ZIP.html

Important tools
See Appendix I for a theory about all the important components that will be used in this
laboratory.

Apparatus and Equipment Overview


The following components will be used in this lab:
● 1 x Arduino Uno R3 Microcontroller
● 1 x USB 2.0 Type A Plug to USB 2.0 Type B Plug Cable
● 1 x Lab or Personal Computer (running Windows, Macintosh, or Linux OS)
● Arduino IDE Software
● 1 x Temperature sensor TMP36
● 1 x Half breadboard
● 13 x Male-male jumper wire
● 2 x 5mm LED

3
● 2 x 220 Ω resistor
● 1 x 1 kΩ resistor
● 1 x photoresistor

Pre-Lab Preparation
Before arriving to the lab, students should review the lab manual and familiarize themselves with
the lab setup and procedures. Students may use their own computer for this lab if they wish (the
software is free), provided that they have downloaded and installed the Arduino IDE, as well as
the required libraries outlined in downloads section. Reviewing the Arduino IDE syntax, as well
as trying to write some of the programs beforehand is also encouraged. A useful list of commands
used in the Arduino IDE can be found here:
https://www.arduino.cc/en/Reference/HomePage.
Additionally, please ensure that you bring a USB-C dongle if your computer only has USB-C
ports. This will allow you to connect the Arduino board to your computer for programming and
communication using the USB-A cable.
All of the lab PCs have the software already installed.

4
Review Questions
What is the programming language used for Arduino?
______________________________________________________________________________
______________________________________________________________________________
What are the 2 main sections in an Arduino program?
______________________________________________________________________________
______________________________________________________________________________
What are the 3 main sections on the Arduino Uno board?
______________________________________________________________________________
______________________________________________________________________________
What is the difference between terminal strips and power rails on a breadboard?
______________________________________________________________________________
______________________________________________________________________________
What does electrical polarity mean?
______________________________________________________________________________
______________________________________________________________________________

Part A – LED Blink Program


The next part of this lab reviews the basic method of connecting and programming an Arduino
microcontroller. It utilizes a sample sketch included in one of the Arduino IDE’s default libraries,
and is primarily used to verify that the microcontroller and the connection are both functioning
properly and gives a basic idea of how to run a very simple Arduino sketch program.

1. Connect the Arduino board to an open USB port on the computer with the USB cable. The
Arduino board LEDs should light up, as power is drawn through the USB connection.
2. Launch the Arduino IDE Software, and pick ‘Arduino Uno’ from the dropdown menu in
Tools→Board→Arduino AVR Boards. Back in the ‘Tools’ tab, select ‘Port’ and choose
the serial port that the Arduino is connected to. If the correct serial port is not apparent,
unplug the Arduino, and see which port disappears. Re-connect the board and select that
port. Remember, if you don’t select the correct serial port, then you won’t be able to see
any printed output.

5
Figure 2 : Arduino port selection
Note: If the port is not detected by the IDE it may be a driver error. Try to download and install
the following CH340 driver on your computer (choose the Windows or MAC version):
http://www.wch-ic.com/downloads/CH341SER_ZIP.html

3. Open File→Examples→01.Basics→Blink. This will open a new sketch that looks like the
one below.

Figure 3 : Blink example

6
4. Now verify and upload the sketch to the Arduino board. To verify, click the check mark in
the upper left hand corner. The Arduino IDE will try to compile the sketch (without
uploading to the board), and warn of any syntax errors in the programming. Once this is
complete, press the upload button (arrow beside the check mark). The sketch will
recompile, and upload to the board.

Figure 4 : Verify and upload buttons


5. Once the upload is complete, the program will automatically run on the microcontroller. In
this case, the LED labeled ‘L’ on the Arduino should flash slowly.

Question 1. How fast does it flash (i.e. what is the flashing rate and duty cycle)?

_____________________________________________________________________________

_____________________________________________________________________________

Question 2. Conduct two separate experiments by modifying the delay value. First, set the
delay to 5000, and then set it to 300. After making each change, please verify and upload the
updated code. What happens to the “L” on the Arduino Board in the two cases?

_____________________________________________________________________________

_____________________________________________________________________________

6. Change the variable LED_BUILTIN to 13, they represent the same pin on the Arduino.
Print the value of this variable in the serial monitor by adding Serial.begin(9600); and
Serial.print(LED_BUILTIN); like in the following picture.
7. Upload your new code.

7
Figure 5 : Blink example modified
8. Open the serial monitor to see what is being printed, select Tools→Serial Monitor.

Figure 6 : Opening the serial monitor


9. Replace Serial.print(LED_BUILTIN) by Serial.println(LED_BUILTIN) and then by
Serial.println(“LED_BUILTIN”). Verify and upload your code.

Question 3. What happened in those two cases?

_____________________________________________________________________________

_____________________________________________________________________________

8
10. Create the corresponding circuit using a LED, a resistor and some electric wires (diagrams
provided below).

Figure 7 : Circuit diagram for one LED blink program


Question 4. What is the relation between this LED and the LED on the Arduino board? If
there is something wrong with the circuit, how do you fix it?

_____________________________________________________________________________

_____________________________________________________________________________

Part B – Photoresistor
This part of the lab uses a simple circuit to hook up the various components that are required for
the lab (see the diagram below).

Note that the neater your circuit is, the easier it will be to debug it, if/when there are problems and
the less likely that wires will come loose, etc. In general, you want to have your wires sit flush
with the plastic surface of the breadboard, so that you can see all of the connections that you are
making and so that people trying to help you can see them too! Using color-coded wires (e.g. red
for +5V and black for ground) is another common practice to help simplify debugging. While the
9
circuit will work with any color of wire, following such conventions will make your circuit ‘better’,
much like the improvements that you get in usability, when including comments in your computer
programs.

1. Connect the photoresistor and the resistor (1 kΩ) to the Arduino board by using the wiring
diagram shown in the figure below.

Figure 8 : Photoresistor circuit diagram


*Note: Using the image above as a guide we can connect the photoresistor. The red wire must
connect to the 5V power source, yellow will connect to the analog I/O port (#A0), and finally
black will connect to the resistor which is connected to the common ground.

2. Your environment and the particular photoresistor you have will affect the value of the
threshold limits that need to be defined. Enter the following code and open the serial
monitor (as explained in the previous section) to see the values being read from the sensor.
int light_sensor=A0;
int lightVal;

void setup() {
pinMode(light_sensor, INPUT);
Serial.begin(9600);
}

10
void loop() {
lightVal=analogRead(light_sensor);
Serial.println(lightVal);
delay(500);
}
3. Place your hand in front of the resistor at varying heights and observe the change in values.
Place your hand about 10-15cm from the sensor and note down the value being read from
it.
4. Unplug the USB cable when you are done.

Question 5. If we want to use the analog port A5 instead of A0 a minimum of two steps need
to be done. What are those steps?

_____________________________________________________________________________

_____________________________________________________________________________

Part C – Temperature Sensor


This part of the lab uses a simple circuit to hook up the various components that are required for
the lab (see the diagram below).

Note that the neater your circuit is, the easier it will be to debug it, if/when there are problems and
the less likely that wires will come loose, etc. In general, you want to have your wires sit flush
with the plastic surface of the breadboard, so that you can see all of the connections that you are
making and so that people trying to help you can see them too! Using color-coded wires (e.g. red
for +5V and black for ground) is another common practice to help simplify debugging. While the
circuit will work with any color of wire, following such conventions will make your circuit ‘better’,
much like the improvements that you get in usability, when including comments in your computer
programs.

This program will read the temperature of the environment using a TMP36 temperature sensor, as
well as light up LEDs when the temperature passes a certain threshold. The temperature will be
printed on the serial monitor of the Arduino IDE. The temperature sensor has an operating
temperature range of -40° C to + 125° C and is accurate to ± 1° C over the range of -1° C to + 25°
C.

1. Open a new sketch in the Arduino IDE (File→New Sketch). Make sure that the correct
microcontroller and communication port is still selected by checking the bottom right of
the window.

11
Figure 9 : Arduino IDE connected port
2. Connect the TMP36 temperature sensor, and 2 LEDs to the Arduino board by using the
wiring diagram shown in the figure below (R1=220Ω, R2=220Ω).

Figure 10 : Temperature sensor circuit diagram with 2 LEDs


*Note: Using the image above as a guide we can connect the temperature sensor. The red wire
must connect to the Vin power source, yellow will connect to the Analog I/O port (#A0), blue will
connect to the digital I/O port (#11), green will connect to the digital I/O port (#10), and finally
black will connect to the common ground.

3. Define the temperature sensor and LEDs as variables above the void setup as shown below.
Pin A0 will be used for the temperature sensor.

12
4. Define a variable for your temperature to have a boundary to change from green to red if
the temperature passes a certain threshold.

5. In the void setup we want to activate the serial monitor, setup the LEDs as OUTPUTS and
prime the temperature sensor so we can request data in the loop.

6. In the loop function, print a few lines in the serial interface to check if the sensor is working
properly. Then, call for the temperature and store the value in a variable that will be used
later.

7. Upon receiving the information from the TMP36 sensor we will need to convert the voltage
signal into a value with Celsius units.

8. Print the temperature value from the sensor to see if the LEDs are lighting up properly.

13
9. In defining the variables, a threshold variable was set to “tempLimit =23”. When the
temperature is below 23, use if statement to make the green LED light up and when the
temperature is above 23, use the else if statement to make the red LED light up. Print text
that mentions which LED is activated.

10. Add a delay to measure the temperature every 0.5 seconds.

11. Connect the Arduino board to the computer by using a USB cable and upload the sample
code to the Arduino controller. Open the serial monitor (Tools→Serial Monitor) to see if
you are reading the temperature correctly.
12. Heat up the temperature sensor (heat coming from your computer, cover it with your hands
etc…) until the temperature goes above the threshold value.
13. Unplug the USB cable when you are done.

Question 6. What is the behavior of the LEDs on the breadboard?

_____________________________________________________________________________

_____________________________________________________________________________

14
Question 7. What is the difference between an “if” statement and an “if … else” type of
statement?

______________________________________________________________________________
______________________________________________________________________________

Part D - Practice Exercise


In this practice exercise you will be reusing the previous circuit but adding a photoresistor and
modifying the code to have the red LED react to the changes in the photoresistor and also have
the green LED react to the temperature sensor.
1. Using the same circuit modify it to resemble the following:

Figure 11 : Circuit diagram for the photoresistor and temperature sensor


*Note: the above circuit is the same as the previous section with the additional photoresistor and
a 1kΩ resistor. Using the image below as a guide we can connect the photoresistor. The red wire
must connect to the 5V power source, brown will connect to the analog port (A1), and finally
black will connect to the common ground. Now we will have to make a few changes to the code
in order to get the circuit to work the way we want.

15
In the following lines of code, modify the “***” so that we can achieve the following desired
functions:
● When the photoresistor reaches a limit value (determined in part B) or higher the red LED
will remain off, however, if the value drops below the limit the red LED will turn on.
● When the temperature sensor reaches a value lower than 23 degrees Celsius the green LED
will be activated, but when the value is higher than 23 the green LED will turn off.
● Open a serial monitor and print the temperature and light values every second and let the
user know when any of the lights turn on.

// Define the analog pins for temperature and light sensors


#define tempPin A0
#define lightPin ***

// Define pins for LEDs


int greenLedPin = ***;
int redLedPin = 11;

// Define threshold values for temperature and light


int tempLimit = ***;
int lightLimit = 400;

void setup() {
// Begin serial communication at 9600 baud rate
Serial.begin(***);

// Set pin modes for LEDs


pinMode(redLedPin, OUTPUT);
pinMode(greenLedPin, *****);
}

void loop() {
// Read the analog voltage from the temperature sensor
int readingTemp = analogRead(tempPin);

// Convert the analog reading into voltage


float voltage = readingTemp * (5.0 / 1024.0);

// Convert voltage to temperature in Celsius


float temperatureC = (voltage - 0.5) * 100;

// Print temperature in Celsius to the serial monitor


Serial.print("Temperature: ");
Serial.print(temperatureC);
Serial.print("\xC2\xB0"); // Display the degree symbol

16
Serial.print("C");

// Check if temperature is below the limit


if (temperatureC <= tempLimit) {
Serial.print", Green LED is ON");
digitalWrite(greenLedPin, ***);
}
// Check if temperature is above the limit
else if (temperatureC > tempLimit) {
Serial.print(", Green LED is OFF");
digitalWrite(greenLedPin, ***);
}

// Read the analog value from the light sensor


int readingL = analogRead(lightPin);

// Print light value to the serial monitor


Serial.print(", Light value is ");
Serial.print(readingL);

// Delay for a short period


delay(500);

// Check if light value is above the limit


if (readingL > lightLimit) {
Serial.println(", Red LED is ON!");
digitalWrite(redLedPin, ***);
}
// Check if light value is below the limit
else if (readingL < ***) {
Serial.println(", Red LED is OFF");
digitalWrite(redLedPin, ***);
}

// Delay for 0.5 seconds


delay(***);
}

Submission
Submit this document with the answers to the questions as well as the code of the last question and
a picture of the circuit of the last question by uploading to Brightspace before the due date. All
uploaded files must be submitted as one submission with many uploads, not many individual
submissions.

17
Appendix I
Arduino Board

Arduino senses the environment by receiving inputs from many different types of sensors, and can
also affect its surrounding environment with outputs that control lights, motors, heaters, or other
actuators. These input and output signals are made available on a digital pins header (see diagram
below).

Digital Pins

Figure 12 : Arduino UNO digital pins


● These pins can be configured as digital INPUTS and used to send signals into the Arduino
processor (e.g. to read sensed logic voltage levels). Digital signals are normally binary and
only have two distinct voltage values (0V or ‘low’ or 5V or ‘high).
● The pins can also be configured to act as an OUTPUT to drive digital ‘high’ or ‘low’ logic
voltages from the Arduino processor (e.g. to turn things on or off).
● Pin13 (LED): There is a built-in LED pre-connected to digital pin 13. When the value of
the pin is driven HIGH by the processor, the LED on the board is illuminated, when the
pin is LOW, it's turned off. This can be used as a status indicator when programs are
running.
There are many types of real-world signals which are not binary digital ones (i.e. they have more
voltage levels than just ‘high’ or ‘low’). These kinds of signals can have a continuous range of
voltage values and are termed analog signals. These signals need to be converted into digital
representations which can be used inside the software-executing portion of the Arduino processor
(which only uses binary digital signals). Analog signal inputs can be accepted for conversion into

18
digital via the Analog Pins header (see diagram below). The Analog to Digital (A/D or “A to D”)
conversion is done inside the processor with specialized circuitry.

Analog Pins

Figure 13 : Arduino UNO analog pins


To help power simple external circuitry, the Arduino also provides a few common digital voltage
output values (e.g. 3.3V and 5V) as well as a 0V or reference voltage (Ground or ‘GND’). These
pins are located next to the Analog pins header (see diagram below). The ‘Vin’ pin is a diode-
drop voltage away from the input voltage being supplied to power the Arduino board and generate
the other voltages.

Power Pins

Figure 14 : Arduino UNO power pins

19
Arduino Software

You can tell your Arduino what to do by writing code in the Arduino programming language and
using the Arduino development environment. Some important facts for the lab are given below
and are intended to help new programmers (this is probably less useful for more experienced
Arduino programmers). If you need more help, ask the Teaching Assistant for clarification or use
the internet to try and find out the answers to your questions:
● Comment bars: “/* */” and “//”: These allow you to write commentaries in your code.
Everything you write in between “/* */ “or after “//” will be a comment and will not affect
the code.
● Semicolon “;”: This character ends a program statement and lets the compiler know ‘the
end of the current line/statement’. A compiler is a computer program that transforms source
code written in a programming language into another computer language, usually one that
can be executed more easily on a real processor.
● “setup” function: The setup function runs only once and performs any actions that are
initially required to run the rest of the program, such as initializing any peripheral
components and setting the communication frequency between the Arduino board and PC.
https://www.arduino.cc/en/Reference/Setup
● “loop” function: The loop function acts as the programs driver; it runs in a continuous
loop, and specifies the order of operations that the microcontroller will perform.
https://www.arduino.cc/en/Reference/Loop. Execution starts at the top, goes through the
contents of the loop and then starts executing from the top again. This procedure is
repeated forever.
● Brackets “{ }” Start and ends a function or is used to group a set of different statements
together, making them effectively a single long sequential statement, that is executed as a
‘glob’.
● pinMode(): Configures the specified pin to behave either as an INPUT or an OUTPUT,
see https://www.arduino.cc/en/Reference/PinMode for more information.
○ Syntax: pinMode(pin, mode)
● digitalWrite(): Writes a HIGH or a LOW value to a digital pin.
○ If the pin has been configured as an OUTPUT with pinMode(), its voltage will be
set to the corresponding value: 5V (or 3.3V on 3.3V boards) for HIGH, 0V (ground)
for LOW, see https://www.arduino.cc/en/Reference/DigitalWrite for more
information.
○ Syntax: digitalWrite(pin, value)
● Delay: Pauses the program for the amount of time (in milliseconds) specified as the
parameter.
○ Syntax: delay(ms) https://www.arduino.cc/en/Reference/Delay
● Variable: a variable is a storage location that is paired with an associated symbolic name
(an identifier), which contains some known or unknown quantity of information referred
to as the value of that variable.

20
● In this lab we are going to use two types of variable value types: “int” and “float”.
○ Int : Allows you to store integer (i.e. counting whole) numbers.
https://www.arduino.cc/en/Reference/Int.
○ Syntax: int variable = value;
○ Float : Store floating-point numbers, a number that has a decimal point and an
exponent. The result is that these kinds of variables can have a much larger range
than is possible for integers, but they will have some roundup errors because they
are implemented with finite precision (i.e. only a certain number of decimal digits
can be used). See https://www.arduino.cc/en/Reference/Float for more
information.
○ Syntax: float variable = value;
● Serial.begin(): This starts off the serial communications interface hardware. You will need
this, if you want to print anything using the serial monitor.
○ For more information, see https://www.arduino.cc/en/Serial/Begin for more
information.
○ Syntax: Serial.begin(9600) sets the serial interface to run at a rate of 9600 serial
bits/s
● Serial.print(): Prints data to the serial port as human-readable text, see
https://www.arduino.cc/en/Serial/Print for more information.
○ Syntax: Serial.print(value)
● “if” statement: See https://www.arduino.cc/en/Reference/If : This lets you conditionally
execute the following statements, depending on a tested condition.

Breadboard

A breadboard is used to prototype a temporary circuit. You can build, test and analyze a circuit
without any permanent connections. It is made up of terminal strips and power rails. The terminal
strips are used to hold any number of components in place and make electrical connections in a
horizontal row. The power rails are the long vertical strips and are used to facilitate power (+) and
ground (-) connections by placing them all in one column. For some general background on how
such a breadboard actually works, take a look at the YouTube video about breadboarding at:
https://www.youtube.com/watch?v=6WReFkfrUIk.

21
Figure 15 : Breadboard
Voltage dividers

A voltage divider is a simple circuit arrangement that allows you to obtain a lower voltage from a
higher voltage source. It consists of two resistors connected in series between the high voltage
source and ground, with the output taken from the junction between the two resistors.
The purpose of a voltage divider in Arduino is typically to scale down a voltage level to a range
that the Arduino's analog input can handle. The analog inputs of an Arduino can read voltages
between 0 and the reference voltage, which is typically 5 volts for most Arduino boards. If you
have a higher voltage signal that you want to measure, you can use a voltage divider to bring it
down to this range.

Figure 16: Voltage divider circuit

22
The resistors used in the voltage divider determine the output voltage. The output voltage is
calculated using the voltage divider formula:
Vout = Vin * (R2 / (R1 + R2))
• Vin is the input voltage from the high voltage source.
• Vout is the output voltage from the high voltage source.
• R1 is the resistance of the first resistor connected to the high voltage source.
• R2 is the resistance of the second resistor

23

You might also like