Professional Documents
Culture Documents
0)
Experiment Manual
Hello World!
This experiment guide will walk you through installing your software, preparing
your materials for assembly, to transferring your code, to building and running
you Arduino circuit board. You’ll also learn programming and electronics
concepts. Each experiment have activity challenges that you can solve to improve
your tech skills.
The manual is arranged in progressive learning. At the end of the exercise you’ll
be able to build a system with combined parts of each experiments.
------------------------------------------------------------------------------------------------------------------------------------------
DISCUSSION
Arduino Hardware Overview
Arduino Microcontroller Theories and Concepts
Basic Electronics: The Breadboard Overview
Basic Electronics: What is an Electronic Circuit
Arduino Software Overview
Arduino Programming IDE Download, Installation and Setup
Arduino Starter Kit Parts presentation
Experiment Platform Assembly
------------------------------------------------------------------------------------------------------------------------------------------
EXPERIMENT PROJECTS
Experiment 1: Digital Output and Blinking an L.E.D.
Experiment 2: Digital Input and Push Buttons
Experiment 3: Analog Output (PWM) and R.G.B. LED
Experiment 4: Analog Input and Potentiometer
Experiment 5: Light Sensor and LDR (Light Dependent Resistor)
Experiment 6: Creating Sounds and Tones with Piezo Speaker (Buzzer)
Experiment 7: Temperature Sensing with LM35 Temperature Sensor
Experiment 8: Displaying characters & texts with LCD Display
Experiment 9: Driving Servo Motors
Experiment 10: Driving DC Motors
PROJECT CIRCUIT 1: Home Automation – Temperature Controlled Fan
PROJECT CIRCUIT 2: Traffic Light System
In today’s world, technology plays a major role in our daily activities. Anywhere we interact with
technology to help our day move. Technology is composed of moving parts in combination of Hardware
and Software. Tech literacy then is an important skill to have. Understanding how things around us work
will enable us to maximize our resources and create those technology that can help improve our
environment.
Arduino Hardware (Arduino UNO R3) Arduino Software (Arduino C/C++ IDE Programming)
What is Arduino? Arduino is an easy-to-use tool for learning hardware electronics and software
programming. Arduino is a microcontroller (or a small computer board) capable of controlling a variety of
devices like Lights, Servos, Motors, Sensors, wireless devices and many others by using its two main
components, the Arduino board mainly “Arduino UNO R3” (Hardware) and the Arduino Programming
IDE (Software).
We use Arduino because it’s easy to use, easily understood and has well-documented supporting
materials. Arduino also has a very big sharing community where learning is more collaborative and open.
Another reason to use Arduino is it is a platform where you can easily scale a project and the skills of the
user. You can start from the very basic but also can extend to the most advanced application. It can do
something as simple as make an LED blink and as advanced as operate a 3D printer. You can add sensors,
attach a GPS or Cellular modules, the possibilities are endless!
With the Arduino platform you not only learn how to code, but you also learn how to design & build
electronics projects and interface them together.
The Arduino is also a perfect platform for learning STEM/STEAM Skills. It was created with beginner’s in
mind where the language and instructions are easily understood by non-technical people and at the same
time still carries the deep technical component for users who wants to experiment in advanced
applications for hobby projects and even for business and commercial product use.
The picture below shows you an example of a circuit connection assembled in a breadboard. Second
picture on the right shows the bottom of the breadboard in which the sticker is peeled to show which
holes/points are connected and not.
Show in yellow segments below are the way the holes are connected together.
Point 1A to 1E is connected to each other, point 2A to 2E is also connected to each other BUT line 1 and
line 2 are not connected to each other, and so on. On both sides we have blue (-) and red (+) lines where
the 2 lines are not connected to each other but each of them have 1 row of 25 points/holes available.
An example simple circuit shown below is composed of a power source (battery positive pin), ground
source (battery ground pin), switch (controls when to close or open the loop), LED (produces light) and a
resistor which controls the amount of current flowing in the circuit in order to avoid over voltage or over
current for the LED. The circuit allows current to flow from the battery, to the switch when closed, to the
LED and to the resistor. In this simple circuit the LED and the Resistor can also be interchanged.
Terms: Schematic Diagram – a schematic diagram is a graphical representation or drawing of the components
and connections in an electronic circuit.
A. Verify – Checks your code for errors and compiles it into a code file. This will also catch and
highlight any code line with errors. (One of the commonly used commands).
B. Coding Tools and Settings – other commands used for navigating and setting up the Arduino
IDE.
C. Upload – Uploads and sends the compiled code file into the Arduino board. When Uploading,
the Arduino board’s Tx and Rx LED’s will be blinking. (One of the commonly used commands).
D. Save – command to save any change to the Arduino file.
E. Serial Monitor – Opens a separate window for debugging or showing of data that is transmitting
into and out to the Arduino. (One of the commonly used commands).
F. Code Area – create and edit all your Arduino codes in this area.
G. Board type and COM Port Status – this area shows the name of the board used and the
computer COM port number it is connected to.
H. Debug Status window – shows information of any errors in the sketch.
I. Compile and Upload Status – displays Arduino code compile and upload status including error
messages.
Sketch – This is another term for an Arduino code or program, called “sketch” or Arduino Sketch.
The Arduino programming language can be divided in three main parts: structure, values (variables and
constants), and functions.
Structure (structure is the main building blocks followed to have of a working Arduino code)
The Arduino program is structured into two basic parts: the void setup() {} and void loop() {}
Some of the example values and data’s are: int (integer number), float (numbers with decimals), char
(letters or characters), String (a word) and many others.
Functions (are commands used to control the Arduino board and perform multiple computations)
1. Download the Arduino Software IDE (Integrated Development Environment) by opening your Internet
browser and going to https://www.arduino.cc/en/Main/Software
The Arduino Software IDE is the place to write and edit your Arduino C/C++ codes to do specific task that
you like. This software is free!
Select the installer you need. We will use the Windows environment for this guide. If you are using Mac
or Linux click on the other option instead. If you do not have access to administrative rights to your
computer when installing, click on the ZIP file for non admin install. If you have administrative rights, click
Windows installer.
Find your downloaded Installer file and double click to install. Choose to Proceed/Install/Agree/Allow for
any pop-ups during the installation. After Complete installation, find your Arduino program launcher icon
in the Desktop or in the Windows: Program Files or (x86) folder(s).
If you downloaded the non admin install zip file, Unzip/Extract the arduino-1.X.X folder and place it to
your local disk of choice (ideally in C: drive). Open and find the arduino.exe application file and launch the
software.
If you are having trouble downloading and installing the hardware or software, go to
https://www.arduino.cc/en/Guide/Windows for step by step and troubleshooting guide.
3. (In this step we will let the Arduino Software IDE recognize and connect to the Arduino UNO R3 Hardware board
in order to transfer and upload the codes to board).
Connect your Arduino UNO R3 board to your computer or laptop using the included USB cable. Windows
OS should recognize and automatically install the Arduino board chip drivers to the Windows OS. A
notification in the taskbar will show installation process and number of the COMXX Port. Take note of the
COMXX port number as this will be used for uploading the Arduino codes.
If you are unsure if your board drivers were installed, you may go and check this guide Installing Arduino
on Windows or Arduino Drive Installation for troubleshooting.
4. (Communicate the Arduino Software IDE and Arduino UNO R3 Hardware board and test upload).
Arduino UNO R3 USB Cable (A to B) Breadboard (half- LED – Red (5mm) LED – Green LED –
size, 400 points) (5mm) Orange/Yellow
(5mm)
Resistor (330 Resistor (1k Resistor (10k Push Button RGB LED Potentiometer
ohms ohms) ohms) Tactile Switch (common cathode) (10k ohms)
(orange/orange/brown) (brown/black/red) (brown/black/orange) (red/green/blue)
(SPDT)
DC Motor (Basic Hobby Transistor (NPN) – 2N2222 Base Holder plate for
Motor) (2N2222 markings) Diode (Signal diode) Arduino and Breadboard
(sold separately)
Overview
When starting in electronics, the Blinking LED circuit is a perfect beginner’s build. The Blinking LED circuit
shows you basic components and structure of an electronic circuit. Blinking an LED is like a “Hello World!”
in programming but in hardware version. This circuit will be used to demonstrate basic concepts and
structure of an Arduino C/C++ Blinking LED program code. This will also explain the concept of Input and
Output (I/O) in an electronic signal as well as HIGH/LOW functionality.
Learning objectives
Resistor – an electronic component which limits the passage of a current and/or voltage. Resistance, is
the measure as to how a material opposes electric current. The unit for resistance is ohms, denoted as Ω.
A lot of electronics component have difference voltage and current requirements for power and data
A resistor is denoted by color coding. Below is an example of a 330 ohm resistor which has the colors of
Orange (number 3), Orange (number 3), Brown (number 1, where 3rd color is the multiplier, or how many
zeroes to put next). In this case Brown is equal to 1, which means just put one number Zero). The last color
band is for tolerance. In most cases we will use common tolerance of Gold which represents 5% tolerance.
Another example, instead of writing 10,000 Ohms, you may write 10k Ohm (where “k” represents
thousands (1,000’s)).
Voltage, also known as electric pressure is the electric potential difference between two points. The unit
for voltage is volts, denoted as V.
Current is the amount of flow of electric charge, or the amount of electrons flowing in a wire. The unit for
current is amperes, denoted as A.
Resistance is the measure as to how a material opposes electric current. The unit for resistance is ohms,
denoted as Ω.
The relationship of voltage, current and resistance is explained in Ohm’s Law, which states that current is
directly proportional to voltage, and inversely proportional to resistance. In a mathematical equation:
𝑉
𝐼=
𝑅
In the given circuit diagram above, let’s assume that the VCC = 5V. The total current passing through the
system is:
5
𝐼=
220
𝐼 = 0.0227 𝐴 𝑜𝑟 22.7 𝑚𝐴
The design above is a typical circuit for a lighting LED. An LED will need a current (I) of about 10mA to
25mA to light up. In our circuit lighting up the LED, we will need a resistor from about 220ohm up to about
1k Ohm (in our experiment we will use 330 ohm). The higher the current (lower resistor value) the brighter
the LED lights up.
Getting the current, voltage or resistance is useful for designing circuits, as different components have
different specifications or requirements for voltage and current. Improper designs can cause the
component to behave improperly, get damaged or even destroyed.
Longer pin
Figure A Figure B
Construct the Circuit in Figure A, your circuit would look something as shown in Figure B.
Circuit Diagram or Wiring Diagram – a representation drawing to show how the connection of each components
will go. The Circuit Diagram is useful tool to trace the connection and to also trace your circuit for
troubleshooting purposes. Figure 1A shows you an example of a Circuit Diagram while Figure 1B shows the
equivalent actual circuit.
In this experiment we built an example application of turning ON and turning OFF of a light source in this
case an L.E.D. Start by connecting a wire from one of the Digital pins from the Arduino, Digital PIN 13. The
other end of the wire goes to one end of the 330 Ohm resistor. The other end of the resistor connects to
the positive terminal of the Red L.E.D. (long leg). Next, the other end of the LED (short leg) connects to
another wire (Black), the other end of the Black wire goes to the GND pin of the Arduino. Here we created
a loop of electricity going from the Arduino Digital PIN 13 to the Ground.
Our Arduino Hardware circuit is ready, now let’s program our blinking LED Arduino code!
2) Type the Arduino Code below to your Arduino IDE. (Or copy and paste it to the Arduino IDE)
/*
Blink and DIGITAL Output
Turns on an LED on for one second, then off for one second, repeatedly.
*/
// the setup function runs once when you press reset or power the board
void setup() {
// initialize digital pin 13 as an output.
pinMode(ledPin, OUTPUT);
}
Your Arduino IDE window with the Arduino LED Blink code
Programming concepts
pinMode(pin, mode); - Configures the specified pin to behave either as an input or an output.
digitalWrite(pin, value); - Write a HIGH or a LOW value to a digital pin. HIGH indicates the pin is equal
to VCC (usually 5V), LOW means 0V or Ground.
int – int stands for integer. In programming, the integer variable can store values from -32,768 up to
+32,767
setup() – this function is standard for all Arduino Code. All Arduino program starts with the setup ()
where a comman placed inside this code function is executed or run once for example if you want to
just declare a pin and other one-time commands.
loop() - this command is standard for all Arduino Code. All Arduino program will have a loop()
command, in this place all the activities that you want to repeat or do forever will be placed inside
this command function (example: repeatedly turn ON and turn ON an LED)
HIGH – used together with digitalWrite(), this text parameter declares something into a HIGH
type/value configuration. With a VCC or power source 5V, HIGH is equal to 5V.
LOW – used together with digitalWrite(), this text parameter declares something into a LOW
type/value configuration. In power source, LOW is equal to 0V or Ground.
delay() – command used to halt/wait a code to execute in a given declared value (ex: 1000ms or 1
second) means delaying or halting the code for 1 second.
; – used for separating two statements or two line of codes.
{} – curly braces are used in housing constructs. These includes functions, conditional statements and
loops
= – known as the equal sign, it is used in assigning a value (data) to a variable
// – creates single line comment
/* */ – creates multiline comment. Any text that inside this two slash-and-asterisk is a comment, and
is not part of the code to execute.
Code Sequence
1. Turn the LED On by giving a HIGH signal to Arduino Digital PIN 13 (D13).
2. Wait 1 second (1000 milliseconds).
3. Turn the LED Off by giving a LOW signal to Arduino Digital PIN 13 (D13).
4. Wait 1 second (1000 milliseconds).
5. Repeat from the start.
Code Explained
The first part of the code is sort of an introduction line. Most Arduino code and in programming practice
it is recommended to describe your code and its information (example: what is it about, version,
creator’s name, etc.). Here we used the code syntax /* */ to put a long text description.
/*
Blink and DIGITAL Output
Turns on an LED on for one second, then off for one second, repeatedly.
*/
In the third part is the code function called setup(). A code function is a grouping of codes grouped
together for easier calling and execution. All functions start with void (name of function), followed by
curly brackets {}.
The setup() code function is one of the two default functions created every time a new Arduino Sketch is
created. Its primary function is to run “one-time” the codes inside it before running the next function,
which is the loop() function. Here in the setup() function we can do pin assignments and initializations,
starting serial communication and any other command that will run once.
In the fourth part is another code function called loop(). The loop is the other function present at default
for every Arduino code. Here you put the code that runs over and over. As shown below the HIGH and
LOW change of the signal which represents the ON and OFF of the LED is inside this group function.
// the loop function runs over and over again forever
void loop() {
digitalWrite(ledPin, HIGH); // turn the LED on (HIGH is the voltage level)
delay(1000); // wait for a second
digitalWrite(ledPin, LOW); // turn the LED off by making the voltage LOW
delay(1000); // wait for a second
}
Activity Challenge
a) Try changing the “delay” value in your code, what happens as you increase or decrease the
value?
b) Let’s try using a different pin of the Arduino, try D8 (Digital Pin 8). Move the wire from the D13
and connect it to the D8, change the part of the code from the LED from 13 into 8, on which part
of the code?
Overview
In this experiment we will learn about Digital Input and using an input device: Push Button Switch. Here
we will learn how to turn a single LED on or off with a button switch. I/O port refers to INPUT and OUTPUT
port. We will use the input function of Arduino UNO I/O port to read the output of the external device.
And we will let you have a basic understanding about the I/O function through this experiment in which
we will use a button and an LED to realize the combination of input and output.
Learning objectives
Tactile Switch
LED (Red) Resistor (330 ohms) (2 units) Resistor (10k ohms)
(1 unit) (1 unit) (brown/black/orange)
The push button leads or pins are not perfectly aligned as squared, it is rectangular when you view it at
the bottom. Show below is the orientation of the pins. 2 pins inside the yellow mark are horizontally
connected but the two are not vertically connected.
A Resistor (usually with 10k Ohm value) is connected to a button switch to stabilize its state. The
purpose of this resistor is to pull the electrical signal to a clean HIGH or LOW signal. Absence of a resistor
in a push button circuit will result to a buggy signal (the system will read different kinds of input voltages
instead of just a 5V (High) or 0V (Low)). There are two circuit configurations: the pull-down network and
the pull-up network.
The pull-down network (left image) pulls the OUTPUT down (to the Ground/0 Volts/LOW) when the tactile
switch S1 is not pressed. The OUTPUT turns high (VCC/5 Volts/HIGH) when the tactile switch S1 is pressed.
On the other hand, the pull-up network (right image), pulls the OUTPUT up when the tactile switch is not
pressed. The output turns low then the tactile switch is pressed.
Figure A Figure B
Construct the Circuit in Figure A, your circuit would look something as shown in Figure B.
New Concept! Common Ground – Common grounding is creating a common Ground point/line in a circuit. In
the breadboard it uses the outer columns (with a Negative (–) sign) to be connected to the ground of the
Arduino board. This makes is easier for components needing ground connections to be connected. You can
also use the same concept when connecting 5V supply or 3.3V supply.
In this experiment, we create a circuit that turns ON and OFF a light source. In this case, the light source
is the LED, while the push button are the light switches.
Connect the positive terminal of the LED (longer leg) to the 330 Ohm resistor, the other leg of the LED is
connected to common GND line from the Arduino’s GND pin. Connect one pair of legs of the pushbutton
to a leg of the 10k Ohm resistor, while the other pair of legs to the common Ground. Do the same for the
other pushbutton. Connect the other leg of the 10k Ohm resistor to the Common 5V line from the Arduino
5V pin, the other end of the 330 Ohm goes to the Arduino Digital Pin 3. Finally, connect the push button’s
Output pins (between the legs of the pushbutton with the resistor) to Digital pins 8 and 9 of the Arduino
Uno
2) Type the Arduino Code below to your Arduino IDE. (Or copy and paste it to the Arduino IDE)
/*
Buttons and DIGITAL Inputs
*/
void setup() {
pinMode(ledRedPin, OUTPUT); // set Arduino pin 3 as output for LED
pinMode(buttonLeftPin, INPUT); // set Left button as a Digital Input
pinMode(buttonRightPin, INPUT); // set Right button as a Digital Input
}
void loop() {
if (digitalRead(buttonLeftPin) == LOW) // if Left Button is Pressed
{
digitalWrite(ledRedPin, HIGH); // turn ON the LED
}
if (digitalRead(buttonRightPin) == LOW) // if Right Button is Pressed
{
digitalWrite(ledRedPin, LOW); // tun OFF the LED
}
}
3) Click Verify button to review code for errors. If the code has no errors and missing commands a message on
the window below will display “Done Compiling” this means your code is ready to be uploaded
into the Arduino microcontroller board.
4) Click Upload button to upload the Arduino Code to the Arduino microcontroller board.
Press the Left button, LED in On! Press the Right Button pressed, LED is Off
Code Sequence
1. Check buttonLeftPin state.
2. If buttonLeftPin is pressed, turn the LED ON by giving a HIGH signal to Arduino Digital PIN 13
(D13). If buttonLeftPin is not pressed, no changes are made.
Code Explained
Here we assign name “variables” for our Arduino PIN assignments. We use the variable ledRedPin to be
equal to integer number 3, which serves as the Arduino Digital PIN 3 and so on for the other 2 variables.
In this part, pinMode() command is used to declare whether the digital pin variable is an input or output.
The ledRedPin is an output since we output a voltage to turn ON and LED light. Both buttonLeftPin and
buttonRightPin are input since the push button sends an input signal into the Arduino when it is pressed.
Declaring and initializing these pins to Input or Output requires only at once, hence it is placed in the
setup() function.
void setup() {
pinMode(ledRedPin, OUTPUT); // set Arduino pin 3 as output for LED
pinMode(buttonLeftPin, INPUT); // set Left button as a Digital Input
pinMode(buttonRightPin, INPUT); // set Right button as a Digital Input
}
In the loop function, there are 3 things that are prevalent, the use of “IF” statement, digitalRead() and
digitalWrite(). Let’s discuss first digitalRead() and digitalWrite().
digitalRead() and digitalWrite() are commands used in manipulating the digital pins of the Arduino board.
digitalRead() is reading the status of any connected component to the pin. The value being read could
only be a HIGH or a LOW, as only digital signals pass through these pins. digitalWrite(), on the other hand,
“writes” or sends out digital signal. Again, the signal sent will only be a HIGH or a LOW.
“IF” statements are a part of a category of statements used in programming in executing a particular
response for a particular condition, which is the conditional statement. A conditional statement is a set of
codes that only run when a certain condition is achieved. To take the code as an example, the
digitalRead(buttonLeftPin) == LOW is a condition or a parameter. If this is true, meaning that the left
button is pressed, the code inside the curly brackets are executed. In this case, the
digitalWrite(ledRedPin, HIGH) is executed.
void loop() {
if (digitalRead(buttonLeftPin) == LOW) // if Left Button is Pressed
{
digitalWrite(ledRedPin, HIGH); // turn ON the LED
}
if (digitalRead(buttonRightPin) == LOW) // if Right Button is Pressed
{
Activity Challenge
a) Add additional LED’s and Buttons to create a Push Button controlled Traffic Light Switch.
b) Let’s try using a different pin on the Arduino for the LED and the Push buttons, try D5, D6 and
D7. Move the LED wire from the D3 and connect it to the D7, change the part of the code from
the LED from 3 into 7, and change the code on the buttons to change to D5 and D6, on which
part of the code?
Overview
In previous experiments we dealt with digital signals in discrete values. In this Experiment we will learn
about Analog signals and use it to control an RGB (Red-Green-Blue) LED with an Arduino by using the
Analog Output commands. We will utilize the analogWrite() programming command to adjust the color
of the LED by adjusting the values of the 3 colors of the RGB color combinations. We will also discuss about
PWM, a signal configuration control that adjusts the output value that an Arduino pin produces.
Learning objectives
RGB LED
Breadboard Connecting wires
(1 unit)
(1 unit)
R.G.B. LED – (short for Red-Green-Blue LED) is an electronic component which houses 3 different color of
lights (Red/Green/Blue) in one package. This RGB LED is responsible for producing different kinds of colors
in TV screens, cellphones and street lights. The way it works is that the value of the Red, Green and Blue
are adjusted lower or higher in order to produce the kind of color that you will output.
For example, a full bright Red, Green and Blue combined will produce a bright White color. While a
completely off Red, Green and Blue combined will produce a Black or dark color.
Pulse Width Modulation, or PWM, is a technique for getting analog results with digital means. Digital
control is used to create a square wave, a signal switched between on and off. This on-off pattern can
simulate voltages in between full on (5 Volts) and off (0 Volts) by changing the portion of the time the
signal spends on versus the time that the signal spends off. The duration of "on time" is called the pulse
width. To get varying analog values, you change, or modulate, that pulse width. If you repeat this on-off
pattern fast enough with an LED for example, the result is as if the signal is a steady voltage between 0
and 5v controlling the brightness of the LED.
In the image below, the green lines represent a regular time period. This duration or period is the inverse
of the PWM frequency. In other words, with Arduino's PWM frequency at about 500Hz, the green lines
would measure 2 milliseconds each. A call to analogWrite() is on a scale of 0 - 255, such that
analogWrite(255) requests a 100% duty cycle (always on), and analogWrite(127) is a 50% duty cycle (on
half the time) for example.
Reference: https://www.arduino.cc/en/Tutorial/PWM
Figure A Figure B
Construct the Circuit in Figure A, your circuit would look something as shown in Figure B.
In this experiment, we made a circuit that will light up the RGB LED in different colors: red, green, blue,
yellow, purple, and white. To do this, connect the common cathode pin of the RGB LED (second lead to
the flat edge of the RGB LED, it is also the longest leg out of the 4 legs) to GND of the Arduino board using
a black connecting wire. Connect 330 Ω resistors to the other 3 pins of the RGB LEDs. To the unconnected
leads of these resistors, using colored wires connect them in the following manner: the lead with the flat
edge of the RGB LED should be connected to digital pin 11 (Red wire), the third lead to digital pin10 (Green
wire) and the last lead to digital pin 9 (Blue wire).
2) Type the Arduino Code below to your Arduino IDE. (Or copy and paste it to the Arduino IDE)
/*
RGB LED and Analog Outputs
*/
void setup()
{
pinMode(redPin, OUTPUT);
pinMode(greenPin, OUTPUT);
pinMode(bluePin, OUTPUT);
}
void loop()
{
setColor(255, 0, 0); // red
delay(1000);
setColor(0, 255, 0); // green
delay(1000);
setColor(0, 0, 255); // blue
delay(1000);
setColor(255, 255, 0); // yellow
delay(1000);
setColor(80, 0, 80); // purple
delay(1000);
setColor(255, 255, 255); // white
delay(1000);
}
3) Click Verify button to review code for errors. If the code has no errors and missing commands a message on
the window below will display “Done Compiling” this means your code is ready to be uploaded
into the Arduino microcontroller board.
4) Click Upload button to upload the Arduino Code to the Arduino microcontroller board.
Programming concept
Function - A block of code that executes a specific task. It is also a type of procedure or routine,
housing lines of code to perform a desired operation. In our example code we create a separate
function setColor() to group the assigning of different colors.
analogWrite() – this function/command sends an output signal equal to the value inside. This value is
translated as a voltage when received by the external component. For PWM pins, the maximum
allowable value is 255, and 1023 for analog pins. The voltage equivalent for these values is 5.0V for
the Arduino Uno board.
Code Sequence
1. Make the RGB LED emit red color by sending a value of 255,0,0 to the redPin, greenPin and
bluePin respectively
2. Wait for 1 second
3. Make the RGB LED emit green color by sending a value of 0,255,0 to the redPin, greenPin and
bluePin respectively
4. Wait for 1 second
5. Make the RGB LED emit blue color by sending a value of 0,0,255 to the redPin, greenPin and
bluePin respectively
Add a multiline comment using /* */ pair, where you put the comments between the * *. Comments are
used to create notes inside the code, add titles, or credit people involved. They are in not included in the
execution of the program.
/*
RGB LED and Analog Outputs
*/
After the setup() function, we are introduced into new codes: analogWrite and setColor. analogWrite()
is a native command of the Arduino environment, meaning it exists by default in the Arduino programming
commands, while the setColor is a customized function coded by us. analogWrite() allows us to write
values not just HIGH or LOW into the pins of the Arduino, but any value supported by the said pin. Analog
pins can support values from 0 to 1023, while digital pins with PWM capability can support values from 0
to 255. To check which digital pins support PWM, check for the (~) symbol beside the pin number. This
means that for the code, 0 is the minimum value, or the lowest state, while 255 is the maximum value, or
the highest state.
Customized functions are a set of codes that we want to group for easier coding. This means that the
number of lines we need to add into the program is reduced, decreasing memory space needed and
making our coding easier to trace errors or changes. In creating your function, you can declare or not
declare parameters.
The parameters are int red, int green and int blue. These parameters are then used inside the function
for processing or executing any command. In this case, analogWrite() writes the values for the RGB pins
they are assigned with.
The other method of creating function is by not using parameters. An example of this are the setup() and
loop() functions. No parameters are declared in these functions, which means that you do not need to
input parameters in your main code or in any other functions when calling this type of function.
Finally, the loop() function houses our codes that we need to repeat indefinitely until the board is off or
reset. You can see that the setColor() function has values inside, with the first call of it having values of
255,0,0. This means that the red, green and blue variables in the setColor() function have 255,0,0 values
respectively. This translates to that the redPin, greenPin and bluePin will have values of 255, 0, 0
respectively through analogWrite() code.
void loop()
{
setColor(255, 0, 0); // red
delay(1000);
setColor(0, 255, 0); // green
delay(1000);
setColor(0, 0, 255); // blue
delay(1000);
setColor(255, 255, 0); // yellow
delay(1000);
setColor(80, 0, 80); // purple
delay(1000);
setColor(255, 255, 255); // white
delay(1000);
}
Activity Challenge
a) Try changing the “delay” value in your code, what happens as you increase or decrease the
value?
b) Let’s try using a different PWM pin of the Arduino, pins with (~) markings. Move the wire from
the PWM pins, what pins did you use? What happens if you don’t use a non-PWM pin?
c) Go and try different function name, change the setColor() name or add new code function to
change and set the RGB Color that you like.
Overview
In the previous experiment we processed an outgoing varying Analog signal. In this experiment we will
tackle an incoming Analog signal towards the Arduino and read this analog signal and process it.
Another form of signal in electronics are analog signals. These are signals that are not limited to two
possible states or values, rather analog signals are a range of continuous values. In this lesson, we will
discuss using the Analog pins of the Arduino to read some components varying signals. We will use the
potentiometer as our component to read, and an LED to blink according to the value of the potentiometer.
Learning objectives
Mode of operation: turning the shaft of the potentiometer, changes the amount of resistance on either
side of the wiper which is connected to the center pin of the potentiometer. This changes the relative
"closeness" of that pin to 5 volts and ground, giving us a different analog input. When the shaft is turned
all the way in one direction, there are 0 volts going to the pin, and we read 0. When the shaft is turned all
the way in the other direction, there are 5 volts going to the pin and we read 1023. In between,
analogRead() returns a number between 0 and 1023 that is proportional to the amount of voltage being
applied to the pin. To translate this value to actual voltage, you have to do the operation shown below:
5
𝑉𝑎𝑐𝑡𝑢𝑎𝑙 = 𝑆𝑒𝑟𝑖𝑎𝑙 𝑣𝑎𝑙𝑢𝑒 ∗
1023
Where Vactual is the actual voltage value and Serial value is the value obtained from analogRead().
Figure A Figure B
Construct the Circuit in Figure A. Your circuit would look as shown in Figure B.
In this experiment, we will read the value of the potentiometer when the knob is rotated. Using colored
wires, connect the center lead of the potentiometer to A0 pin of the Arduino board. Connect one
unconnected leg of the potentiometer to the 5V pin, while the other leg to GND of the Arduino.
2) Type the Arduino Code below to your Arduino IDE. (Or copy and paste it to the Arduino IDE)
/*
Potentiometer and Analog Inputs
*/
void setup(){
Serial.begin(9600); // set baudrate to use in the Serial Monitor
}
void loop(){
// analogRead translates the potentiometer voltage from GND 0V to VCC 5V
// into 0 to 1023 and assign it to readInput variable
readInput = analogRead(potentiometerPin);
// print the value to the Serial Monitor to see the reading
Serial.println(readInput);
delay(200);
}
3) Click Verify button to review code for errors. If the code has no errors and missing commands a message on
the window below will display “Done Compiling” this means your code is ready to be uploaded
into the Arduino microcontroller board.
4) Click Upload button to upload the Arduino Code to the Arduino microcontroller board. Open Serial
Monitor, and set baud rate to "9600, BOTH NL & CR”.
Arduino Serial Monitor – A tool built in to the Arduino IDE allowing sending and receiving serial data to and
from a connected board. The Arduino Serial Monitor can be used to show the data as the code is executed.
The kinds of data to show will depend on the coder to which part this monitoring programming command will
be inserted on the code.
analogRead(analogPin) – another built-in command of the Arduino. This reads the incoming analog
voltage signal connected to the analogPin Arduino pin assigned. The output of this function ranges
from 0-1023 for Arduino Uno.
Serial - process or sending of a data one bit at a time. Data processed together is called Parallel.
Serial.begin(9600) – Sets the data rate in bits per second (baud) for serial data transmission. For
communicating with the computer, use one of these rates: 300, 600, 1200, 2400, 4800, 9600, 14400,
19200, 28800, 38400, 57600, or 115200. In most examples, 9600 will be used.
Serial.println() - Prints data to the serial port as human-readable ASCII text followed by a carriage
return character (ASCII 13, or '\r') and a newline character (ASCII 10, or '\n'). This command takes the
same forms as Serial.print() command.
Code Explained
In the code above, there are three new lines: Serial.begin, analogRead() and Serial.println().
Serial.begin() allows us to start using the Serial Monitor to display and monitor responses using serial
communication. This is just limited to devices using the Serial.
void setup(){
Serial.begin(9600); // set baudrate to use in the Serial Monitor
}
analogRead() is used when using the analog pins as input. Unlike digital pins, we do not need to use
pinMode() to set the analog pin as an input or an output. That’s why there is no pinMode() in the setup()
function as it is not needed. Like the digitalRead() syntax, the analogRead() syntax reads the value of the
analog pin. This value is in the range of 0-1023 as this is the limitation of the hardware for the Arduino
Uno for the analog pins. This value is then stored in a variable, which is readInput for the given code.
Serial.println() is used to send data to the serial port as human-readable value, which is ASCII text. In the
code, Serial.println() is used to print the value of readInput into the Serial Monitor.
void loop(){
// analogRead translates the potentiometer voltage from GND 0V to VCC 5V
// into 0 to 1023 and assign it to readInput variable
readInput = analogRead(potentiometerPin);
// print the value to the Serial Monitor to see the reading
Serial.println(readInput);
delay(200);
}
Activity Challenge
a) Try changing the “delay” value in your code, what happens as you increase or decrease the
value?
b) Try using a different Analog pin, what pin is allowed to use? Move the old pin to the new pin
assigned and change the corresponding changes in the code.
c) How about interchange the Red and Black wire of the potentiometer, what happens to the
value? How it is different or related to the first configuration?
Overview
In the previous experiments, we’ve learned how to read inputs connected in an Arduino pin from a
mechanical component triggered by human interaction, as well as responding to its corresponding results.
In this experiment, we will discuss on another form of inputs commonly used together with Arduino
boards: Sensors. Sensors can be triggered or used with or without human interaction. In this section we
will also discover why sensors are needed in automated systems, and we will create a simple circuit using
a simple light sensor: the light-dependent resistor (LDR).
Learning objectives
The resistance of the photoresistor changes with incident light intensity. If the incident light intensity is
high, the resistance decreases; if the incident light intensity is low, the resistance increases. In this
experiment the LDR will compare two different light intensities (dark or bright environment) and use an
LED light source to react (ON or OFF) as the state changes.
Fig. 1A Fig. 1B
Construct the Circuit in Figure A. Your circuit would look as shown in Figure B.
In this experiment, we create a dark-activated LED, with conditions that when the environment is dark,
the LED light source switches on. If it is environment is bright, the LED switches off. To make this circuit,
connect one leg of the 10k Ohm resistor to the common 5V source from the pin of the Arduino (red wire),
while the other lead connects to the one leg of light-dependent resistor, with in the same hole line a
(green) wire is connect to analog pin A0 of the Arduino Uno. Using (black) wire connect the unconnected
lead of the LDR to the common GND pin from the Arduino Uno, this common ground together with the
cathode of the LED. Connect the anode of the LED to the 330 Ω resistor, while the other lead pin of the
330 Ω resistor goes to digital pin 12 of the Arduino Uno.
2) Type the Arduino Code below to your Arduino IDE. (Or copy and paste it to the Arduino IDE)
/*
LDR or Photocell/Photoresistor (light sensor)
*/
void setup()
{
Serial.begin(9600); //Begin serial communcation
pinMode(ledPin, OUTPUT); // initialize the "ledPin (arduino pin 12) as an output.
}
// Compare light and dark conditions to turn ON and OFF the LED
if (lightValue > 500) { // Room is Dark or low light
digitalWrite(ledPin, HIGH); // LED is On
}
else { // Room is Bright or bright light
digitalWrite(ledPin, LOW); // LED is Off
}
delay(10); //short delay for faster response to light.
}
3) Click Verify button to review code for errors. If the code has no errors and missing commands a message on
the window below will display “Done Compiling” this means your code is ready to be uploaded
into the Arduino microcontroller board.
4) Click Upload button to upload the Arduino Code to the Arduino microcontroller board.
When the LDR is exposed to good amount of light source (room with lights On), the Red LED light is Off.
Covering the LDR light sensor or turning off the source of light in the room turns ON the Red LED light.
Operators (Mathematical) – these are symbols that behave like functions, but differ in syntax or
form. This includes +, -, *, /, =, >, <, !.
> - An operator that stands for “greater than” when the value on the open-left side is bigger/higher
than on the pointed-right side. Say that an argument, x > y exists, means that “x is greater than y”.
Code Explained
Just like from previous experiment we want to view the Analog values of our Analog component, we
initialize and call the Serial.begin() command to use the Serial Monitor feature.
Serial.begin(9600); //Begin serial communcation
Using the analogRead() command, the change of resistance in the LDR is obtained by reading the value
in Arduino Analog pin A0 (pin “0” is declared in the beginning of the code as variable lightPin). The value
read is then stored to another variable named lightValue. It is then printed in the Serial Monitor using
the Serial.println() command.
lightValue = analogRead(lightPin);
Serial.println(lightValue);
This value is then used in the IF-ELSE statement. If lightValue is greater than 500, where the Room is
Dark or low light, the ledPIN is HIGH which turns On the Red LED. Else, if the lightValue is lesser than
500, where the Room is bright or the room has bright lights, the ledPIN is LOW which turns Off the LED.
if (lightValue > 500) { // Room is Dark or low light
digitalWrite(ledPin, HIGH); // LED is On
}
else { // Room is Bright or bright light
digitalWrite(ledPin, LOW); // LED is Off
}
delay(10); //short delay for faster response to light.
}
Activity Challenge
a) Try using the different Arduino analog input pins, what changes in your code should be made?
b) Add a second and third LED (yellow and green) assign them in three different value ranges with
the Red LED. 0 to 340 for Red, 340 to 680 for Yellow and 680 to 1023 for Green. What changes
to be made in your code and circuit?
Overview
Sounds are generally used as notifications, alarms or expressions of art. In this lesson, we will be
experimenting how to use a Piezo Speaker (tone adjustable buzzer) to make different tones and
interfacing it with the Arduino environment. We will be using a programming data type called Array
which helps organize a code in a more efficient and structured way.
Learning objectives
The variable mySensVals, have 5 numbers in it, which are 2, 4, -8, 3 and 2. In previous experiments, you
can observe that variables have only a single number stored at a given time. However, arrays make it
possible to store multiple numbers, letters or variables at any given time. This allows for using a single
variable for storing different values instead of multiple variables for storing multiple values.
Arrays are zero indexed, that is, referring to the array initialization above mySensVals, the first element
of the array is at index 0, hence
mySensVals[0] == 2, mySensVals[1] == 4, and so forth.
Variable type sets what type of variable will be used. This could be an integer, double, character, etc. Array
size sets the size of the array. It also sets how many elements can be housed inside the variable. For the
example above, the array can house up to 6 elements. The elements are the data or information found
within the variable.
Tone – Tone is a sound function that have changes of pitch, sound frequencies, amplitude or volume of
sound to generate rhythms of sounds. A tone can be represented with a sinusoidal waves below.
Tone (Arduino programming command) – a built in programming function in the Arduino environment.
This command allows the Arduino boards to play create different waves of frequencies to create different
sounds. It has the following syntax:
tone(pin, frequency)
Fig. A Fig. B
Construct the Circuit in Figure A. Your circuit would look as shown in Figure B.
In this experiment, we will be generating different tones using buzzer. To do this, connect the positive
pin of the buzzer into digital pin 8 of the Arduino Uno. To know the positive pin of the buzzer, look for
the plus sign found on the head of the buzzer. Connect the negative pin of the buzzer to the GND pin of
Arduino.
2) Type the Arduino Code below to your Arduino IDE. (Or copy and paste it to the Arduino IDE)
/*
Project 6 - Buzzer (making sounds)
*/
void setup() {
//we do not need to put any code initialization here.
}
void loop() {
// A "for" loop function is used to make a count from 0 to 9 using a variable "i".
// This "i" corresponds to the tone sequences listed like
// for i = 0 is for 261 and for i = 9 is for 440.
for (int i = 0; i < listTones; i++)
{
// The "tone" command from the Arduino library need only 2 parameters
// first parameter is the pin for the buzzer (buzzerPin)
// and second the tones we wish to play (tones)
tone(buzzerPin, tones[i]);
delay(500);
}
noTone(buzzerPin); // call the "noTone" command to stop playing any tones
delay(1000); // delay 1 second before playing again
}
3) Click Verify button to review code for errors. If the code has no errors and missing commands a message on
the window below will display “Done Compiling” this means your code is ready to be uploaded
into the Arduino microcontroller board.
4) Click Upload button to upload the Arduino Code to the Arduino microcontroller board.
Create an array tones[] variable to store frequency values. The variables are integers with 10 values.
int tones[] = {261, 277, 294, 311, 330, 349, 370, 392, 415, 440};
To set the buzzer to play a tone, simply call the tone() command. To do this set the two paramaters,
one: buzzerPin the buzzer positive + pin, two: call the tone frequency in the array of tones by using an
index number variable “i”.
tone(buzzerPin, tones[i]);
Because we will be playing all the different sounds stored in the tones variable, a loop statement, “for”
is used. Starting at i=0, the tone syntax plays the first tone found in the tones array, which has a value of
261. After 0.5 seconds, the i integer increments by one, making i=1. The tones syntax then plays the
second tone found in the array. For every increment of the “I” variable, the tone to be played also
changes by increment. This for:loop is true until the value of i is less than listTones by a value of 1, or
i=9. At i=10, the “for” loop stops.
for (int i = 0; i < listTones; i++)
{
// The "tone" command from the Arduino library need only 2 parameters
// first parameter is the pin for the buzzer (buzzerPin)
// and second the tones we wish to play (tones)
tone(buzzerPin, tones[i]);
delay(500);
}
After the loop function stopped, the buzzer stops playing using the noTone() syntax.
noTone(buzzerPin); // call the "noTone" command to stop playing any tones
delay(1000); // delay 1 second before playing again
Activity Challenge
a) Try adding other tone values to play different musical tones. What change to do in the array
parameter? You may also connect the LDR from the previous project and program the Arduino
that equivalent values read by the LDR to play the tone value on the speaker!
b) This time try creating a buzzer alarm using one or multiple tones. What frequencies to use?
Overview
Another sensor commonly used are the temperature sensors. In this experiment, we will be using one of
the most common and readily available sensors, the LM35 IC temperature sensor, as well as discussing
another electronic tool: component Datasheets. This temperature sensors connected to a display
system can be found in factories, malls, grocery store and other where the temperature is constantly
monitored for good environment control and monitoring.
Learning objectives
Arduino UNO R3 USB Cable (USB-A to USB-B) LM35 Temperature Sensor (Analog)
(1 unit) (1 unit) (1 unit)
When using the LM35 in Arduino, the LM35 sends out voltage readings, which is not the reading we
wanted since we wanted to get the temperature. Hence, we need to get the correction factor to get the
temperature reading. To do this:
Where voltage supply is equal to 5V, which is also the voltage used to power the LM35. The 1000 is used
to change the voltage unit from V to mV (m stands for milli- or one-thousandth of a unit). The 1024 is the
number of possible values that the Arduino microcontroller can read from an analog signal. This means
that if there are 1-10000 values, it can read only 1023 values, which means that when you divide 10000
by 10, you can only read values from 0, 9.765625, 19.53125 and so on. This is because of the limitation of
the Arduino microcontroller. The 1˚𝐶/10𝑚𝑉 is the parameter of the LM35. This means that every time
there is a change of 1˚C in the detection of the LM35, the voltage output changes by 10 mV.
By using the equation above, we can obtain a correction factor of 0.48828125. We will be using this value
in the experiment.
Datasheet – known also as specification sheet, it is a document that summarizes the performance and
other technical characteristics of a product or system. Some data found inside the datasheet are its
features, operational parameters, maximum tolerance for input and maximum output capacity, and many
others. It is important that you read the datasheet before using the component, especially its rating values
for voltage, current and temperature. The LM35 has a datasheet, with a sample image of the first page
below.
Fig. A Fig. B
Construct the Circuit in Figure A. Your circuit would look as shown in Figure B.
In this experiment, we’re building a simple temperature monitoring system and display the values to the
Arduino Serial Monitor. To setup the system, connect the +5V pin of LM35 to +5V pin of Arduino using
(red) wire, GND pin (black) to Arduino GND. OUT pin (green) to analog pin A0.
2) Type the Arduino Code below to your Arduino IDE. (Or copy and paste it to the Arduino IDE)
/*
Project 7 - Temperature Sensing with LM35
*/
void setup()
{
Serial.begin(9600); // call a serial monitor communication to view the readings
}
3) Click Verify button to review code for errors. If the code has no errors and missing commands a message on
the window below will display “Done Compiling” this means your code is ready to be uploaded
into the Arduino microcontroller board.
4) Click Upload button to upload the Arduino Code to the Arduino microcontroller board.
Placing the LM35IC near a warm/hot or cold item or environment will show increase and decrease of the
temperature value in the Serial Monitor.
Code Sequence
1. The value from the LM35 sensor is read and stored into the tempReading variable.
2. The value of tempReading is multiplied by 0.488 and stored into the correctTemperature
variable.
3. The value of correctTemperature is printed to serial port, displaying its value in the Serial
monitor.
4. A pause of 1000 milliseconds happens, and the process repeats again.
To store values that have decimal places, the variable type float is used in the code for storing data from
the LM35 and the corrected value and then declares equivalent variable names tempReading and
correctTemperature.
//assign variable to use for the program
float tempReading; // use a float variable tempReading for decimal reading
float correctTemperature; // use a float variable correctTemperature for decimal reading
Using analogRead() command, read the analog voltage value from the pin where the LM35 output pin
(temperaturesensorPin) is connected in the Arduino. The value taken from the LM35 is stored into the
tempReading variable.
tempReading = analogRead(temperaturesensorPin);
This value is multiplied by the correction factor 0.488 to obtain the temperature reading in degree
Celsius, and stored into the correctTemperature variable.
correctTemperature = tempReading * 0.488;
The value is then printed to the serial port together with the text “degree Celsius”. A delay of 1 second is
added before repeating the loop() function.
Serial.print(correctTemperature); // print the result to the serial monitor.
Serial.println(" degree Celsius"); // print result in a new line
delay(1000); // 1 second delay to display the value every second.
Activity Challenge
a) Put your circuit board near a fan or air condition unit and you should see that the value will
slowly go down since the temperature sensor detects a colder environment. You should see in
the serial monitor some data the same as in the image below.
b) Try moving to another Arduino Analog Pin, what pin did you use? What are the changes needed
to do in the code?
c) Try placing the LM35 circuit near a hot item or warm environment, what happens to the values?
Overview
Robotics and motor controls are one of the big categories in the industry sector. These robotics are used
in many environment such as factories and machines. One of the popular applications of Arduino is
controlling motors. One such motor is the Servo motor. In this experiment, we will be discussing about
servo motor and how the servo motor is controlled by the Arduino Uno using the Servo() Arduino
library. Servo motors can be found in factories, UAV drones, automobile cars, factory robots and in
machine automation environment. We will also discuss an important concept in programming, the
“objects” and “method”.
Learning objectives
Arduino UNO R3 USB Cable (USB-A to USB-B) Servo Motor (SG90) micro – 180
(1 unit) (1 unit) degrees
Servo Motor – Servo motors have three wires: power, ground, and signal. The power wire is typically
red, and should be connected to the 5V pin on the Arduino board. The ground wire is typically black or
brown and should be connected to a ground pin. The signal pin is typically yellow, orange or white and
should be connected to a digital pin on the Arduino board. Note that servos draw considerable power,
so if you need to drive more than one or two, you'll probably need to power them from a separate
supply (i.e. not the +5V pin on your Arduino). Be sure to connect the grounds of the Arduino and
external power supply together. In this case we will use a 180 degrees servo but a 360 degrees is also
available.
More information on the Servo and Servo library can be found here: https://www.arduino.cc/en/reference/servo
Duty Cycle – Duty cycle is the fraction of one period in which a signal or system is active. For example,
an LED lights up for one second, then switches off for another second. This cycle is repeated indefinitely.
This means that the sample system has a duty cycle of 50%. This concept is used in PWM systems, such
as servo motors, RGB LEDs and many more.
Arduino Libraries (built-in from Arduino Software, other libraries are externally downloaded and
imported) – To allow the Arduino environment to accommodate more operations, algorithms, modules
and even other microcontroller, libraries are introduced into the environment. These provide extra
functionality to use in sketches, be it coding for a third-party microcontroller or doing complex algorithms
not found on the Arduino environment. These libraries are coded by the Arduino organization, as well as
third parties. These libraries are commonly found on web-hosting services such as GitHub.
“objects” and “methods” – In programming, these “objects” are like variables which can store data but
also can do more like have their own programming functions as well. The concept of object and method
is used in C++ OOP (object oriented programming). In this experiment, “objects” will be used to create a
sub-name (or “object”) from the external Servo Arduino library. Example: the Servo library contains many
different functions, we will assign “myServo” as an object to call functions inside the Servo library. This
will be explained further in the example code and explanation.
Figure A Figure B
Construct the Circuit in Figure A. Your circuit should look as shown in Figure B.
In this experiment, we will make the servo motor rotate 180 degrees from left to right and vice versa. To
do this, connect the orange wire to digital pin 9 (orange wire), red wire to Arduino 5V pin (red wire), and
black wire to GND pin of the Arduino Uno (black wire).
2) Type the Arduino Code below to your Arduino IDE. (Or copy and paste it to the Arduino IDE)
/*
Project 9 - Servo Motor
*/
// include the "Servo.h" Arduino library for the servo motor commands
#include <Servo.h>
// we create our own name (or called "object" in programming) to use for calling servo command
Servo myservo;
//assign a variable for storing the value of the servo position from 0 to 180 degrees
int pos = 0;
void setup()
{
// use this command and put the Arduino pin number where we connect our servo motor input
// in this case we connect the servo motor on pin 9
// connection: orange wire to pin 9, red wire to 5V+, brown wire to GND
myservo.attach(9);
}
void loop()
{
// use a "for" loop function to count from 0 to 180 degrees
// the servo turns with a 1 degree per step
for (pos = 0; pos <= 180; pos += 1)
{
myservo.write(pos); // tell servo to go to position in variable 'pos'
delay(15); // waits 15ms for the servo to reach the position
}
// use another "for" loop to reverse the spin of the servo from 180 to 0 degrees
for (pos = 180; pos >= 0; pos -= 1)
{
myservo.write(pos); // tell servo to go to position in variable 'pos'
delay(15); // waits 15ms for the servo to reach the position
}
}
3) Click Verify button to review code for errors. If the code has no errors and missing commands a message on
the window below will display “Done Compiling” this means your code is ready to be uploaded
into the Arduino microcontroller board.
4) Click Upload button to upload the Arduino Code to the Arduino microcontroller board.
#include <name_of_library.h> – includes the library into your sketch. It should be a file name in H file
format.
myservo.attach() – similar to the function of pinMode(), it sets the pin declared inside the parenthesis
to the parameter “myservo”. Everytime you use commands found inside the servo library with the
parameter “myservo”, this pin is used.
myservo.write() – sends a command to the servo motor attached to “myservo” to rotate according to
the value specified. Has a range of 0-180˚
Comparison operator: greater than or equal to “>=” - compare the variable on the left with the value
or variable on the right of the operator. Returns true when the operand on the left is greater (bigger)
than or equal to the operand on the right. The opposite “>=” implies the opposite condition.
Code Sequence
1. Include the Servo library and assign an object name myservo.
2. Initialize servo position at 0 degrees, Set Arduino pin 9 as servo pin.
Code Explained
First, we tell Arduino to call and include the Servo library using #include command to make use of
functions for the servo motor.
#include <Servo.h>
An instantiation of the library is needed, thus the myservo variable (“object”) is used to instantiate.
Servo myservo;
We initialize and call the attach() function to assign which Arduino PIN the servo is connected to. Since
the servo motor is connected to Digital pin ~9 (PWM ~), 9 was used in the parameter.
void setup()
{
// use this command and put the Arduino pin number where we connect our servo motor input
// in this case we connect the servo motor on pin 9
// connection: orange wire to pin 9, red wire to 5V+, brown wire to GND
myservo.attach(9);
}
To rotate the servo motor, the for loop used in rotating it 180 degrees clockwise and counterclockwise.
Inside the for loop, the write(pos) function (in programming is the “method”) moves the arm of the servo
motor according to the value of position “pos”. A delay is added for a smooth transition between each
position.
for (pos = 0; pos <= 180; pos += 1)
{
myservo.write(pos); // tell servo to go to position in variable 'pos'
delay(15); // waits 15ms for the servo to reach the position
}
Activity Challenge
a) What code to add/change to control servo motor rotation with a use of push buttons? One
pushbutton rotates the servo motor clockwise the other pushbutton rotates it reverse.
b) Try using a different PWM pin, what pin can be used and what changes are made in the code?
What happens if a non PWM pin is used?
Overview
Besides from using Serial Monitor to display values and information, external displays such as LCDs
(Liquid Crystal Display) can be used to show your output values, text or any messages. In this
experiment, you will be using the LCD module to display texts as well as use corresponding libraries to
make it work with Arduino. These LCD technology display are very common in the street for big
billboards, the television, cellular phone and many other bright text and image display.
Learning objectives
Arduino UNO R3 USB Cable (USB-A to USB-B) LCD Display Module – 2x16
(1 unit) (1 unit) Characters (1 unit) (to obtain separately)
With the presence of libraries, using LCD modules becomes easier since all you need to do is plug in the
necessary lines to get your LCD module working.
(The LCD module and other supporting component may be obtained separately from the Kit).
Fig. A Fig. B
Construct the Circuit in Figure A. Your circuit would look as shown in Figure B.
Follow the connections from the Schematic drawing above, also from the earlier section “Circuit
Connection Guide” and in the Arduino Hardware Circuit images. Connections from the LCD Display
module to the Arduino is done by connecting the LCD’s data lines to the Arduino SPI pins and data pins.
2) Type the Arduino Code below to your Arduino IDE. (Or copy and paste it to the Arduino IDE)
/*
Project 8 - LCD Display
*/
void setup() {
// To start using the LCD, we first need to set up the LCD's number of columns and rows:
// thus, put (16 columns and 2 rows) using the "lcd.begin(x,y)" command
lcd.begin(16, 2);
// Now, we can print a message to the LCD.
lcd.print("Hello, World!");
}
void loop() {
// set the cursor to column 0, line 1
// (note: line 1 is the second row, since counting begins with 0):
lcd.setCursor(0, 1);
// We test out by printing the number of seconds since the time we start or reset the Ardui
no
lcd.print(millis() / 1000);
}
3) Click Verify button to review code for errors. If the code has no errors and missing commands a message on
the window below will display “Done Compiling” this means your code is ready to be uploaded
into the Arduino microcontroller board.
4) Click Upload button to upload the Arduino Code to the Arduino microcontroller board.
LiquidCrystal.h – a library that contains the functions and syntax to control LCD modules. This
includes instantiating variable names and printing texts.
millis() – returns the amount of time elapsed since the code started running. This value is in terms of
milliseconds.
Code Sequence
1. Display on the LCD module a “Hello, World!” text on the first row.
2. Set cursor for printing the next message to second row, first column.
3. Print time elapsed in seconds
4. Repeat second step.
In the code above, the LiquidCrystal library is imported to make use of functions that will allow the use
of the LCD module.
#include <LiquidCrystal.h>
An instantiation of the library is needed, thus the lcd variable is used to instantiate. To communicate
with the LCD module we need to include the 6 parameters, the digital pins connected to D4-D7, RS and E
are included in the instantiated variable parameter.
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
The communication between Arduino Uno and LCD module needs to be initialized, thus begin(16,2) was
used in setup() function. This was then followed by sending a text “Hello, World!” to the LCD module by
using the print() command.
void setup() {
// To start using the LCD, we first need to set up the LCD's number of columns and rows:
// thus, put (16 columns and 2 rows) using the "lcd.begin(x,y)" command
lcd.begin(16, 2);
// Now, we can print a message to the LCD.
lcd.print("Hello, World!");
}
To set where the text will be displayed, the function setCursor(0,1) is used. 0 is used for the 1st column
while 1 is for the row position. This means that the text will start printing at the second row, 1st character
block. The print() function is again used to print a text to the LCD module, with the text being the amount
of seconds that passed since the code was started. Because the cursor was set at 0,1, this means that the
seconds elapsed will be printed at the second row, not at the first row. The “Hello, World!” text remains
at the first row, while the time elapsed is updated at the second row.
void loop() {
// set the cursor to column 0, line 1
// (note: line 1 is the second row, since counting begins with 0):
lcd.setCursor(0, 1);
// We test out by printing the number of seconds since the time we start or reset the Ardui
no
lcd.print(millis() / 1000);
}
Activity Challenge
a) Try connecting the LM35 Sensor IC and display the temperature in the LCD? What code will you
add? What circuit connection needs to be added?
b) Try connecting the LDR photocell and display the light intensity value with the temperature
value. What code and circuit will you add?
Overview
In this section we will explore with another type of motor, the DC Motor. In the previous experiment we
used PWM program to control a servo motor’s degree/angles. Here we will learn how to use DC motors,
design the circuit that controls it and create a program to control the speed using Arduino commands.
These DC motors are found and used in motor electric fans, small motor boats, factories, power plant
and even at home. We can also use these motors for hobby project such as robotic car line follower or
obstacle-avoidance robots.
Learning objectives
Flyback diode (also called Back-voltage or signal diode) – DC motors generate a voltage spike that pushes
back against the current that created it when there is a sudden change in the supply voltage. This can
potentially damage circuits, and even render it inoperable. This is why diodes are often used in
conjunction with motors. A diode allows only one-way flow of current, meaning that it can be used to
eliminate the potential danger caused by the voltage spike generated by the DC motor.
NPN or PNP configuration (transistor) – are configuration/polarity type for a semiconductor like an NPN
Transistor 2N2222. NPN configuration is used mostly to pull the output of a system to the Ground “N”.
While PNP is mostly used to pull a positive source “P” to the output of the system.
Construct the Circuit in Figure A, your circuit would look something as shown in Figure B.
In this experiment, we will be controlling the speed of the DC motor using Arduino Uno. To assemble the
circuit, connect the cathode (negative side, with white marking) of the diode to the negative terminal
(black wire in figure B, green wire in figure A) of the DC motor, at the same time this pin is connected to
the common 5V in the breadboard (orange wire). The positive of diode is connected to DC motor positive
(red wire in figure B, yellow wire in figure A) and to the collector pin (right pin, facing the flat side) of the
2N2222. Connect the base of the 2N2222 transistor (middle pin) to a 330 Ohm resistor, the other end of
the 330 ohm resistor goes to Arduino Digital PIN 9 (using the green wire). Then, the emitter of the 2N2222
(left pin facing the flat side) goes to the common GND in the breadboard. Lastly, connect a common 5V
and GND from the Arduino UNO to the breadboards common 5V and GND pin lines using red and black
wire.
2) Type the Arduino Code below to your Arduino IDE. (Or copy and paste it to the Arduino IDE)
/*
Project 10 - DC Motor
*/
void setup()
{
// Call a Serial Monitor to use for entering a speed for the DC motor
// and assign the DC motor arduino pin as output.
Serial.begin(9600);
pinMode(motorPin, OUTPUT);
Serial.println("Type a speed from 0 to 255 in the box above and hit Enter");
}
void loop()
{
// We use "if" statement to check if a value (speed from 0 to 255) is entered in the serial
monitor.
// If there is, we use parseInt() function to get all the numbers.
// Then, use analogWrite() function to use that value to drive the DC motor speed.
if (Serial.available())
{
int motorSpeed = Serial.parseInt();
if (motorSpeed >= 0 && motorSpeed <= 255)
{
analogWrite(motorPin, motorSpeed);
}
}
}
3) Click Verify button to review code for errors. If the code has no errors and missing commands a message on
the window below will display “Done Compiling” this means your code is ready to be uploaded
into the Arduino microcontroller board.
4) Click Upload button to upload the Arduino Code to the Arduino microcontroller board.
Serial.available() – a command that gets the number of characters available for reading from the
serial port. This is data that’s already arrived and stored in the serial receive buffer (which holds 64
bytes).
Serial.parseInt() - Looks for the next valid integer in the incoming serial communication.
Boolean operator “&&” (logical and) – returns a true logic if both operands in left and right are true.
Learn more about the Arduino commands and syntax, go to https://www.arduino.cc/reference/en/
Code Sequence
1. Assign motor pin variable, initialize Serial communication and set pin modes.
2. Wait for speed value inputted in the Serial Monitor.
3. Once value is transmitted, the data is converted from string to integer and stored into variable
motorSpeed.
4. motorSpeed value is written to digital pin 9.
5. Motor spins. Then, value of motorSpeed is used until new value is introduced.
In the loop function, we use Serial.available() command statement to check if a data is inputted in the
Serial Monitor and sent to Arduino. We insert this in the “if” statement. Then, if a Serial data is available
(meaning a DC motor speed value is inputted in the Serial Monitor and Send button is clicked), we check
this value inputted by using the command Serial.parseInt() - this command checks for a “integer number
only”. This value then store to integer variable motorSpeed.
If the value inputted motorSpeed is greater than or equal to zero, and also less than or equal to 255 (if
(motorSpeed >= 0 && motorSpeed <= 255)), the code proceeds to sending this value in the Arduino Digital
PIN 9 motorPin using the command analogWrite(). Thus, making the motor spin to the equivalent speed.
void loop()
{
// We use "if" statement to check if a value (speed from 0 to 255) is entered in the serial
monitor.
// If there is, we use parseInt() function to get all the numbers.
// Then, use analogWrite() function to use that value to drive the DC motor speed.
if (Serial.available())
{
int motorSpeed = Serial.parseInt();
if (motorSpeed >= 0 && motorSpeed <= 255)
{
analogWrite(motorPin, motorSpeed);
}
}
}
Activity Challenge
a) Copy and upload the code below. What happens to the motor and how does it operate? Also,
try to play with the Run and Stop values to make the motor spin longer or shorter.
/*
Project 10 - DC Motor, code 2
*/
void setup()
{
pinMode(motorPin, OUTPUT); // set the motorPin to output
}
void loop()
{
// Call the function "motorRunandStop()" to run repeatedly in
motorRunandStop();
}
// We create an outside function to make the DC motor Run and Stop for 2 seconds
void motorRunandStop()
{
b) Try entering a text string in the Serial Monitor, what happens after? Will the motor spin?
c) Let’s try using a different Arduino Pin. Move the wire to the change pin. What are the code
changes needed?
Overview
If you are looking to automate turning on and off of a small DC fan for warm weather conditions, the
automated temperature controlled fan is your go to project! Automation is one of the many real world
applications that you can take your skill in programming and hardware design. Here you will explore on
how we can program the Arduino to monitor the room temperature using the Temperature sensor (LM35
IC) and automatically turn on a DC Motor which functions a fan to provide air cooling.
All the parts required to build this project can be found in this kit.
Parts needed
Project Concept
A temperature sensor (LM35IC) will monitor the room temperature. A DC Motor fan turns On and Red
LED lights up when hot condition is obtained. In the opposite, the DC motor fan turns Off when the
environment is Cold and the Green LED also lights up. The hot and cold value are user defined in the
Arduino code.
LM35 temperature
IC (flat side in front)
Now cut out a small paper/carton and attach it to the end of the DC motor to serve as your fan blade.
// assign variable for the arduino pin connected to DC motors, LM35 and LEDs
int motorPin = 9;
int greenLED = 10;
int redLED = 11;
int temperaturesensorPin = 0; // use Arduino Analog pin 0 for temprature reading
void setup()
{
// Call a Serial Monitor to use for checking temperature readings
// and designation of motorPins, greenLED and redLED as output
Serial.begin(9600);
pinMode(motorPin, OUTPUT);
pinMode(greenLED, OUTPUT);
pinMode(redLED, OUTPUT);
}
void loop()
{
// reads analog value from temperaturesensorPin and stores it to correctTemperature after ca
libration
// DC motor and LEDs respond depending on the value of the correctTemperature using conditio
nal statements
tempReading = analogRead(temperaturesensorPin);
correctTemperature = tempReading * 0.48828125;
if (correctTemperature > 30.00)
{
Serial.println("HOT!");
analogWrite(motorPin, 150);
digitalWrite(redLED, HIGH);
digitalWrite(greenLED, LOW);
}
else
{
Serial.println("COLD!");
analogWrite(motorPin, 0);
digitalWrite(redLED, LOW);
digitalWrite(greenLED, HIGH);
}
delay(500);
}
If the room temperature is below 30˚C, the serial monitor displays “COLD!” text. The green LED also
lights up while the DC motor does not spin.
If the room temperature is above 30˚C (covering the LM35 temperature sensor with fingers in order to
not detect the cold room temperature), the serial monitor displays “HOT!” text. The red LED lights up
and the DC motor will now spin at the speed indicated in the code.
The temperature reading of the LM35 sensor is first obtained. This value is then stored to variable
tempReading.
tempReading = analogRead(temperaturesensorPin);
Because the value is not the actual temperature value, it is multiplied with the correction factor value
(0.48828125) when using LM35 to get the temperature reading in Celsius. Value is then stored in the
integer variable correctTemperature.
correctTemperature = tempReading * 0.48828125;
To control the fan based on two situations, such as when it its hot or cold, we use a set temperature value
that triggers when the reading from LM35 is higher or lower than this value. This value is set at 30.00
degrees celsius. When the reading is greater than 30.00 (hot environment) , the DC motor runs, and the
red LED goes on while green LED goes off.
if (correctTemperature > 30.00)
{
Serial.println("HOT!");
analogWrite(motorPin, 100);
digitalWrite(redLED, HIGH);
digitalWrite(greenLED, LOW);
}
If the reading is less than 30.00 (Cold environment), the fan and red LED goes off, while green LED goes
on.
else
{
Serial.println("COLD!");
analogWrite(motorPin, 0);
digitalWrite(redLED, LOW);
digitalWrite(greenLED, HIGH);
}
Project challenge
1. Emulate an electric fan in your house. Set 3 different speeds as speed1, speed2, speed3. What
code changes should you make? What circuit will you add?
2. Change the temperature value to your own personal application.
Overview
In this project, we will construct a circuit that mimics the traffic lights system. A traffic light system serves
a big purpose on the street they are used in intersections, pedestrian crossings and other locations that
needed regulation of flow of traffic. This project involves a little complex (challenge) coding, as well as
analysis of the code to be used. We will use array programming functions, LED lights and other skills we
gained from the Arduino primer.
All the items we will be using can be found in the parts of our starter kit.
Parts needed
Project Concept
A Traffic light system is mostly used in streets but also can be used in production lines and signage. Traffic
system allows for a smooth and safety flow of vehicles and transportation. Having a way to automate and
create our own traffic system will help enhance and optimize travel time. In this project we will create
and control two traffic lanes name Traffic1 and Traffic2. This involves the use of signaling lights such as
LEDs to display when the vehicle can pass or stop. We will program our Arduino microcontroller to
automate and regulate the flow of traffic where when applied to real world application will optimize travel
time.
/*
* Traffic Light System Code
* by Bitstoc Electronics
* February 2019
*/
//other varaiables
int previouserror = 0;
int currenterror = 0;
//for controlling how much time each LED lights up during transition
int lightpause = 1000;
void setup() {
// put your setup code here, to run once:
//setting up Traffic 1 Lights as OUTPUT
pinMode(greenLight1, OUTPUT);
pinMode(orangeLight1, OUTPUT);
pinMode(redLight1, OUTPUT);
void loop() {
// put your main code here, to run repeatedly:
//triggers when Traffic1 button is pressed (to LOW) and Traffic2button is not pressed
if (TLIGHT1trigger == LOW && TLIGHT2trigger == HIGH)
{
currenterror = 1;
//triggers when Traffic2 button is pressed (to LOW) and Traffic1 button is not pressed
else if (TLIGHT1trigger == HIGH && TLIGHT2trigger == LOW)
{
currenterror = 0;
if (currenterror != previouserror)
{
goTrafficLight1();
delay(lightpause);
SwitchTrafficLight();
delay(lightpause);
goTrafficLight2();
}
previouserror = currenterror; //previouserror value turns to 0
}
}
void goTrafficLight1()
{
//turns greenLight1 and redLight2 ON while other LEDs off
digitalWrite(greenLight1, HIGH);
digitalWrite(orangeLight1, LOW);
digitalWrite(redLight1, LOW);
digitalWrite(greenLight2, LOW);
digitalWrite(orangeLight2, LOW);
digitalWrite(redLight2, HIGH);
}
void SwitchTrafficLight()
{
//turns ornageLight1 and orangeLight2 ON while other LEDs off
digitalWrite(greenLight1, LOW);
digitalWrite(orangeLight1, HIGH);
digitalWrite(redLight1, LOW);
digitalWrite(greenLight2, LOW);
digitalWrite(orangeLight2, HIGH);
digitalWrite(redLight2, LOW);
}
void goTrafficLight2()
{
//turns greenLight2 and redLight1 ON while other LEDs off
digitalWrite(greenLight1, LOW);
digitalWrite(orangeLight1, LOW);
digitalWrite(redLight1, HIGH);
digitalWrite(greenLight2, HIGH);
digitalWrite(orangeLight2, LOW);
digitalWrite(redLight2, LOW);
}
Once the program starts, Traffic2 (Left) is GO (green) first while Traffic1 (Right) is STOP (Red).
If you Press Left Lane (TRAFFIC2), then both lights go Yellow, then TRAFFIC2 (Left) goes GREEN while
TRAFFIC1 (Right) now goes to Red. And vice versa.
Code Explained
In the first part the variables to use are declared. Also, we include a state checker variable previouserror
and currenterror to use later for which state is currently running.
//other varaiables
int previouserror = 0;
int currenterror = 0;
Pins are initialized in the setup() function. Also, we set the TRAFFIC2 goTrafficLight2() function (left
traffic in the circuit/drawing) to run and Go (Green light) first.
void setup() {
…
//setting up inital state of traffic lights
goTrafficLight2();
}
There are two possible cases in the system: TRAFFIC1button is pressed is one case and TRAFFIC2 is pressed
is another. That’s why there are only two conditional statements used in this project. To make the system
more stable, only one button must be pressed at a time, otherwise no change will happen.
// triggers when Traffic1 button is pressed (to LOW) and Traffic2button is not pressed
if (TLIGHT1trigger == LOW && TLIGHT2trigger == HIGH)
{
…
}
// triggers when Traffic2 button is pressed (to LOW) and Traffic1 button is not pressed
else if (TLIGHT1trigger == HIGH && TLIGHT2trigger == LOW)
{
Situation 1. Right push button (TRAFFIC1 is pressed and goes to LOW). We will give the currenterror
integer a value of 1. Since the previouserror value from the start of the code is 0, then the code will
continue to execute since currenterror (1) != previouserror (0) (is not equal “!=”). The code sequence for
TRAFFIC1 to have a Go (Green) signal is:
Situation 2. Left push button (TRAFFIC2 is pressed and goes to LOW). We will give the currenterror integer
a value of now 0 (in TRAFFIC1 it is 1). Since the previouserror value was changed to 1 from the TRAFFIC1
code sequence, then the TRAFFIC 2 code will continue to execute since currenterror (0) != previouserror
(1). The code sequence for TRAFFIC2 to have a Go (Green) signal is:
Situation 3. Pressing the push button for a Go traffic while still in Go state.
Even if TRAFFIC1 is still Go (Green) and you press the TRAFFIC1 Go button, the TRAFFIC1 Go code sequence
will not run because when TRAFFIC1 was in Go state, it’s last code sequence set the previouserror equal
value to the currenterror which is 1 and in the beginning of the TRAFFIC1 code sequence the currentstate
is already 1, they are equal. The code for change of lights will only continue and run if the currenterror is
not equal to previouserror (currenterror != previouserror).
The same with TRAFFIC2. Even if TRAFFIC2 is still Go (Green) and you press the TRAFFIC2 Go button, the
TRAFFIC2 Go code sequence will not run because when TRAFFIC2 was in Go state, it’s last code sequence
set the previouserror equal value to the currenterror which is 0 and in the beginning of the TRAFFIC2
code sequence the currentstate is already 0, they are equal. The code for change of lights will only
continue and run if the currenterror is not equal to previouserror (currenterror != previouserror).
At the last part, we created custom functions to call for controlling the switching of the LEDs. Three
functions were made:
a) The Go TRAFFIC1 contains a greenlight TRAFFIC1 On with redlight TRAFFIC 2 and orangelight both OFF.
b) The Go TRAFFIC2 contains a greenlight TRAFFIC2 On with redlight TRAFFIC 1 and orangelight both OFF.
c) The SwitchTrafficLight function contains a TRAFFIC1 and TRAFFIC2 greenlight and redlight Off, while
having a orangelight1 and orangelight 2 On.
void goTrafficLight1()
{
//turns greenLight1 and redLight2 ON while other LEDs off
digitalWrite(greenLight1, HIGH);
digitalWrite(orangeLight1, LOW);
digitalWrite(redLight1, LOW);
digitalWrite(greenLight2, LOW);
digitalWrite(orangeLight2, LOW);
digitalWrite(redLight2, HIGH);
}
void SwitchTrafficLight()
{
//turns ornageLight1 and orangeLight2 ON while other LEDs off
digitalWrite(greenLight1, LOW);
digitalWrite(orangeLight1, HIGH);
digitalWrite(redLight1, LOW);
digitalWrite(greenLight2, LOW);
digitalWrite(orangeLight2, HIGH);
digitalWrite(redLight2, LOW);
}
void goTrafficLight2()
{
//turns greenLight2 and redLight1 ON while other LEDs off
digitalWrite(greenLight1, LOW);
digitalWrite(orangeLight1, LOW);
digitalWrite(redLight1, HIGH);
digitalWrite(greenLight2, HIGH);
digitalWrite(orangeLight2, LOW);
digitalWrite(redLight2, LOW);
Project Challenge
a) Try and program the code where Stop and Go is time limited. Which part of the code will
change? What code lines need to be added?
b) Try adding third and fourth lane, what circuit connections will you add? What code needs to be
added?
Use this section to assemble your Arduino and Breadboard with the base holder plate. The base plate will
hold together the board and the breadboard to easily connect and organize your wiring.
1. Peel off the protective sticker on both sides. 5. Get your Arduino UNO R3 board and place it
on top of the four plastic rings with holes
aligned.
List of other Arduino Libraries, extra codes bundled to use for other projects
https://www.arduino.cc/en/Reference/Libraries