ET1016 IEP Lab Guide Using Basic Embedded System
ET1016 IEP Lab Guide Using Basic Embedded System
Programming
Lab Guide
Official (Closed), Non‐Sensitive
In this module, you are required to carry out an Arduino project to further develop your programming
skill and apply your C++ programming knowledge in Engineering applications.
Light
Logic voltage Drivers Motors
Sensor
Temp to
Temp Voltage &
Microcontroller LED
Sensor ADconvert (uC)
Digital
Micro Intelligent Analog Power
Amplifier Speakers
phone ADconvert Process & Convert Amplifier
Some Decision Some
Input Signal Output Signal
Input ‘The Brain’ Output
Conditioning Conditioning
Devices Devices
& interface & interface
There are many programming languages that are used for Embedded Systems like Assembly
Language, C, C++, JAVA, Python, etc.
In this module, you will learn how to use C++ programming language to develop a simple
engineering application running on an Arduino Uno based embedded system.
2. What is Arduino?
Arduino is an open‐source platform used for building electronics projects involving both
hardware and software.
The Arduino board is in the form of a printed circuit board (PCB) that is specifically designed
to use a microcontroller chip as well as other inputs and outputs. It also has many other
electronic components that are needed for the microcontroller to function or to extend its
capabilities.
You write code in the Arduino software to tell the microcontroller what to do. For example,
by writing a line of code, you can tell an LED to blink or stop blinking. If you add a pushbutton
and add another line of code, you can tell the LED to turn on only when the button is pressed.
Next, you may want to tell the LED to blink only when the pushbutton is held down. In this
way, you can quickly build a behaviour for a system that would be difficult to achieve without
a microcontroller.
Similarly to a conventional computer, an Arduino can perform a multitude of functions, but
it’s not much use on its own. It requires other inputs or outputs to make it more useful. These
inputs and outputs allow a computer to sense objects in the world and to affect the world.
There are many types of Arduino boards, each with its own design to suit various
applications. Deciding what board to use can be a daunting prospect because the number of
boards is increasing, each with new and exciting prospects.
However, one board can be considered the backbone of the Arduino hardware; this is the
one that almost all people start with and that is suitable for most applications. It’s the
Arduino Uno. R3 relates to the revision of the features on the board, which includes updates,
refinements, and fixes. In this case, it is the third revision.
The language that you will use to code the Arduino is C++. And we will use Visual
Micro to write/develop your Arduino Programs in Visual Studio Environment that you
are familiarised with by now.
After the setup ( ) function is executed, the loop ( ) function runs next. The loop ( ) function
hosts statements like reading inputs, triggering outputs, checking conditions, etc. As the
name suggests, the loop( ) function executes the set of statements (enclosed in curly braces)
repeatedly. This function is the core of all Arduino programs and does the bulk of the work.
One example is shown as follows. Refer to the comments for explanation of the code.
void setup() {
pinMode (pin_number, OUTPUT); // set the ‘pin_number’ as output
pinMode (pin_number, INPUT); // set the ‘pin_number’ as input
}
void loop() {
digitalWrite (pin_number,HIGH); // turns ON the component connected to ‘pin_number’
delay (1000); // wait for 1 sec or 1000 milliseconds
digitalWrite (pin_number, LOW); // turns OFF the component connected to ‘pin_number’
delay (1000); //wait for 1sec
}
Now, let us take a giant leap and do some experiments with Arduino.
Refer to the lab on “Getting started with Programming the Arduino Board” and other lab exercises to
learn how to write programs with engineering applications.
With the Arduino Uno and the I/O shield (Rich Shield), you will learn how to create and develop some
simple engineering projects, such as the following:
Control of LEDs
Monitoring Light sensor and Control of LEDs
Passive buzzer play tone
Button detect
Knob control for LED brightness
Temperature and humidity measurement and display
Infrared remote control, etc.
Lab Experiment 1:
Installing Visual Micro (Arduino IDE for Visual Studio)
Getting Started with Arduino Programming
Controlling LEDs on IO Shield
Activities
1.1 On the menu bar in Visual Studio, choose Extensions > Manage Extensions
1.2 Click Online in the Manage Extensions window and then download the Arduino IDE for Visual
Studio 2022
1.3 Close or exit all Visual Studio Application. The following window will pop up.
At the end of these steps, you will be ready to write, compile, debug, and upload your Arduino
sketches.
Note: Arduino sketch is the name that Arduino uses for a program. It's the unit of code that is
uploaded to, and run on an Arduino board. A basic Arduino sketch consists of two functions: setup()
and loop().
If it is the first time after you have installed Arduino for Visual Micro, the Configuration Manager will
pop up where you can configure your system. For example, it pops up the first time that a new
Arduino project is created. Visual Micro must know the version and installation path of the Arduino
software that you have installed previously. If Arduino IDE was not installed previously, it is
recommended that you follow the following steps below to install it.
Step A:
For the purpose of setting
up and configuring the
Arduino IDE, create a new
project. Search for
“Arduino Simple Empty
Project” or “Blink Led
Example” template and
click next.
Step B:
Choose a location, enter a
project name and create a
project.
Important Note: Do NOT install the Arduino IDE in any network drive.
Step C (i): (If your computer does not have the Arduino software installed before)
Click the "Download/Install IDE" button. It will lead you to Arduino home page (Arduino.cc). Click the
Software menu on top of the page. Download Arduino IDE 1.8.19 version and install it. After the
Arduino IDE installation is completed, the Arduino IDE folder location is automatically specified. Click
"OK" in the "Configure IDE Locations" window. The Arduino project will be created and shown in the
Visual Studio IDE.
Record the Arduino IDE installation path here, which might be useful in the later part on installing /
using RichShield library, as Arduino IDE installation path might be different from laptop to laptop:
________________________________________________________________________________
Step C (ii): (If your computer already has Arduino software installed before)
Click the "OK" button instead.
Now the initial setup of your system is done. Close the project.
You may now continue by creating a new project or by opening an existing project.
1
Steps to key in Visual Micro License Key into Visual Studio 2022 after installing Visual
Micro.
From Visual Studio menu, click Extensions | vMicro |
Buy or Activate a Visual Micro License,
then enter the key given by your lecturer and
click Activate Purchased Key.
Or,
From Visual Studio menu, click Tools | Options | Visual Micro | General | Application
Authentication | License Key. After entering and activating the key, click OK to close the options
window and re‐start the IDE.
3. Create a Visual Micro Project for the Blink LED Program Example, Compile,
Upload and Run It
3.1 Launch Visual Studio IDE. Create a new project. Select "Blink Led Example" template
and click next.
3.2 In the Configure your new project window, enter project name and location of your
project and click Create.
Before you can upload your Arduino sketch, you must connect your Arduino board and select the
correct board model. The following section shows you how to do it.
Use the Visual Micro "Micro Boards" toolbar to select the board model you use.
Note: If the Visual Micro toolbar is missing, then you can show it by right clicking on an empty space in
the toolbar area and checking "Micro Boards"
Connect your Arduino board to your PC using the USB cable provided.
Use the Visual Micro Serial Communications toolbar, for this purpose.
Tip: If you connect your board to a different USB plug on your PC, then the COM port number may
change. Whenever you have problems uploading your sketch to the Arduino board, first check if the
proper serial port is selected.
Note: If you only want to compile but not upload your sketch,
click the toolbar button or choose vMicro > Build from the
menu.
Check that the built‐in LED on the Arduino Uno board is blinking. As your Uno board is connected to
the Rich Shield, you can only see the blinking LED on the board underneath the Shield.
// the setup function runs once when you press reset or power the board
void setup() {
// you may add more program statements to turn ON/OFF other LEDs
Arduino LED
Start Start
or
LAB1
Practice 1 : Writing User‐defined functions for LED control
In this practice, you will apply using loops and functions in your program to control how a LED
will blink, e.g. different blinking rate, how many times to blink, etc.
1) Write a program that causes the blue LED connected to pin 6 on the Arduino to blink,
alternating between fast blinks and slow blinks as follows.
The LED should blink 5 times quickly and then it should blink 5 more times slowly.
When blinking quickly, the LED should have a 1 second period, so it should be high (to be
turned on) for 0.5 seconds and low (to be turned off) for 0.5 seconds.
When blinking slowly, the LED should have a 4 second period, so it should be high for 2
seconds and low for 2 seconds.
The LED should continue to blink in this alternating fashion for as long as the Arduino
receives power (keep your Arduino Board connected to your laptop to power it on).
Start
(a) Use two for loops:
Set BLUE LED PIN 6 as output,
The 1st for loop to control the LED to fast blink 5 times Declare int variable count
and the 2nd loop to control the LED to slowly blink 5
count=5
times (refer to the flowchart on the left.)
No Yes
Is count 0?
(b) The codes in the loop () can be improved / shortened Write 1 or HIGH count=5
by 2 function calls as follows: to BLUE LED Yes
Is count 0?
void loop() { Delay 0.5 sec No
Write 1 or HIGH
blink(LED_BLUE, 1000, 5); Write 0 or LOW to BLUE LED
to BLUE LED
blink(LED_BLUE, 4000, 5); Delay 2 sec
} Delay 0.5 sec
Write 0 or LOW
count‐‐ to BLUE LED
Refer to the flowchart below to implement the blink
function with the following function prototype (use Delay 2 sec
void blink(int pinNum, int blinkPeriod, int blinkTimes); Flowchart for Lab 1 Practice 1(a)
funcitonName This is the symbol for user‐defined function (refer to Appendix D for reference).
School of EEE
`. Lab Guide Page 15
Official (Closed), Non‐Sensitive
LAB1
Practice 2 : Blinking Red LED to simulate emergency flashing lights
(Optional based on your project needs)
Red beacon lights are associated with emergency situations. In Singapore, red flashing lights on
ambulances and fire engines signal to other road users that there is an emergency. All other
vehicles are legally bound to give way to the emergency vehicles in such situations. Red
beacons are also used to warn of hazardous conditions, and for people to stay away from a
certain area.
(a) Modify the Blink LED Program Example to blink the red LED instead as a simulation of the
red beacon lights.
To save your program, click File > Save xxxxx.ino (where xxxxx follows the same name as your
project).
Note: In the original Arduino IDE, programs are called sketches. These are files with .ino
extension placed in the folders on disk. An INO file contains source code written in the Arduino
programming language. INO files are used to control Arduino circuit boards. Visual Micro can
create projects from existing sketches as well as create new ones.
(b) Practise drawing the block diagram and flowchart in the space provided below and
modify your program by calling the “blink function” designed in Practice 1(b) to simulate
emergency flashing lights.
LAB1
Practice 3 : Traffic Lights Sequence for vehicles (Optional based on your
project needs)
Create a new project to control the LEDs to simulate the Traffic lights sequence as follows:
Note: You can create this new project under the same "Visual Studio Solution".
Activities
1.1 Launch Visual Studio. Create a new project. Select "Arduino Simple Empty Project" (you may use
the search box to search for it).
1.2 In the Configure your new project window, enter project name and location of your project and
click Create. Your screen should look like this:
void setup() {
void loop() {
1.4 If you only want to compile but not upload your sketch, click the toolbar button or
choose vMicro > Build from the menu.
To upload your Arduino sketch, you must connect your Arduino board to your PC using the USB
cable, select the correct board model and select the serial port in the port selection box.
Normally, you will only see one serial port, which is the port your Arduino board is connected to.
*The port number that your Arduino Board is connected to might be different from the one shown above.
School of EEE Lab Guide Page 19
Official (Closed), Non‐Sensitive
Start the compilation and upload process by clicking on the Micro Project toolbar or click the
vMicro > Build & Upload from the menu.
Your sketch will compile, and after successful compilation, Visual Micro will upload it to your
Arduino board.
In this case, a window will pop up. This window is called Serial monitor. Whenever you press
button K1, the string message in Serial.println("Button K1 is pressed") will appear in the Serial
monitor.
You have successfully run the basic code. Do the practice on the
next page to use the button switches to control LEDs.
Block diagram and flowchart for
Start
this coding activity are given
below and on the right Set Button K1 PIN 8 as input with
respectively for your reference. INPUT_PULLUP mode
Set serial port data rate to 9600 bps
No
Is Button K1 pressed?
Yes
Delay 0.1 sec
No
Is Button K1 Relessed?
Yes
LAB2
Practice 1 : Button to control Traffic light sequence
Modify the above program to simulate pedestrian’s request to stop the vehicles’ flow when
button K2 is pressed. 2 seconds after the button K2 is pressed, the green LED will be OFF and
yellow LED will be ON for 2 seconds followed by red LED turned ON for 4 seconds. The
pedestrian can then safely cross the road. After this, the green LED is ON again indefinitely if
button K2 is not pressed.
(a) Draw the block diagram and plan your program with the flowchart in the space provided
below.
(b) Write your program with the use of a function. Its function prototype is given below:
Introduction
The blue knob in the IO shield is connected to Analog pin, A0. It
is an analog input.
It is not necessary to use pinMode () to set it as an input.
The int analogRead(int analogPin) function is used to check the strength of the analog
signal that is internally digitised by the Arduino board.
analogRead(A0) returns a value ranged from 0 to 1023 which is a 10‐bit digitised value
(from Analog to Digital conversion) of the analog signal strength as the knob is turned from
one end (anticlockwise) to the other end (clockwise).
The knob can be used to simulate an analog input or sensor, such as water level sensor,
distance sensor, pressure level sensor and so on.
Similarly, the Light Dependence Resistor, LDR is connected to analog pin, A2 and
analogRead(A2) is used as it is an analog input/sensor (light level sensor).
LDR are light sensitive devices most often used to indicate the presence or absence of light,
or to measure the light intensity.
Its resistance decreases with increasing light levels. Typically > 1 MΩ when dark and < 1 kΩ
in high light levels with response time of 2 – 50 ms.
LDR on the shield is connected such that
o When there is no light (or full darkness environment), analogRead(A2) returns a very
small value (can be less than 10).
o When very strong lights shine on it, analogRead(A2) returns a very high value (can be
near to 1023, the maximum possible value).
Activities
Create a new project using "Arduino Simple Empty Project" template as in the previous steps. Type
the following code to setup( ) and loop( ). Compile, upload to run the program by slowly turning the
blue knob clockwise and anticlockwise.
void setup() {
Serial.begin(9600);
}
void loop() {
knobValue=analogRead(KNOB_PIN); //read value of the knob and assign it to the variable
Serial.println(knobValue); //print out the value of the knob to the Serial monitor
delay(100);
}
Write down your observation / learning points on how to program for the knob.
LAB2
Practice 2 : LED ON/OFF control with LDR and Brightness control with Knob
(Optional based on your project needs)
(a) Add in the code to use the LDR to control LED.
Using Serial.println ( ) function, observe how ldrValue changes as you use your phone torch
light to shine on it and as you cover it with a black cloth or with your hand.
(b) Apply the LDR control such that when the ldrValue is lower than a DARKNESS level (to be set
by you with reference to the ambient light of your surrounding), the yellow LED (pin 7) will be
turned ON, otherwise, the yellow LED will be turned OFF.
(c) Add in a control in your program to dim another LED light when the blue knob, served as a
dimmer switch, is turned anticlockwise. Conversely, the LED brightness level will increase
when the knob is turned clockwise.
Choose either the green LED (pin 5) or blue LED (pin 6). Pin 5 and pin 6 are 2 of the PWM
(Pulse Width Modulation) pins that can be used with the analogWrite ( ) function described
below.
(d) Draw the block diagram and plan your program with the flowchart on the next page. Write
your program with a user‐defined function:
void dimmerSwitch(int outputPwmPinNum, int inputControlPinNum);
Design and implement this function, and use it in your program.
The Arduino's built‐in library function makes PWM easy to use; simply call analogWrite(pin,
value), where value is an 8‐bit number from 0 to 255, and pin is one of the PWM pins (3, 5, 6, 9,
10, or 11).
The 8‐bit value corresponds to an effective voltage of 0 to 5 Volts. The higher the value, the
higher the effective voltage to the PWM pin.
The analogWrite function provides a simple interface to the hardware PWM, but doesn't provide
any control over frequency.
In this lab, you will learn how to program the other input and output devices on the RichShield. You
will need to install the RichShield libraries which provide some useful functions and examples to help
you in programing these input and output devices more easily and you do not have to write too much
code to complete the project.
the Arduino IDE installation folder on your Laptop shown on Lab Guide Page 9.
Introduction
A buzzer is a basic audio device that generates a sound from an incoming electrical signal. An
active buzzer generates the sound itself. You basically just turn it
on or off. A passive buzzer, on the other hand, needs a signal
source that generates the sound.
The buzzer in the RichShield is a passive buzzer which is connected
to pin 3, one of the PWM pins of Arduino Uno.
You will learn how to use the Example program, L2_Buzzer_PlayTone and modify it to play
other simple songs and activate the buzzer to produce tones of different frequencies.
Essential program lines and statements needed to program the Buzzer:
Notes:
A class is a user‐defined type that describes what a certain type of object will look like. data 1
A class is a blueprint for creating objects, providing initial values for data (member data ..
variables or attributes), and implementations of behaviour (member functions or methods).
function 1
An object is a single instance of a class. You can create as many as possible objects from function ..
the same class type.
b. Create an object of PassiveBuzzer class and set the buzzer pin. Example as follows:
PassiveBuzzer buz(PassiveBuzzerPin);
/*where buz is the name of an object of the PassiveBuzzer class. Other name can be
used too. Remember to add #define PassiveBuzzerPin 3 at the top of the program*/
c. The object created can then be used to access the member function:
void playTone(long note, long millisecond);
// This has been defined in the PassiveBuzzer class
The line below shows how the object, buz calls the member function to produce a tone
of frequency (value stored in array element, doubleTiger[thisNote] ) for a duration
(value stored in noteDuration variable):
buz.playTone ( doubleTiger[thisNote], noteDuration );
Activities
Follow the steps below
which is a different way of
creating an Arduino
program.
a. Launch visual
studio ‐> click
continue without
code
LAB2
Practice 3A : Create your song with Passive Buzzer (Optional based on
your project needs)
Study the program and modify it to play a different simple song.
Note: You can create a new project under the same "Visual Studio Solution" for this program.
LAB2
Practice 3B : Play Buzzer tone for Traffic Light (Optional based on your
project needs)
Create a new project (new Visual Studio solution), write a program with 1 button (K1, pin 8), 2
LEDs (green led, pin 5 and red led, pin 4) and the passive buzzer (pin 3) such that when the
button is pressed, the normally ON green LED will be turned OFF (after a delay of 1 second)
followed by turning ON the red LED and activate the buzzer for about 4 seconds. You may
program the buzzer to produce a 1‐tone sound. The green LED will be ON again after this
sequence of operations.
digitalWrite(LED_GREEN, LOW);
digitalWrite(LED_RED, HIGH);
else{
digitalWrite(LED_GREEN, );
digitalWrite(LED_RED, );
}
Introduction
The bare 4‐digit 7‐segment displays usually require 12 connection
pins. But the TM1637 IC, a 7‐segment LED driver, is mounted on the
back of the display module, which reduces the total wire to 4. Two pins are required for the
power connections (Vcc and Gnd) and the other two pins are used to control the segments
(CLK pin and DIO data pin)
The CLK pin is connected to pin 10 and DIO pin is connected to pin 11 of the UNO or its
compatible board.
You will learn how to display numbers, which can be displayed in bits, or you can display
integers directly by using the functions provided by the RichShield library.
Essential program lines and statements needed to program the 4‐Digit 7‐Segment
Display:
a. Include library header file:
#include "RichShieldTM1637.h" /* This header file contains the definition of a class
type named as TM1637 */
b. #define CLK 10 //CLK of the TM1637 IC connected to D10 of OPEN‐SMART UNO R3
#define DIO 11 //DIO of the TM1637 IC connected to D11 of OPEN‐SMART UNO R3
e. The disp object created can then be used to access other member functions as listed
below.
Note: The above table shows TM1637 class has 4 display member functions, but each display function
has different parameter list. This is called function overloading.
Activities
Follow the steps as in Activities on Lab Guide page 27 & 28, step a to c, to create a copy of
example program, "L4_Display". Connect your Arduino board and upload the program to
run it.
Study the program and lean how to use the disp.display() function.
// "L4_Display" program
#include "RichShieldTM1637.h"
#define CLK 10 //CLK of the TM1637 IC connected to D10 of OPEN‐SMART UNO R3
#define DIO 11 //DIO of the TM1637 IC connected to D11 of OPEN‐SMART UNO R3
TM1637 disp(CLK,DIO); // create TM1637 class object disp, initialize its pins for clock and data
void setup(){
disp.init(); /*disp object calls TM1637 class member function, init() to initialize the 4‐
Digit 7‐Segment display on the IO shield */
}
void loop(){
int8_t ListDisp[4] = {3,4,5,6}; //declare and initialize array ListDisp with int type elements 3, 4, 5, 6
disp.display(ListDisp); /*disp object calls display () (member function listed in S/N 2 in the
table above) to display the numbers stored in ListDisp array */
delay(1000);
disp.display(‐100); /*disp object calls display () (member function listed in S/N 4 in the
table above) to display integer ‐100 */
delay(1000);
disp.display(256); /*disp object calls display () (member function listed in S/N 4 in the table
above) to display integer 256 */
delay(1000);
disp.display(1.234); /* disp object calls display () (member function listed in S/N 9 in the
table above) to display decimal value 1.234 */
delay(1000);
}
LAB2
Practice 4 : Count‐down display for Traffic Light (Optional based on your
project needs)
Add a Count‐down feature to Practice 3B such that when the red led is turned ON, the digital
display will start counting down from 20 to 0. When the number changes, it will produce a
tone (of say 100ms) and the number will stay for an appropriate delay time (of say 100ms).
After that, the system will go back to normal green light ON condition and sense if the button
is pressed in order to turn on the red led.
Before you start coding, draw the block diagram and flowchart. Implement your program with
user defined function.
Introduction
DHT11 is a single wire digital humidity and temperature sensor, which
gives relative humidity (RH) in percentage and temperature in degree
Celsius.
It can be easily interfaced with any micro‐controller such as Arduino, Raspberry Pi, etc., to
measure humidity and temperature instantaneously.
It provides humidity value in percentage in relative humidity (20 to 80% RH with 5% accuracy)
and temperature values in degree Celsius (0 to 50 °C with a 2‐degree accuracy). The sampling
rate of this sensor is 1 Hz.
This sensor is used in various applications such as measuring humidity and temperature values
in heating, ventilation and air conditioning systems.
Offices, cars, museums, greenhouses and industries use this sensor for measuring humidity
values and as a safety measure.
The data pin of DHT11 on the IO Shield is connected to digital pin 12 of Uno or its compatible
board.
Essential program lines and statements needed to read the temperature and humidity values
with the use of the library functions:
#include "RichShieldDHT.h" /* This header file contains the definition of a class type
named as DHT */
b. Create an object of DHT class. The data pin is set to pin 12 by default in the class
definition.
DHT dht; /* dht is the name of an object of the DHT class. You can use other name as well */
c. Initialize dht in the setup(): dht.begin();
d. The dht object created can then be used to access other member functions as listed
below:
Activities
Follow the steps as in Activities on Lab Guide page 27 & 28, step
a to c, to create a copy of example program, "L11_DHT11" in
RichShield > Advanced folder. A project, named as
"L11_DHT11" will be created in the
"C:\Users\{username}\Documents\Arduino\My Examples"
folder. (It might be in different folder on your Laptop.)
Connect your Arduino board and upload the program to run it.
Study the code, upload to run it and lean how to program the
DHT11 sensor. Use this same project to continue with Practice
5A and Practice 5B.
/* OPEN-SMART Rich Shield Lesson 11: Temperature and humidity measurement and display.through the DHT11 measurement
module to obtain the temperature and humidity, and display on the digital tube. */
#include "RichShieldDHT.h"
#include "RichShieldTM1637.h"
#define CLK 10 //CLK of the TM1637 IC connect to D10 of OPEN-SMART UNO R3
#define DIO 11 //DIO of the TM1637 IC connect to D11 of OPEN-SMART UNO R3
TM1637 disp(CLK,DIO); // create TM1637 class object disp and initialize its pins for clock and data
DHT dht; // create DHT class object dht with data pin set to pin 12 by default in the DHT class
void setup() {
disp.init(); /* disp object calls TM1637 class member function init() to initialize the 4‐Digit 7‐
Segment display on the IO shield */
dht.begin(); /* dht object calls DHT class member function begin() to Initialize the digital
humidity and temperature sensor on the IO shield */
}
void loop() {
// Reading temperature or humidity takes about 250 milliseconds!
// Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
float h = dht.readHumidity(); /* dht object calls DHT class member function readHumidity() to read
humidity value and store it to variable h */
float t = dht.readTemperature(); /*dht object calls DHT class member function readTemperature ()
to read temperature value and store it to variable t */
//Check if the functions above return valid values, if they are nan (not a number), then something went wrong!
if (isnan(t) || isnan(h)){
displayError(); //call user defined function displayError() to display error, its design is at the end of code
}
else{
displayTemperature((int8_t)t); /*call user defined function, displayTemperature() to display variable
t’s value to the 7‐segment display, its design is shown below */
delay(3000); //delay to let the temperature shown for a while
displayHumidity((int8_t)h); /*call user defined function, displayHumidity() to display variable h’s
value to the 7‐segment display, its design is shown below */
delay(2000); //delay to let the humidity shown for a while
}
}
/* Function: Display temperature on 4‐digit 7‐segment display */
void displayTemperature(int8_t temperature){
int8_t temp[4];
if(temperature < 0){
temp[0] = INDEX_NEGATIVE_SIGN;
temperature = abs(temperature);
}
else{
if(temperature < 100) temp[0] = INDEX_BLANK;
else temp[0] = temperature/100;
}
temperature %= 100;
temp[1] = temperature / 10;
temp[2] = temperature % 10;
temp[3] = 12; // 12 represents 'C' for displaying celsius degree symbol.
disp.display(temp);//disp object calls TM1637 class member function to display numbers stored in temp array
}
/* Function: Display humidity on 4‐digit 7‐segment display */
void displayHumidity(int8_t humi){
int8_t temp[4];
if(humi < 100) temp[0] = INDEX_BLANK;
else temp[0] = humi/100;
humi %= 100;
temp[1] = humi / 10;
temp[2] = humi % 10;
temp[3] = 18; //18 represents 'H' just for displaying a symbol for humidity.
disp.display(temp);//disp object calls TM1637 class member function to display numbers stored in temp array
}
/* Function: Display ‘E’ as error on the right most 7‐segment*/
void displayError(){
disp.display(3,14);/*14 is the ASCII value of ‘E’, disp object calls TM1637 class member function to display ‘E’
on the right most 7‐segment*/
}
Optional activity
into one function. Test it out by a call to this new function in the previous program or a new
program.
LAB2
Practice 5A : Drawing Graphs Using @Plot Windows
In this practice, you will learn how to monitor the temperature and humidity values with graphs.
You can instruct Visual Micro to plot a curve by using the @Plot keyword in a breakpoint Action.
To set a breakpoint at a specific line of your code, place your cursor on the gray sidebar on the
left of the code, in this case indicated by the golden star (it was black before any click) at the left
of line 37 and right click to select "Insert Tracepoint" as follows:
{@plot.MyPlotWindow.Humidity h} {@plot.MyPlotWindow.Temperature t}
Both the Humidity graph and the Temperature graph are generated in the same window as
shown in the next page.
Reference: https://www.visualmicro.com/page/User‐Guide.aspx?doc=Multiplot.html
LAB2
Practice 5B : Environmental Control with DHT, Temperature and
Humidity Sensor (Optional based on your project needs)
From the graphs, you would know roughly the range of temperature and humidity values at
the time and place of experimenting with the DHT sensor. Based on the range of values, add in
some control in your program, e.g. if the temperature is >32 °C (by applying some heat on the
DHT), it will turn on the green LED (to simulate turning on a cooling fan) till the temperature
drops to 32 °C or below.
You can also add other controls depending on your application, e.g. when the relative humidity
is > 85, it will turn on the blue led (to simulate turning on a dehumidifier) till the relative
humidity drops to 85 or below.
Before you start coding, draw the block diagram and flowchart. Implement your program with
user defined function.
Introduction
NTC refers to a type of temperature sensor, an NTC thermistor.
NTC stands for "Negative Temperature Coefficient". NTC thermistors are resistors
with a negative temperature coefficient, which means that the resistance decreases
with increasing temperature.
This type of Temperature sensors can be found in every day appliances such as fire
alarms, ovens and refrigerators. They are also used in digital thermometers and in
many automotive applications to measure temperature.
The signal pin of NTC temperature sensor on the IO Shield is connected to analog pin
A1 of Uno or its compatible board.
Essential program lines and statements needed to read the temperature values with
the use of the library functions:
a. Include library header file.
#include "RichShieldNTC.h" //This header file contains definition of a class named as NTC
The temper object created can then be used to access the member function as listed below:
Activities
Follow the steps as in Activities on Lab Guide page 27 & 28, step a to c, to create a copy of
example program, “L7_Temperature_Display” under RichShield > Basic folder.
Study the program, build and upload it. By now, you should be able to plot a graph of
temperature readings for monitoring purpose and/or modify the program to do certain
temperature control based on your program applications.
Introduction
Infrared radiation is a form of light similar to the light we see all around us. The only
difference between IR light and visible light is the frequency and wavelength. Infrared
radiation lies outside the range of visible light, so humans can’t see it:
Because IR is a type of light, IR communication requires a direct line of sight from the
receiver to the transmitter. It can’t transmit through walls or other materials like WiFi or
Bluetooth.
Infrared (IR) communication is a widely used and easy to implement wireless technology
that has many useful applications. The most prominent examples in day to day life are
TV/video remote controls.
A typical infrared communication system requires an IR transmitter and an IR receiver.
The transmitter looks just like a standard LED, except it produces light in the IR spectrum
instead of the visible spectrum.
With an IR receiver connected to Digital pin 2 of UNO (or its compatible board) and a
remote keypad controller with a built‐in IR transmitter, you can do projects involving
remote control of things (e.g. simulating home appliances) connected to the Arduino.
Essential program lines and statements needed to read the temperature values with the
use of the library functions:
#include "RichShieldIRremote.h" /* This header file contains the definition of a class type
named as IRrecv */
b. Define RECV_PIN (IR Receiver Signal Pin) which is connected to pin 2 of UNO (or its
compatible board) and create an object of IRrecv class.
#define RECV_PIN 2
IRrecv IR(RECV_PIN); /* where IR is the name of an object of the IRrecv class and
initialise the IR receiver pin to pin 2. */
The IR object created can then be used to access other member function as listed below:
IRrecv class Functions and usage Descriptions
(where IR is an object of IRrecv class)
IR.enableIRIn(); Start or enable the IR receiver in setup ()
IR.decode(); If no result, it returns 0, otherwise it returns 1.
IR.resume(); Resume to receive again. Run this statement so
that it can receive the next value.
IR.isReleased(); if the button is not released yet, it returns 0;
otherwise (when it is released), it returns 1;
Other useful information:
1. There are 20 keys in the keypad.
2. Each key is encoded and defined in the key code table in the "RichShieldIRremote.h" header file.
/*IR remote control key code table*/
#define KEY_POWER 0x45
#define KEY_MENU 0x47
#define KEY_TEST 0x44
#define KEY_PLUS 0x40
#define KEY_BACK 0x43
#define KEY_PREV 0x07
#define KEY_PLAY 0x15
#define KEY_NEXT 0x09
#define KEY_ZERO 0x16
#define KEY_MINUS 0x19
#define KEY_C 0x0D
#define KEY_ONE 0x0C
#define KEY_TWO 0x18
#define KEY_THREE 0x5E
#define KEY_FOUR 0x08
#define KEY_FIVE 0x1C
#define KEY_SIX 0x5A
#define KEY_SEVEN 0x42
#define KEY_EIGHT 0x52
#define KEY_NINE 0x4A
3. To read the code of the key pressed and received by the IR receiver, simply access the member
variable of the IR object, IR.keycode of unsigned char data type.
Activities
Follow the steps as in Activities on Lab Guide page 27 & 28, step a to c, to create a copy
of example program, “L13_IR_Control_Display” under RichShield > Advanced folder.
Study the program (reproduced below for your reference), build, upload and run the
program.
#include "RichShieldTM1637.h"
#include "RichShieldIRremote.h"
#include "RichShieldPassiveBuzzer.h"
PassiveBuzzer buz(PassiveBuzzerPin); //Create PassiveBuzzer type object buz and set the buzzer pin
void setup(){
disp.init();// disp object calls TM1637 class member function, init() to initialize the 7‐Segment display
IR.enableIRIn(); // IR object calls IRrecv class member function, enableIRIn() to start the receiver
}
void loop(){
if (IR.decode()){ /* IR object calls IRrecv class member function, decode() and check if a valid key
code is detected */
if(IR.isReleased()) /* IR object calls IRrecv class member function, isReleased() and check if it is
not the repeat code for long press */
{
buz.playTone(2500,50);/*every time you press the key, the buzzer will beep 2500Hz for 50ms */
switch(IR.keycode){
case KEY_ZERO: num = 0;break;
case KEY_ONE: num = 1;break;
case KEY_TWO: num = 2;break;
case KEY_THREE: num = 3;break;
case KEY_FOUR: num = 4;break;
case KEY_FIVE: num = 5;break;
case KEY_SIX: num = 6;break;
case KEY_SEVEN: num = 7;break;
case KEY_EIGHT: num = 8;break;
case KEY_NINE: num = 9;break;
case KEY_PLUS: num = num+1;break; /* The number will be increased by 1 if + is pressed on the IR
remote controller and received by IR receiver on the IO shield */
case KEY_MINUS: num = num-1;break;/* The number will be decreased by 1 if – is pressed on the
IR remote controller and received by IR receiver on the IO shield */
default: break;
}
disp.display(num); /* On the 7‐segment display, disp object calls TM1637 class member function
to display the value stored in num variable */
LAB2
Practice 6 : Remote Control to ON/OFF devices (Optional based on your
project needs)
Write a program with a remote control (via the IR transmitter keypad control) to turn on/off
some devices.
For example, press ‘1’ to turn on and ‘2’ to turn off the yellow LED.
Press ‘4’ to turn on and ‘5’ to turn off the blue LED.
Press ‘7’ to turn on and ‘8’ to turn off both LEDs.
Before you start coding, draw the block diagram and flowchart. Implement your program with
user defined function.
• In this lab, you will learn how to write Arduino program to control servo motors using a
servo driver circuit board, PCA9685.
• DoF stands for degrees of freedom, a robotics term that defines the number of axis on a
system.
• 2 DoF Pan-tilt bracket can work as a camera mount to cover a wide range and to capture
seamless time-lapse or panoramic videos in video surveillance applications.
• You can use this bracket to create multi-functional, automated robotic picking systems as
well.
Introduction
Servo Motor
• Usually referred to as simply a “servo”, it provides predictable
and repeatable movement. There are different types of servo
motors, but the ones used in the lab are simple and low-cost
units, which have a rotational range of 180°. We can send a
command to a servo from Arduino to tell it to rotate to a
specific angle.
• Servo motor does not rotate freely and continuously like DC motor. Its rotation is limited to
180⁰ whereas the DC motor rotates continuously. Servo motors are used in robotic arms, legs, or
rudder control systems and toy cars. DC motors are used in fans, car wheels, etc.
• The servo motor is a small and effective motor and it can be used in some applications like
precise position control. The controlling of this motor can be done with a PWM (pulse width
modulator) signal. Within a specified pulse width range, it works such that the longer the pulse
width, the wider the angle of turn.
• A typical servo motor expects to be updated every 20 ms with a pulse between 1 ms and 2 ms,
or in other words, between a 5% and 10% duty cycle on a 50 Hz waveform. With a 1.5 ms pulse,
the servo motor will be at the 90 degree position (i.e. middle position with reference to 0 degree
to 180 degree position).
Activities
5. From vMicro menu, select "Add Library" > "Install Arduino Library From Zip" as shown in the
screen shot and then click the library zipped file downloaded in step 1.
6. After the PCA9685 library has been installed, build and upload to run the "TestServosPCA9685"
program on the Arduino based embedded system.
7. Study and understand the program reproduced below with explanation given in comment lines.
#include <Wire.h>
#include "PCA9685.h"
PCA9685 pwmController(Wire);
PCA9685_ServoEval pwmServo1;
void setup() {
/* Initializes module using default totem-pole driver mode, and default disabled
phase balancer */
pwmController.init();
// Set standard servo frequency of 50Hz (or 20ms servo phase length)
pwmController.setPWMFreqServo();
/* Bring to starting position as defined by the programmer based on how the servos
were mounted and the application */
/* Channel 0 connected to upper Servo. Angle value Limited to -10 degree (minimum
value in this application) due to its movement blocked by the lower bracket/servo
(mechanical design) */
pwmController.setChannelPWM(0, pwmServo1.pwmForAngle(-10));
pwmController.setChannelPWM(1, pwmServo1.pwmForAngle(0));
delay(1000);
}
void loop() {
for (i = 0; i >= -90; i -= 5){ //Slow Turn clockwise (from 0 to -90 degree)
pwmController.setChannelPWM(1, pwmServo1.pwmForAngle(i));
delay(250); //longer delay for Slow turn movement
}
for (i = -90; i <= 0; i += 5){ //Fast Turn anti-clockwise (from -90 to 0 degree)
pwmController.setChannelPWM(1, pwmServo1.pwmForAngle(i));
delay(100); //shorter delay for faster turn movement
}
for (i = -10; i <= 90; i += 5){ //Slow Turn going downward (from -10 to 90 degree
// upper servo (degree of turn is limited (from -10 degree)
pwmController.setChannelPWM(0, pwmServo1.pwmForAngle(i));
delay(250); //longer delay for Slow turn movement
}
for (i = 90; i >= -10; i -= 5){ //Fast Turn raising up (from 90 to -10 degree)
pwmController.setChannelPWM(0, pwmServo1.pwmForAngle(i));//upper servo
delay(100); //shorter delay for faster turn movement
}
}
LAB3
Practice 1 : Servo motor control with Potentiometer (knob) (Optional
based on your project needs)
1. In the same Solution, click File > Add > New project. Create an Arduino Simple Empty Project,
with name, "KnobControlServo" in the same folder as the previous program.
3. Modify the program to use the blue knob on Rich Shield to control the degree of turn for the
lower servo (connected to Channel 1 of PCA9685) such that
i. While the blue knob is turned anti-clockwise, the lower servo will turn anti-clockwise
accordingly.
ii. While the blue knob is turned clockwise, the lower servo will turn clockwise accordingly.
iii. The upper servo (connected to Channel 0 of PCA9685) is fixed at the 90 degree
position throughout the program.
Hints:
#define KNOB_PIN A0
int knobValue, degree;
Before you start coding, draw the block diagram and flowchart. Implement your program with
user defined function.
That is,
a value of fromLow would get mapped to toLow,
a value of fromHigh get mapped to toHigh,
a value in-between (fromLow to fromHigh) get mapped to value in-between (toLow to toHigh).
LAB3
Practice 2 : Video Monitoring via WiFi camera (Optional based on your
project needs)
1. Set up the WiFi camera to link with your phone through an app
1.1 APP Software download/installation for the WiFi camera used in the lab
For IOS system phone, search for "Little Stars" in "App Store" to
install the APP directly.
Step1: Short press the on/off button on the top of the camera. The blue light flashes quickly and
indicates that the camera enters into the WiFi hotspot mode.
Step2: Go to your phone’s "Settings" > "Wireless & network", select the WiFi network starting
with ACCQ or BCCQ in the available WiFi list.
Step3: Click CONNECT to this WiFi. Launch the "Little Stars" APP.
Step4: Click the AP button at the top left corner on the APP page.
You will then be able to watch the live video captured by the
camera through this APP in the phone wirelessly.
Note: This camera can also be used for remote viewing through
the internet, but it is not covered in this lab.
2. Video Monitoring
2.1 With the TestServosPCA9685.ino program running on
the Arduino based embedded system, you’ll be able to
observe the updated live video captured by the rotating
WiFi camera.
2.2 Refer to Lab3_Practice 1, you can control the movement of the servo (and hence, the WiFi
camera), so as to monitor the live video captured by the WiFi camera from different angle
via the knob.
Before you start coding, draw the block diagram and flowchart. Implement your program with
user defined function.
#include "RichShieldPassiveBuzzer.h"
#define PassiveBuzzerPin 3
PassiveBuzzer buz(PassiveBuzzerPin);
//4-digit display /*nitialise 4‐digit
display in setup() */
#include "RichShieldTM1637.h"
#define CLK 10 /*CLK of the TM1637 IC connected to D10 of UNO R3*/
#define DIO 11 /*DIO of the TM1637 IC connected to D11 of UNO R3*/ disp.init();
TM1637 disp(CLK, DIO);
//For NTC
#include "RichShieldNTC.h"
#define NTC_PIN A1 //NTC Temperature Sensor
NTC temper(NTC_PIN);
//For DHT //Initialize DHT11 in setup()
#include "RichShieldDHT.h"
dht.begin();
DHT dht;
C++ used for Arduino is a subset of standard C/C++, with additional functionalities related to
the hardware features of the board. The main differences between Arduino C++ and
standard C++ are in the memory storage. Usually a modern computer has more than 2GB of
RAM, while the Arduino Uno has 2kB (1 million times less). The Arduino also uses 8‐bit
instructions instead of the 32‐bit or 64‐bit ones a computer uses. This will mainly affect the
amount of information you can store in a variable.
C++ defines a number of different data types. Below is a list of the data types commonly
seen in Arduino.
Note: signed variables allow both positive and negative numbers, while unsigned variables
allow only non‐negative values.
Arduino Data Size Value Ranges
Types in
Bytes
boolean 1 true (1) or false (0)
char 1 signed number from ‐128 to 127.
This is most commonly what you see used for general purpose
variables in Arduino example code provided with the Arduino IDE
long 4 signed number from ‐2,147,483,648 to 2,147,483,647
unsigned long, 4 unsigned number from 0 to 4,294,967,295.
uint32_t
The most common usage of this is to store the result of the
millis() function, which returns the number of milliseconds the
current code has been running.
float 4 signed number from ‐3.4028235E38 to 3.4028235E38.
Represents a group of
Predefined
statements performing one
Process/Function
processing task.