You are on page 1of 111

Arduino Starter Kit (Version 2.

0)
Experiment Manual

Your guide to learn programming and building electronics with Arduino

BITSTOC ELECTRONICS www.bitstoc.com 1|P a g e


WELCOME TO ARDUINO PROGRAMMING AND CIRCUIT DESIGN

Hello World!

Welcome to the most popular


programming and electronics
design platform,
the Arduino Starter Kit!

The Arduino Starter Kit is a


complete learning tool for
programming and electronics
design. The kit contains all the
essential parts to get you started:
the main Hardware board, the
Arduino UNO R3, a small breadboard to connect the components, LED’s for light,
push buttons, sensors and many others.

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.

BITSTOC ELECTRONICS www.bitstoc.com 2|P a g e


Contents
------------------------------------------------------------------------------------------------------------------------------------------
INTRODUCTION
 Robotics Technology
 Robotics and Arduino
 Arduino Environment and Background
 Arduino and STEM/STEAM

------------------------------------------------------------------------------------------------------------------------------------------
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

BITSTOC ELECTRONICS www.bitstoc.com 3|P a g e


Introduction

Robotics and Technology

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.

Robotics with Arduino

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.

BITSTOC ELECTRONICS www.bitstoc.com 4|P a g e


Arduino Hardware Overview

The Arduino UNO R3 is the main hardware


board used to start with the Arduino
Platform. Other version and form factor in
the Arduino ecosystem are available, but the
version UNO R3 is the main starting point.
This board has all the main parts needed to
complete a circuit and start coding.

Parts of an Arduino UNO R3 Board


A. USB Port – port for connecting the USB Cable, either for powering the Arduino Uno board or
uploading codes from the computer.
B. Reset Button – resets the Arduino Uno before execution of the code. The code uploaded to the
board does not get erased, but rather restarts the Arduino Uno board.
C. Barrel Jack – provides power to the Arduino Uno when a power source is connected.
D. 5V voltage regulator – ensures that the voltage being supplied to the microcontroller stays at
5V. Able to regulate voltage inputs from 5V to 12V.
E. Power LED indicator – when power is supplied to the Arduino Uno, this LED indicator lights up
to indicate that power is supplied to the board
F. ATMEGA328P Integrated Circuit (IC) Microprocessor – the brain of the Arduino Uno. All
processing of information occurs here, from digital and analog signals to serial communication.
G. Power Pins – provide power to the Arduino Board as well as to modules connected to it. It has 4
pins: Vin, GND, 5V and 3.3V. Vin is used to indicate the input pin for the voltage to the Arduino
board when it’s using an external power source connected (referred to the drawing above part C:
Barrel Jack). 5V gives out a 5V stable supply, and 3.3V pin for 3.3V supply. The GND pin provides
access to ground connection.
H. Analog Pins – provides access to analog pins of the Arduino Uno. It can be used to read or send
analog signals.
I. Digital Pins – provides access to digital pins of the Arduino Uno. It can be used to read or send
digital signals. Additionally, some of these pins have the (~) symbol, meaning they have Pulse
Width Modulation (PWM) capability, which is used to control motors.
J. TX and RX LEDs– stands for transmit and receive respectively. They are used for checking a
successful serial communication.
The brain of the Arduino UNO R3 microcontroller board is ATmega328P microprocessor IC. A
microprocessor is a computer in the form of a single Integrated Chip (IC) dedicated to a specific task or
application. Like a computer, it has a memory, a programmable input/output and a processor.

The ATmega328P is low-cost, high-performance microcontroller IC with 32 kB of memory, 14 digital pins,


6 analog pins, PWM capability, serial communication (UART, SPI and I2C) and 16Mhz pf crystal oscillator.

BITSTOC ELECTRONICS www.bitstoc.com 5|P a g e


Basic Electronics: The Breadboard
The Breadboard is a tool that makes it easy to connect many electronics component. It has holes, letter,
numbers and connection lines designed to easily spot a certain point in a circuit.

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.

BITSTOC ELECTRONICS www.bitstoc.com 6|P a g e


Basic Electronics: What’s an electronic circuit?
An electronic circuit is a system composed of individual electronic components such as resistor, LED’s,
capacitors, transistors, power source, ground source and many others of which these components
conduct electricity and provide a path for the electric current to flow. In short, a circuit forms a loop where
the path starts and ends at the same point.

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.

Schematic Diagram Actual Circuit

Common Electronic & Electrical Terms


 Voltage – the electric potential difference between two points.
 Current – the amount of flow of electrons.
 Resistance (Resistor) – the amount of opposition of a material to the flow of electrons.
 Switch – a component for controlling (opening or closing) the connection in an electrical circuit.
 Battery – a mobile, limited DC source. Exists as either primary (non-rechargeable) or secondary
(rechargeable).
 IC (Integrated Circuit) – a set of electronic circuits compressed together in a single material.
 Ground – the reference point of power for every circuit. In this manual, the ground is the
negative terminal of the power supply.
 Transistor - A 3 terminal (usually) electronic device which can act as either an amplifier or a
switch. Common types of transistors include the Bipolar Junction Transistor (BJT) and the Metal
Oxide Semiconductor Field Effect Transistor (MOSFET).

BITSTOC ELECTRONICS www.bitstoc.com 7|P a g e


Arduino Software IDE Overview

Parts of the Arduino IDE (code editor)

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.

BITSTOC ELECTRONICS www.bitstoc.com 8|P a g e


Arduino Programming Concepts
The Arduino is programmed with C/C++ programming language. To have a working code you will form a
sequence and combination of commands and syntaxes that is structured to do the task you want. Below
are concepts to apply when creating an Arduino C/C++ code.

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() {}

Values (are variable/names, types of data (data type) and constants)

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)

Some example functions are:

digitalRead() – to read digital signals


digitalWrite() – to write digital signals
pinMode() – to set the mode of use for a pin
analogRead() – read analog data
analogWrite() – write analog data

For a complete list of programming commands and functions go to


https://www.arduino.cc/reference/en/

BITSTOC ELECTRONICS www.bitstoc.com 9|P a g e


Install and Prepare the Arduino Software IDE

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.

To install in Mac OS: https://www.arduino.cc/en/Guide/MacOSX


To install in Linux OS: https://www.arduino.cc/en/Guide/Linux

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.

BITSTOC ELECTRONICS www.bitstoc.com 10 | P a g e


2. Launching the Arduino will open the
Arduino Software IDE!

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).

Choose the type of Arduino board to use.


Go to Tools>Board>click “Arduino UNO”
/ “Genuino UNO”

BITSTOC ELECTRONICS www.bitstoc.com 11 | P a g e


Connect to the target Arduino board by
selecting the assigned port number
(COMXX) from the earlier installation.
This case our Arduino UNO is assigned
in “COM14”. Go to Tools>Port>click
“COMXX (Arduino Uno)

Every Arduino board connected to the


computer will be assigned with its own
COM port number, remember this COM
port number for all your code uploads.

Click Verify button to Compile the code.

Click on the Upload button.

Wait Uploading to finish and


Done uploading prompts.

For troubleshooting your Arduino hardware or software installation, go to


https://www.arduino.cc/en/Guide/HomePage and https://www.arduino.cc/en/Guide/Windows.

BITSTOC ELECTRONICS www.bitstoc.com 12 | P a g e


Kit Parts Inventory

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)

Connecting Wires LCD Display (2x16


- Male-Male, LDR (Photocell, Buzzer (Piezo, LM35 Characters, Servo Motor
30pcs (assorted- Light Sensor) Passive, Tone- Temperature White in blue (SG90) micro –
size) Adjustable) Sensor IC backlight) 180 degrees
(LM35 markings) (sold separately)

DC Motor (Basic Hobby Transistor (NPN) – 2N2222 Base Holder plate for
Motor) (2N2222 markings) Diode (Signal diode) Arduino and Breadboard
(sold separately)

Parts description and uses


 Arduino UNO R3 – the main Arduino Hardware board to program and connect electronics
components.
 USB Cable Type A to B – the USB Connection cable use to connect and communicate the Arduino
board to the computer.
 Breadboard - Half Size, 400 points – the base plate with holes which connect the Arduino and all
other electronics components.
 LED - Green (5mm) – the light source in color Red to produce lighting projects.
 LED - Red (5mm) – the light source in color Green to produce lighting projects.
 LED – Orange/Yellow (5mm) – the light source in color Orange/Yellow to produce lighting
projects.
 Resistor (330 ohms (orange/orange/brown) – an electronic component used to control/limit the
current & voltage that is running in an electronic circuit.
 Resistor (1k ohms) (brown/black/red) – an electronic component used to control/limit the
current & voltage that is running in an electronic circuit.

BITSTOC ELECTRONICS www.bitstoc.com 13 | P a g e


 Resistor (10k ohms) (brown/black/orange) – an electronic component used to control/limit the
current & voltage that is running in an electronic circuit.
 Connecting Wires - Male-Male, 65pcs (assorted-size) – jumper wires used to connect a certain
point to another point from your circuit in a breadboard.
 Push Button Tactile Switch (SPDT) – an electronic component used for giving signal to a circuit or
code with a “push” mechanical action.
 RGB L.E.D (Red-Green-Blue) common cathode - the light source that can produce different colors
using a combined intensity of each Red, Green, or Blue
 Potentiometer (10k Ohm) – an electronic component used to adjust a signal by adjusting the
resistance of a certain point in a circuit.
 LDR (Light Dependent Resistor) – a component that detects brightness and darkness and outputs
a certain resistance or voltage value equivalent.
 Buzzer (passive, tone-adjustable) – a component that’s capable of producing sounds or tones in
different rhythmic pattern.
 LM35 Temperature Sensor – a sensor component used to detect surrounding temperature and
outputs a certain voltage equivalent.
 Servo Motor SG90 (micro) 180 degrees – a motor in a “Servo” type used frequently motor
application which the rotation angle can be controlled using “PWM” signals.
 DC Motor (basic hobby motor) – a usual DC motor for spinning and rotation.
 Transistor NPN – 2N2222 – an electronic component controlled digitally to act as a switch.
 Diode (Rectifier) - 1A, 50V – a component which sets the direction of a voltage/current of a circuit
in positive or negative flow.
 LCD Display 2x16 characters – used for displaying text, characters or symbols. (Note: this item is
sold separately).
 Base Holder for Arduino and Breadboard – a placement holder for the Arduino board and
Breadboard to organize wiring and circuit connections. (Note: this item is sold separately).

BITSTOC ELECTRONICS www.bitstoc.com 14 | P a g e


Platform Assembly and Setup
If you got the Base Holder plate for Arduino and Breadboard, go to Appendix A (page 109) for the
assembly guide. If you did not get a base holder you may proceed with the experiment proper.

BITSTOC ELECTRONICS www.bitstoc.com 15 | P a g e


EXPERIMENT 1
Digital Output – Blinking an LED

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

In this Experiment we will discuss the following.


 First use of the Arduino UNO R3 board
 Constructing a basic electronics circuit
 Learning about an LED, a Resistor, Connecting wires and Breadboard
 Programming our Arduino board to blink the LED
 Digital Output
 Basic construction of an Arduino Code

BITSTOC ELECTRONICS www.bitstoc.com 16 | P a g e


Parts you will need

Resistor (330 ohms)


Arduino UNO R3 USB Cable (USB-A to USB-B) LED (Red) (orange-orange-brown)
(1 unit) (1 unit) (1 unit) (1 unit)

Breadboard Connecting wires


(1 unit) 1(Black), 1(Red)

Concepts & Vocabulary


Digital - A system that deals with discrete values (ex. Number 0 and 1).
Digital Output – a signal direction going out (“output”) from a system or component (in Arduino UNO
voltage it’s equivalent to 5V supply).
Polarity – refers to an electronic component which can only be connected in one direction. Example,
positive pole and negative pole which cannot be interchanged when used. An LED described below where
has two polarities, Positive with a symbol (+) and a Negative with a symbol (-).
Anode – another term for Positive polarity/pin of an electronic component.
Cathode – another term for Negative polarity/pin of an electronic component.
L.E.D. (Light Emitting Diode) - is an electronic component that outputs/emits light. It has a Negative pin
(or Ground pin) and a Positive pin. LED’s can be found in many devices such as signage, disco lights, TV,
traffic lights and many more. In a basic circuit a positive (HIGH voltage) signal should pass through the
positive point of the LED and the negative pin to the circuit ground in order to work.

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

BITSTOC ELECTRONICS www.bitstoc.com 17 | P a g e


signal uses, a resistor will control the flow of electricity so that the components will function well and not
get damaged.

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)).

Resistor Value Color Code Chart

BITSTOC ELECTRONICS www.bitstoc.com 18 | P a g e


Voltage, Current, Resistance and Ohm’s Law

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:

𝑉
𝐼=
𝑅

VCC – used in a circuit or


diagram to reference a
common Positive voltage
source.

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.

Now, let’s build our circuit!!!

BITSTOC ELECTRONICS www.bitstoc.com 19 | P a g e


The Arduino Hardware Circuit

Longer pin

Figure A Figure B

Construct the Circuit in Figure A, your circuit would look something as shown in Figure B.

Terms and Concepts

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.

Hardware Circuit Explained

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!

BITSTOC ELECTRONICS www.bitstoc.com 20 | P a g e


The Arduino Code
1) Open the Arduino Software IDE. Go to top-left corner of the Arduino IDE window and click File>New.
This action opens up a new coding editor window for a new project.

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.
*/

// assign a text variable to represent as the value Arduino Digital 13 (D13)


int ledPin = 13;

// 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);
}

// 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
}

Your Arduino IDE window with the Arduino LED Blink code

BITSTOC ELECTRONICS www.bitstoc.com 21 | P a g e


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.

The Experiment Output


After you successfully upload your Arduino code to the Arduino board, the code will automatically run.
You should see that the LED will start to blink ON and OFF every second.

BITSTOC ELECTRONICS www.bitstoc.com 22 | P a g e


Learn about the 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.

To learn more about the Arduino commands and syntax, go to https://www.arduino.cc/reference/en/

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.
*/

BITSTOC ELECTRONICS www.bitstoc.com 23 | P a g e


In the second part, we declare ledPin to be used as a text variable equivalent to an integer (int) number
13. The character // signifies a comment line, this code line is not compiled and included for the
machine code. In programming practice it is recommended to put some comments/notes in the code to
guide you when troubleshooting your code and knowing what the code line does.
// assign a text variable to represent as the value Arduino Digital 13 (D13)
int ledPin = 13;

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.

Example below, we set the ledPin to have an OUTPUT mode.


// 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);
}

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?

BITSTOC ELECTRONICS www.bitstoc.com 24 | P a g e


EXPERIMENT 2
Digital Input – PUSH BUTTON

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

In this Experiment we will discuss the following.

 Constructing a button circuit controlling lights


 Learning about an Buttons, Pull-up / Pull-down Resistor
 Digital Input
 Push Buttons

BITSTOC ELECTRONICS www.bitstoc.com 25 | P a g e


Parts you will need

Arduino UNO R3 USB Cable (USB-A to USB- Breadboard Connecting wires


(1 unit) B) (1 unit) (1 unit)

Tactile Switch
LED (Red) Resistor (330 ohms) (2 units) Resistor (10k ohms)
(1 unit) (1 unit) (brown/black/orange)

Concepts & Vocabulary


Digital Input – a signal direction going into (“input”) the system or component.
Switches – any component that can change the parameter or current state of the system.
Button Switches – (also called Push Buttons or Tactile Switch) is an electronic component which
functions as a mechanical switch. Usually they are used as switches to connect or disconnect circuits to
control the operation of electronic devices. You can see many of this in house switch lightings, remote
controls, DVD player controls and many others.

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.

BITSTOC ELECTRONICS www.bitstoc.com 26 | P a g e


Pull-up and Pull-down Resistor Network

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.

In most application and in our experiment, a pull-up resistor configuration is used.

Now let’s build our circuit!

BITSTOC ELECTRONICS www.bitstoc.com 27 | P a g e


The Arduino Hardware Circuit

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.

Hardware Circuit Explained

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

BITSTOC ELECTRONICS www.bitstoc.com 28 | P a g e


The Arduino Software Code
1) Open the Arduino Software IDE and on the top left corner click File>New.
This action opens up a new coding editor window for a new project.

2) Type the Arduino Code below to your Arduino IDE. (Or copy and paste it to the Arduino IDE)

/*
Buttons and DIGITAL Inputs
*/

// assign Arduino Pins for the LED and Buttons


int ledRedPin = 3;
int buttonLeftPin = 9;
int buttonRightPin = 8;

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.

BITSTOC ELECTRONICS www.bitstoc.com 29 | P a g e


The Experiment Output
The Red LED is OFF when the circuit starts after uploading the code. Press the Left Push Button
on the breadboard and the Red LED light’s up (ON). Now Press the Right Button and the Red LED will turn
OFF.

Press the Left button, LED in On! Press the Right Button pressed, LED is Off

Learn about the Code!


 digitalRead(Arduino Digital Pin); – checks value or status of digital pin. Returns a value of HIGH (1) or
LOW (0)
 Conditional Statement – Conditional statements allow different computations or actions depending
on the specified action to a specific situation. The IF statement is an example of a conditional
statement, where if the parameters inside the parenthesis () becomes true, it then performs the
operations inside the curly brace {}.

To learn more about the Arduino commands and syntax, go to https://www.arduino.cc/reference/en/

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.

BITSTOC ELECTRONICS www.bitstoc.com 30 | P a g e


3. After checking of the buttonLeftPin state, proceed to next “IF”
4. If buttonRightPin is pressed, turn the LED Off by giving a LOW signal to Arduino Digital PIN 13
(D13). If buttonRightPin is not pressed, proceed to next line
5. Repeat from the start.

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.

// assign Arduino Pins for the LED and Buttons


int ledRedPin = 3;
int buttonLeftPin = 9;
int buttonRightPin = 8;

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
{

BITSTOC ELECTRONICS www.bitstoc.com 31 | P a g e


digitalWrite(ledRedPin, LOW); // tun OFF the LED
}
}

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?

BITSTOC ELECTRONICS www.bitstoc.com 32 | P a g e


EXPERIMENT 3
Analog Output (PWM) & RGB LED Light

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

In this Experiment we will discuss the following.


 Constructing light circuit with different colors
 Learn Electronic Component - RGB LED
 Analog Output
 RGB LEDs
 PWM (Pulse Width Modulation) signal
 Creating your personal function

BITSTOC ELECTRONICS www.bitstoc.com 33 | P a g e


Parts you will need

Arduino UNO R3 USB Cable (USB-A to USB-B) Potentiometer – 330 Ohm


(1 unit) (1 unit) (3 unit)

RGB LED
Breadboard Connecting wires
(1 unit)
(1 unit)

Concepts & Vocabulary


Analog – It is a signal that can continuously vary over time. Unlike digital which has binary state example
1 or 0 and 5V or 0V, an analog signal can be between them (e.g. 0.2, 2.82, 4.031 etc.)
Common Cathode / Common Anode – term use to specify an RGB LED’s common connection type. A
Common Cathode configuration means all pins of an RGB or LED component is Anode and one pin
(common pin is the Cathode). A Common Anode means all pins of an RGB or LED component is Cathode
and one pin (common pin is the Cathode).

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.

BITSTOC ELECTRONICS www.bitstoc.com 34 | P a g e


RGB LEDs can emit or produce different colors of light. They are manufacture by putting in three LEDs of
red, green, and blue into a transparent or semitransparent plastic shell and lead out four pins. The three
primary colors of red, green, and blue can be mixed to compose all kinds of colors by brightness, so you
can make a RGB LED emit colorful light by controlling the circuit.

PWM (Pulse Width Modulation)

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.

Another example for PWM can be found in Arduino IDE: File->Examples->Analog->Fading

Reference: https://www.arduino.cc/en/Tutorial/PWM

BITSTOC ELECTRONICS www.bitstoc.com 35 | P a g e


The Arduino Hardware Circuit

Figure A Figure B

Construct the Circuit in Figure A, your circuit would look something as shown in Figure B.

Hardware Circuit Explained

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).

BITSTOC ELECTRONICS www.bitstoc.com 36 | P a g e


The Arduino Software Code
1) Open the Arduino Software IDE. Go to File>New to create a new programming window.

2) Type the Arduino Code below to your Arduino IDE. (Or copy and paste it to the Arduino IDE)

/*
RGB LED and Analog Outputs
*/

int redPin = 11;


int greenPin = 10;
int bluePin = 9;

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);
}

// create a new programming “Function” called setColor


void setColor(int red, int green, int blue)
{
analogWrite(redPin, red);
analogWrite(greenPin, green);
analogWrite(bluePin, blue);
}

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.

BITSTOC ELECTRONICS www.bitstoc.com 37 | P a g e


The Experiment Output
After you successfully upload your Arduino code to the Arduino board, the board will automatically run
the code. You will see six different colors, with the first three colors shown below. You may want to
cover the RGB LED with a white/masking tape to diffuse and see the full colors.

Learn about the Code!

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.

Programming commands (syntax)

 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.

To learn more about the Arduino commands and syntax, go to https://www.arduino.cc/reference/en/

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

BITSTOC ELECTRONICS www.bitstoc.com 38 | P a g e


6. Wait for 1 second
7. Make the RGB LED emit blue color by sending a value of 0,255,0 to the redPin, greenPin and
bluePin respectively
8. Wait for 1 second
9. Make the RGB LED emit blue color by sending a value of 0,255,0 to the redPin, greenPin and
bluePin respectively
10. Wait for 1 second
Code Explained

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
*/

Adding a single line comment uses //


// red

We then have the declaration of variables.


int redPin = 11;
int greenPin = 10;
int bluePin = 9;

And setting up the digital Pins involved.


void setup()
{
pinMode(redPin, OUTPUT);
pinMode(greenPin, OUTPUT);
pinMode(bluePin, OUTPUT);
}

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.

BITSTOC ELECTRONICS www.bitstoc.com 39 | P a g e


Declaring parameters allow us to make use of arguments when calling the said function. This means that
we can process values that are inputted to the said function. Making use of the code, the setColor()
function is a form of function with declared parameters.
void setColor(int red, int green, int blue)
{
analogWrite(redPin, red);
analogWrite(greenPin, green);
analogWrite(bluePin, blue);
}

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.

BITSTOC ELECTRONICS www.bitstoc.com 40 | P a g e


EXPERIMENT 4
Analog Input and Potentiometer

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

In this Experiment we will discuss the following.


 Engineering Concept: Analog signals, Analog Input, concepts on Serial programming and devices
 Electronics component: Potentiometer
 Programming tool and function: analogRead(), Serial(), Serial.println(), Arduino Serial Monitor

BITSTOC ELECTRONICS www.bitstoc.com 41 | P a g e


Parts you will need

Arduino UNO R3 USB Cable (USB-A to USB-B) Potentiometer – 10k Ohm


(1 unit) (1 unit) (1 unit)

Breadboard Connecting wires


(1 unit) 1 (Red), 1(Black), 1(Green)

Concepts & Vocabulary


Analog Signal – signal whose values are not just LOW or HIGH, but a range of values. This could be from
0-100, 0-1023 or even 0-1 including values in between (0.001, 0.0001)
Analog to Digital Conversion/Converter (ADC) – A method of converting analog signals to digital format.
ASCII - stands for American Standard Code for Information Interchange. It is a coding standard for
electronic communication. It provides standards for transmission of data between devices to be
translated as readable human language.
Potentiometer - A potentiometer is a simple knob that provides a variable resistance, which we can
read into the Arduino board as an analog value. In this example, that value controls the rate at which an
LED blinks. This potentiometers can be found in your audio equipment’s volume or channel control and
in many other devices.

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().

BITSTOC ELECTRONICS www.bitstoc.com 42 | P a g e


The Arduino Hardware Circuit

Figure A Figure B

Construct the Circuit in Figure A. Your circuit would look as shown in Figure B.

Hardware Circuit Explained

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.

BITSTOC ELECTRONICS www.bitstoc.com 43 | P a g e


The Arduino Software Code
1) Open the Arduino Software IDE. Go to File>New to create a new programming window.

2) Type the Arduino Code below to your Arduino IDE. (Or copy and paste it to the Arduino IDE)

/*
Potentiometer and Analog Inputs
*/

// assign Arduino Pin for reading the Analog Voltage


// declare variable readInput for the output reading from 0 - 1023
int potentiometerPin = 0;
int readInput = 0;

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”.

BITSTOC ELECTRONICS www.bitstoc.com 44 | P a g e


New Programming Tool!

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.

The Arduino Serial Monitor tool

BITSTOC ELECTRONICS www.bitstoc.com 45 | P a g e


The Experiment Output
After the code is successfully uploaded, the Serial Monitor gives an output from 0 as the minimum and
1,010 as the maximum value. These two values are obtained by rotating the knob fully counterclockwise
(going to the black line) and clockwise (going to the red line) respectively.

(value approaching to 0 when knob turn to the


black-wire side)

(value approaching to 1010 (~1023) when knob turn to the


red-wire (positive) side)

Learn about the Code!

Programming commands (syntax)

 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.

BITSTOC ELECTRONICS www.bitstoc.com 46 | P a g e


Code Sequence
1. Read analog value (0V to 5V to 0 to 1023 range) of potentiometer.
2. Store read value into readInput variable.
3. Send to serial monitor the value of readInput and print it.
4. Wait for two hundred milliseconds.
5. Repeat from the start of the loop() function.

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?

BITSTOC ELECTRONICS www.bitstoc.com 47 | P a g e


EXPERIMENT 5
Light Sensor – LDR (Light Dependent Resistor)

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

In this Experiment we will discuss the following.

 Engineering Concept: Sensors, Light Sensor, Voltage Divider


 Electronics component: LDR (Photocell/Photoresistor)
 Programming: using math/mathematical operators

BITSTOC ELECTRONICS www.bitstoc.com 48 | P a g e


Parts you will need

Arduino UNO R3 USB Cable (USB-A to USB-B) LDR (Photocell)


(1 unit) (1 unit) (1 unit)

Breadboard Connecting wires Resistor (10k ohms)


(brown/black/orange)
(1 unit)

LED (Red) Resistor (330 ohms)


(1 unit) (1 unit)

Concepts & Vocabulary


Sensors – A component or electronic device that measures one form of energy (like light or heat or
mechanical energy) and converts it to voltage or current.
Voltage Divider – A type of circuit that provides an output that is a fraction of its input voltage. You are
building a voltage divider when you combine a photoresistor (LDR) with a fixed resistor to provide an
analog input. A potentiometer can also be used as a voltage divider.
Photoresistor or light-dependent resistor (LDR) or photocell - is a light-controlled variable resistor. The
resistance of a photoresistor decreases with increasing incident light intensity; in other words, it exhibits
photoconductivity. A photoresistor can be applied in light-sensitive detector circuits, and light- and dark-
activated switching circuits. This component has 2 pin but is not polarized (can be connected in any
direction).

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.

BITSTOC ELECTRONICS www.bitstoc.com 49 | P a g e


The Arduino Hardware Circuit

Fig. 1A Fig. 1B

Construct the Circuit in Figure A. Your circuit would look as shown in Figure B.

Hardware Circuit Explained

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.

BITSTOC ELECTRONICS www.bitstoc.com 50 | P a g e


The Arduino Software Code
1) Open the Arduino Software IDE. Go to File>New to create a new programming window.

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)
*/

//assign variables to use for the program


int lightPin = 0; //pin for the LDR Photo resistor
int ledPin = 12; //pin for LED
int lightValue = 0; //variable to assign for the value of the light represented by the LDR
// the setting up of pins.

void setup()
{
Serial.begin(9600); //Begin serial communcation
pinMode(ledPin, OUTPUT); // initialize the "ledPin (arduino pin 12) as an output.
}

// the loop is where your program runs repeatedly.


void loop()
{
// Read the value from the analog pin "lightPin" where the LDR is connected
// and print to the Serial monitor
lightValue = analogRead(lightPin);
Serial.println(lightValue);
// The reading will not reach 0 or 1024, it will be from around 16 (brightest) and 970 (dar
kest)
// because of the internal resistance of the resistor and LDR.

// 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.

BITSTOC ELECTRONICS www.bitstoc.com 51 | P a g e


The Experiment Output
Run the program and open your Arduino Serial Monitor.

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.

Bright light or room light is


On, the Resistance is Low.

So, below 500 is bright room,


the LED is Off.

Low Light/dark or room light


is Off, Resistance is High.

So, above 500 is dark room,


the LED is On.

Learn about the Code!


Programming concept

 Operators (Mathematical) – these are symbols that behave like functions, but differ in syntax or
form. This includes +, -, *, /, =, >, <, !.

Programming commands (syntax)

 > - 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”.

BITSTOC ELECTRONICS www.bitstoc.com 52 | P a g e


Code Sequence
1. Set ledPin as output
2. Read value from LDR and store it to variable lightvalue
3. Compare lightvalue to set condition
4. If lightvalue is greater than 500, LED goes on
5. If lightvalue is less than 500, LED goes off.
6. Repeat step 2 and onwards.

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?

BITSTOC ELECTRONICS www.bitstoc.com 53 | P a g e


EXPERIMENT 6
Creating Sounds and Tones with Piezo Speaker (Buzzer)

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

In this Experiment we will discuss the following.


 Interfacing a Piezo Speaker (tone adjustable buzzer) with Arduino
 Creating tones
 Using the programming data type – Array and programming structure “for loop”

BITSTOC ELECTRONICS www.bitstoc.com 54 | P a g e


Parts you will need

Arduino UNO R3 USB Cable (USB-A to USB-B) Piezo Speaker (Buzzer)


(1 unit) (1 unit) (1 unit)

Breadboard Connecting wires


(1 unit) 1(Black), 1(Green)

Concepts & Vocabulary


Programming Concept (Data Type: Array) – An array is a group of variables that are identified by one
name, and accessed by an index number. Arrays in the C programming language, on which Arduino is
based, can be complicated, but using simple arrays is relatively straightforward.
Say for the example below:
int mySensVals[6] = {2, 4, -8, 3, 2};

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.

int – variable type.

mySensVals – variable name

[6] – array size

{2, 4, -8, 3, 2} – elements

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.

Learn more about Array and for: loop through here:


https://www.arduino.cc/reference/en/language/variables/data-types/array/
https://www.arduino.cc/reference/en/language/structure/control-structure/for/

BITSTOC ELECTRONICS www.bitstoc.com 55 | P a g e


Piezo Speaker (Buzzer) – is a sound source that uses piezoelectric effect for generating sound. A
mechanical motion is created by applying voltage to the piezoelectric material, this motion is then
converted into audible sound using diaphragms and resonators. A tone adjustable piezo buzzer is
polarized (+ and – pins are labeled, connec + to signal to the signal source and – to the Ground).

Piezo electric sound material housed piezo electric buzzer

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)

tone(pin, frequency, duration)

You may learn more about tone() function here:


https://www.arduino.cc/reference/en/language/functions/advanced-io/tone/

BITSTOC ELECTRONICS www.bitstoc.com 56 | P a g e


The Arduino Hardware Circuit

Fig. A Fig. B

Construct the Circuit in Figure A. Your circuit would look as shown in Figure B.

Hardware Circuit Explained

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.

BITSTOC ELECTRONICS www.bitstoc.com 57 | P a g e


The Arduino Software Code
1) Open the Arduino Software IDE. Go to File>New to create a new programming window.

2) Type the Arduino Code below to your Arduino IDE. (Or copy and paste it to the Arduino IDE)

/*
Project 6 - Buzzer (making sounds)
*/

//assign variables to use in our program


int buzzerPin = 8; //Arduino pin to connect the positive pin of buzzer
int listTones = 10; //number of tones we will play

//list of tones we will play which corresponds to


// C, C#, D, D#, E, F, F#, G, G#, A
int tones[] = {261, 277, 294, 311, 330, 349, 370, 392, 415, 440};

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.

BITSTOC ELECTRONICS www.bitstoc.com 58 | P a g e


The Experiment Output
The program starts to play the tones that we put in the tones[] array. 10 tones will be played
simultaneously with a 1 second delay after the last tone. The program plays back the first tone after the
last tone.

Learn about the Code!


Programming concept

 Array - a collection of variables that are accessed with an index number.

Programming commands/function (syntax)

 For(expression 1; expression 2; expression 3) – a form of a program loop function. Expression 1


initializes variables used in the loop function. Expression 2 sets the conditions for the loop to keep
executing. If this condition remains true, the loop keeps going. If not, the loop is ended. Expression 3
is the modifier which may be an increment or a decrement of a variable.
 Tone() - Generates a square wave of the specified frequency (and 50% duty cycle) on a pin. A duration
can be specified, otherwise the wave continues until a call to noTone(). The pin can be connected to a
piezo buzzer or other speaker to play tones. Only one tone can be generated at a time. If a tone is
already playing on a different pin, the call to tone() will have no effect. If the tone is playing on the
same pin, the call will set its frequency.
 noTone - Stops the generation of a square wave triggered by tone(). Has no effect if no tone is being
generated.

To learn more about the Arduino commands and syntax, go to https://www.arduino.cc/reference/en/

BITSTOC ELECTRONICS www.bitstoc.com 59 | P a g e


Code Sequence
1. Assign variable names to use and create a tone[] array (10 different tone frequencies)
2. Start using for:loop to create tone - Integer i is set to zero.
3. First tone plays for 0.5 seconds.
4. Integer i is incremented by one
5. Next tone is played for 0.5 seconds until the tenth tone.
6. After playing the the last tone, stop by calling noTone() command.
Code Explained

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?

BITSTOC ELECTRONICS www.bitstoc.com 60 | P a g e


EXPERIMENT 7
Temperature Sensing – LM35 Temperature Sensor

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

In this Experiment we will discuss the following.


 Engineering Concept: Sensors, Temperature sensing
 Electronics component: LM35 IC Analog Temperature Sensor
 Programming Data Type: float decimal numbers
 Arithmetic math function: multiplication (*)
 Electronics datasheet

BITSTOC ELECTRONICS www.bitstoc.com 61 | P a g e


Parts you will need

Arduino UNO R3 USB Cable (USB-A to USB-B) LM35 Temperature Sensor (Analog)
(1 unit) (1 unit) (1 unit)

Breadboard Connecting wires


(1 unit) 1(Black), 1(Green), 1)Red)

Concepts & Vocabulary


Data Type: float decimal number – A datatype used to represent a fraction. This entails the use of
decimal points for floating point numbers.
Arithmetic/Mathematical Operation: multiplication (*) – In programming, you can perform basic
mathematical operations: addition, subtraction, multiplication and division. The corresponding
operation for addition, subtraction, multiplication and division are +, -, * and / respectively.
Calibration – calibration is the process of comparing the measured values taken form a device under
test and comparing it with a value of known accuracy. This is to configure the device to work as
expected while minimizing errors.
Integrated Circuit – these are chips that are actually sets of electronic circuits miniaturized or compressed
into a small form factor. You can think of it as a basic electronic circuit, only made smaller. Integrated
circuits are made of resistors, capacitors, and transistors made for a specific purpose. In this experiment,
the LM35 is an example of an integrated circuit.
LM35 Temperature Sensor (Analog) – The LM35 is precision integrated-circuit centigrade temperature
sensor. This means that the LM35 is calibrated to send voltage readings that need to be translated or
interpreted in terms of Celsius, which is a unit of temperature. It is capable of reading from -55˚C up to
150 ˚C. The LM35 is 3 pin polarized, meaning the pins work in different manners must be connected right.

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:

BITSTOC ELECTRONICS www.bitstoc.com 62 | P a g e


5000 1˚𝐶
𝑐𝑜𝑟𝑟𝑒𝑐𝑡𝑖𝑜𝑛 𝑓𝑎𝑐𝑡𝑜𝑟 = (𝑉𝑜𝑙𝑡𝑎𝑔𝑒 𝑠𝑢𝑝𝑝𝑙𝑦 ∗ 1000 ∗ )( )
1024 10 𝑚𝑉

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.

BITSTOC ELECTRONICS www.bitstoc.com 63 | P a g e


The Arduino Hardware Circuit

Fig. A Fig. B

Construct the Circuit in Figure A. Your circuit would look as shown in Figure B.

Hardware Circuit Explained

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.

BITSTOC ELECTRONICS www.bitstoc.com 64 | P a g e


The Arduino Software Code
1) Open the Arduino Software IDE. Go to File>New to create a new programming window.

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
*/

//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
int temperaturesensorPin = 0; // use Arduino Analog pin 0 for temprature reading

void setup()
{
Serial.begin(9600); // call a serial monitor communication to view the readings
}

// the loop is where your program runs repeatedly.


void loop()
{
// First we get the value of the temperature read by the sensor
// from Arduino analog pin 0.
tempReading = analogRead(temperaturesensorPin);

// We multiply the resulting value of "tempreading" by .488


// to get the exact callibrated value of the temperature in degree Celsius.
correctTemperature = tempReading * 0.488;

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.
}

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.

BITSTOC ELECTRONICS www.bitstoc.com 65 | P a g e


The Experiment Output
Run the program and open the Arduino Serial Monitor (configurations of the Serial Monitor in the
bottom of the window: checked Autoscroll, Both NL&CR and 9600 baud). You should see the values of
the temperature in degrees Celsius print out in the Serial monitor. From the code above, the value will
be printed every 1 second.

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.

Learn about the Code!

Programming data type / variable

 float – numbers which are composed of decimal figures.

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.

BITSTOC ELECTRONICS www.bitstoc.com 66 | P a g e


Code Explained

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?

BITSTOC ELECTRONICS www.bitstoc.com 67 | P a g e


EXPERIMENT 8
Servo Motors

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

In this Experiment we will discuss the following.

 Understand what a servo motor is and how it works


 Use and manipulate the servo library & object.
 Programming concepts: “objects” and “methods”
 Programming concept: Importing libraries

BITSTOC ELECTRONICS www.bitstoc.com 68 | P a g e


Parts you will need

Arduino UNO R3 USB Cable (USB-A to USB-B) Servo Motor (SG90) micro – 180
(1 unit) (1 unit) degrees

Breadboard Connecting wires


(1 unit) 1 Red, 1 Orange, 1 Black

Concepts & Vocabulary


Programming (Programming Libraries / Arduino Libraries) – are files (of libraries) which provide your
code with additional functionality. This allows the Arduino boards to work with different modules,
systems and even microcontrollers. The servo makes use of such library, which is the Servo. To add and
use a separate library in your code, use/call the syntax below on the first line of your Arduino sketch.
#include <name of library.h>

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.

BITSTOC ELECTRONICS www.bitstoc.com 69 | P a g e


One cycle then is composed of one second of the LED being lit up and another second switched off. To
compute for the duty cycle,
𝑡𝑖𝑚𝑒 𝑠𝑦𝑠𝑡𝑒𝑚 𝑖𝑠 𝑜𝑛
𝐷𝐶 = ∗ 100%
𝑡𝑜𝑡𝑎𝑙 𝑝𝑒𝑟𝑖𝑜𝑑 𝑜𝑓 𝑠𝑦𝑠𝑡𝑒𝑚

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.

BITSTOC ELECTRONICS www.bitstoc.com 70 | P a g e


The Arduino Hardware Circuit

Figure A Figure B

Construct the Circuit in Figure A. Your circuit should look as shown in Figure B.

Circuit Connection Guide


Servo pin Brown (GND) to Arduino GND
Servo pin Orang (VCC) to Arduino 5V
Servo pin Yellow (PWM) to Arduino PWM pin D9

Hardware Circuit Explained

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).

BITSTOC ELECTRONICS www.bitstoc.com 71 | P a g e


The Arduino Software Code
1) Open the Arduino Software IDE. Go to File>New to create a new programming window.

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.

BITSTOC ELECTRONICS www.bitstoc.com 72 | P a g e


The Experiment Output
Run the program and you should see that the servo motor turns from 0 to 180 degrees and then turns
back to 180 to 0 degrees.

Learn about the Code!


Programming commands (syntax) and functions

 #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.

BITSTOC ELECTRONICS www.bitstoc.com 73 | P a g e


3. First loop begins. Using for:loop set value variable pos (as position) to 0. Servo motor rotates
according to the value written for variable pos every 15 milliseconds. Value of pos increases by
one after completion of each loop.
4. When variable pos reaches to 180, the first loop ends
5. Second for:loop begins. Set value of variable pos to 180. Servo motor rotates according to the
value written for variable pos every 15 milliseconds. Value of pos decreases by one after
completion of each loop.
6. When variable pos reaches to 0, the second loop ends, and the loop() function loops back to the
first line, first for:loop runs again.

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?

BITSTOC ELECTRONICS www.bitstoc.com 74 | P a g e


EXPERIMENT 9
Displaying characters & texts with LCD Display

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

In this Experiment we will discuss the following.


 Engineering Concept: Programming Libraries (external libraries)
 Electronics component: LCD (Liquid Crystal Display) Character Module
 Using the LiquidCrystal Arduino library

BITSTOC ELECTRONICS www.bitstoc.com 75 | P a g e


Parts you will need

Arduino UNO R3 USB Cable (USB-A to USB-B) LCD Display Module – 2x16
(1 unit) (1 unit) Characters (1 unit) (to obtain separately)

Breadboard Connecting wires Potentiometer – 10k Ohm


(1 unit) (1 unit)

Resistor (220 ohms)


(red/red/brown) (to obtain separately) (or may use the 330ohm instead)

Concepts & Vocabulary


Character LCD Display Module (with 2x16 Characters) – LCD stands for Liquid Crystal Display. These are
relatively cheap displays that offer greater flexibility versus seven segment LED displays. They are used
as external displays for texts, data or value. The LCD module used in this experiment is a 16x2 LCD
module, meaning it can display 16 characters per line, with 2 available lines. The LCDs come in many
sizes such as 2x16, 4x20 and many other.

Below is a table of the pin assignment of an LCD module.

Pin Symbol Function


1 Vss Ground
2 Vdd +5V logic supply voltage
3 Vo Display contrast adjustment
4 RS Register Select
5 R/W Read/Write
6 E Enable
7-14 D0-D7 Data bus for 4-bit (D4-D7) mode or 8-bit mode (D0-D7)

BITSTOC ELECTRONICS www.bitstoc.com 76 | P a g e


15 A Backlit anode (v+)
16 K Backlit cathode (Gnd)

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).

BITSTOC ELECTRONICS www.bitstoc.com 77 | P a g e


The Arduino Hardware Circuit

Fig. A Fig. B

Construct the Circuit in Figure A. Your circuit would look as shown in Figure B.

Circuit Connection Guide:


 LCD pin 1 (VSS) to Common GND
 LCD pin 2 (VDD) to 5V+
 LCD pin 3 (V0) to Center of potentiometer
 LCD pin 4 (RS) to Arduino pin 12
 LCD pin 5 (RW) to GND
 LCD pin 6 (E/Enable) to Arduino pin 11
 LCD pin 7-10 (D0-D3) no connection
 LCD pin 11 (D4) to Arduino pin 5
 LCD pin 12 (D5) to Arduino pin 4
 LCD pin 13 (D6) to Arduino pin 3
 LCD pin 14 (D7) to Arduino pin 2
 LCD pin 15 (A,Anode) to 330 ohm or 220 ohm resistor to 5V+
 LCD pin 16 (K,Cathode) to GND
*one side of potentiometer to 5V+ and one side to GND

BITSTOC ELECTRONICS www.bitstoc.com 78 | P a g e


Schematic Diagram (electrical connection drawing) for Arduino LCD Display circuit

Hardware Circuit Explained

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.

BITSTOC ELECTRONICS www.bitstoc.com 79 | P a g e


The Arduino Software Code
1) Open the Arduino Software IDE. Go to File>New to create a new programming window.

2) Type the Arduino Code below to your Arduino IDE. (Or copy and paste it to the Arduino IDE)

/*
Project 8 - LCD Display
*/

// We use the "#include" command to use an LCD library "LiquidCrystal.h"


// Always include this line when using an LCD display
#include <LiquidCrystal.h>

// An LCD needs some initialization pins, from the Arduino board


// we use the pins listed in the "lcd()" function below
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

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.

BITSTOC ELECTRONICS www.bitstoc.com 80 | P a g e


The Experiment Output
Compile and Upload the program. Start and you will see on the first line a text “Hello, World!” and on
the second line is an increasing count of number in seconds from which you started or reset the Arduino
board.

Learn about the Code!


Programming command / function

 LiquidCrystal.h – a library that contains the functions and syntax to control LCD modules. This
includes instantiating variable names and printing texts.

Programming commands (syntax)

 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.

BITSTOC ELECTRONICS www.bitstoc.com 81 | P a g e


Code Explained

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?

BITSTOC ELECTRONICS www.bitstoc.com 82 | P a g e


EXPERIMENT 10
DC Motors

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

In this Experiment we will discuss the following.


 Electronics component: DC Motor, Transistors, Diode,
 Motor circuit design
 Programming functions Serial.available(), Serial.parseInt() and boolean operator “&&”
 Interaction and inputting data with the Serial Monitor

BITSTOC ELECTRONICS www.bitstoc.com 83 | P a g e


Parts you will need

Arduino UNO R3 USB Cable (USB-A to USB-B) DC Motor


(1 unit) (1 unit) (1 unit)

Breadboard Diode (signal diode)


(1 unit) Connecting wires (1 unit)

Resistor (330 ohms Transistor (NPN) – 2N2222


(orange/orange/brown) (1 unit) (2N2222 markings) (1 unit)

Concepts & Vocabulary


DC (Direct Current) – the flow of electric current or electric charge in one direction only. A good
example is a battery as a source of DC power supply.
DC Motor (Direct Current Motor) – is any class of rotating electrical machine that converts direct current
electrical energy to mechanical energy. The most common type of DC motors operates on the concept of
magnetic fields for converting electrical energy to mechanical energy.

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.

BITSTOC ELECTRONICS www.bitstoc.com 84 | P a g e


Transistor – an electronic device (an IC integrated circuit) that can be used as signal amplifier or as an
electronic switch for electrical signals. It has three terminals, which are the emitter, base, and collector
respectively. There are different types of transistors that exist today, but for this discussion the transistor
in the experiment will be used as a switch. This would allow us to control the speed of the DC motor by
controlling the switching speed of the transistor using PWM. In this experiment our transistor is the NPN
Transistor 2N2222.

2N2222 IC 2N2222 pinout diagram NPN Transistor Symbol

Full 2N2222 datasheet here: https://datasheetspdf.com/pdf-file/1129135/SEMTECH/2N2222/1

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.

BITSTOC ELECTRONICS www.bitstoc.com 85 | P a g e


The Arduino Hardware Circuit

“2N2222 flat side


facing out”
Figure A Figure B

Construct the Circuit in Figure A, your circuit would look something as shown in Figure B.

Hardware Circuit Explained

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.

BITSTOC ELECTRONICS www.bitstoc.com 86 | P a g e


The Arduino Software Code
1) Open the Arduino Software IDE. Go to File>New to create a new programming window.

2) Type the Arduino Code below to your Arduino IDE. (Or copy and paste it to the Arduino IDE)

/*
Project 10 - DC Motor
*/

// assign variable for the arduino pin connected to DC motor


int motorPin = 9;
// the setting up of pins.

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.

BITSTOC ELECTRONICS www.bitstoc.com 87 | P a g e


The Experiment Output
Run the program and open the Arduino Serial Monitor. Type a value to set a speed for the dc motor. The
DC motor minimum voltage supply is around 3V, which is around 150 (using the range 0 to 255). Using
values around 150 and below will not start the motor, using value around 150 (approximately 3V) the
motor starts to spin. Type in value from 150 to 255 (3V to VCC 5V) then hit “Enter” or click Send button.
The DC motor spins fast when the value is at 255 and get slower spin if set below of 255.

Learn about the Code!


Programming commands (syntax)

 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.

BITSTOC ELECTRONICS www.bitstoc.com 88 | P a g e


Code Explained

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
*/

// assign variable for the arduino pin connected to DC motor


int motorPin = 9;

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()
{

BITSTOC ELECTRONICS www.bitstoc.com 89 | P a g e


int Run = 2000; // milliseconds to turn the motor on
int Stop = 2000; // milliseconds to turn the motor off
digitalWrite(motorPin, HIGH); // turn ON the DC motor
delay(Run); // delay for 2000 mS (2 seconds)
digitalWrite(motorPin, LOW); // turn OFF the DC motor
delay(Stop); // delay for 2000 mS (2 seconds)
}

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?

Congratulations! You have officially learned Arduino. It’s time to combine


Arduino Programming and Circuit design skills.
Let’s build a full project!

BITSTOC ELECTRONICS www.bitstoc.com 90 | P a g e


PROJECT CIRCUIT 1
Automation – Temperature Controlled Fan

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

Arduino UNO R3 USB Cable (USB-A to USB-B) DC Motor


(1 unit) (1 unit) (1 unit) Resistor (330 ohms)
(3 unit)

BITSTOC ELECTRONICS www.bitstoc.com 91 | P a g e


Breadboard Connecting wires Diode (signal diode) Transistor NPN 2N2222
(1 unit) (1 unit) (1 unit)

LED (red) LED (green) Resistor (10k ohms) LM35 Sensor


(1 pc) (1 pc) (1 pc) (1 pc)

Additional parts you may need:


Small carton (to serve as a fan blade)
Glue
Scissors

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.

The Arduino Hardware Circuit


Wire your circuit as shown below. Zoom in to clearly see the correct wiring.

LM35 temperature
IC (flat side in front)

2N2222 Transistor (flat side facing front)

BITSTOC ELECTRONICS www.bitstoc.com 92 | P a g e


Actual circuit may look like this.

Now cut out a small paper/carton and attach it to the end of the DC motor to serve as your fan blade.

BITSTOC ELECTRONICS www.bitstoc.com 93 | P a g e


The Arduino Code
In your Arduino IDE go to File>New to create a new programming window. Type the Arduino Code
below to your Arduino IDE. (Or copy and paste it to the Arduino IDE)

// 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

float tempReading; // use a float variable tempReading for decimal reading


float correctTemperature; // use a float variable correctTemperature for decimal 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);
}

Now Verify and Upload the code to your Arduino board.

BITSTOC ELECTRONICS www.bitstoc.com 94 | P a g e


Your Project Output
After uploading, open the Arduino Serial Monitor and the room temperature will start to display on the
screen.

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.

BITSTOC ELECTRONICS www.bitstoc.com 95 | P a g e


Now change the temperature value correctTemperature for hot and cold comparison that fits for your
current room environment.

Our Code Sequence goes like this:


1. Monitoring of temperature from LM35 sensor occurs.
2. Data coming from LM35 sensor is calibrated, corrected and stored to variable
correctTemperature.
3. Comparison of value from correctTemperature and the threshold temperature (set to 30˚C)
4. Response according to the comparison. If it is below 30˚C, the “COLD!” text appears on the serial
monitor, green LED lit up and the DC motor does not run. If it is above 30˚C, the “HOT!” text
appears on the serial monitor, red LED lit up and the DC motor runs.
5. Code cycles back to monitoring of temperature.

BITSTOC ELECTRONICS www.bitstoc.com 96 | P a g e


Code Explained

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.

BITSTOC ELECTRONICS www.bitstoc.com 97 | P a g e


PROJECT CIRCUIT 2
Traffic Lights System

Overview

Want to create your own traffic light system?

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

Arduino UNO R3 USB Cable (USB-A to USB-B) Tactile Switch


(1 unit) (1 unit) (1 unit) Resistor (330 ohms)
(3 unit)

BITSTOC ELECTRONICS www.bitstoc.com 98 | P a g e


Breadboard Connecting wires LED – Orange/Yellow (5mm) LED (green)
(1 unit) (1 unit) (1 pc)

LED (red) Resistor (10k ohms)


(brown/black/orange)
(1 pc)

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.

BITSTOC ELECTRONICS www.bitstoc.com 99 | P a g e


The Arduino Hardware Circuit
Wire your circuit as shown below.

Your actual circuit.

BITSTOC ELECTRONICS www.bitstoc.com 100 | P a g e


The Arduino Code
In your Arduino IDE go to File>New to create a new programming window. Type the Arduino Code
below to your Arduino IDE. (Or copy and paste it to the Arduino IDE)

/*
* Traffic Light System Code
* by Bitstoc Electronics
* February 2019
*/

//variables for Traffic Light 1


int greenLight1 = 5;
int orangeLight1 = 6;
int redLight1 = 7;

//variables for Traffic Light 2


int greenLight2 = 11;
int orangeLight2 = 12;
int redLight2 = 13;

//variables for Traffic Light Switches 1 and 2


int TRAFFIC1button = 3;
int TRAFFIC2button = 2;

//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);

//setting up Traffic 2 Lights as OUTPUT


pinMode(greenLight2, OUTPUT);
pinMode(orangeLight2, OUTPUT);
pinMode(orangeLight2, OUTPUT);

//setting up Traffic Light Switches as INPUT


pinMode(TRAFFIC1button, INPUT);
pinMode(TRAFFIC2button, INPUT);

//setting up inital state of traffic lights


goTrafficLight2();
}

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

//read state of Switch 1 and store it in variable TLIGHT1trigger


int TLIGHT1trigger = digitalRead(TRAFFIC1button);

//read state of Switch 2 and store it in variable TLIGHT2trigger


int TLIGHT2trigger = digitalRead(TRAFFIC2button);

//triggers when Traffic1 button is pressed (to LOW) and Traffic2button is not pressed
if (TLIGHT1trigger == LOW && TLIGHT2trigger == HIGH)
{
currenterror = 1;

BITSTOC ELECTRONICS www.bitstoc.com 101 | P a g e


if(currenterror != previouserror)
{
goTrafficLight2();
delay(lightpause);
SwitchTrafficLight();
delay(lightpause);
goTrafficLight1();
}
previouserror = currenterror; //previouserror value turns to 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);
}

Now Verify and Upload the code to your Arduino board.

BITSTOC ELECTRONICS www.bitstoc.com 102 | P a g e


Your Project Output
How it works: Left push button is for left traffic light trigger and the right push button is for the right
traffic light trigger. Pressing the button will emulate a car is present in the designated lane. If a car is
present (first button is pressed on either one) this lane goes green while the other is red.

Once the program starts, Traffic2 (Left) is GO (green) first while Traffic1 (Right) is STOP (Red).

Right Button (TRAFFIC1) is pressed, both light lane goes yellow.

BITSTOC ELECTRONICS www.bitstoc.com 103 | P a g e


Then Right Lane TRAFFIC 1 goes GREEN!

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.

BITSTOC ELECTRONICS www.bitstoc.com 104 | P a g e


Code Sequence
1. Left traffic light (TRAFFIC2) starts Go (green) first.
2. Check if any of the push button is pressed.
3. Create two separate code function for left and right traffic push buttons. Each have their own
designated traffic sequence when it is Go or Stop.
These two conditions uses the currenterror and previouserror variables to check if the state is
already running or not. Green (Go) side should not run any code if designated button is pressed.
Red (Stop) side should run its Go code if the designated button is pressed and at the same time
the Go (green) side will run it Stop (red) code.
4. The code cycles, and monitoring of status of the two pushbuttons happens again.
5. Create three separate code functions to call for use. These are goTrafficLight1(),
SwitchTrafficLight() and goTrafficLight2().

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();
}

The state of the two buttons, TRAFFIC1button and TRAFFIC2button is monitored.


//read state of Switch 1 and store it in variable TLIGHT1trigger
int TLIGHT1trigger = digitalRead(TRAFFIC1button);

//read state of Switch 2 and store it in variable TLIGHT2trigger


int TLIGHT2trigger = digitalRead(TRAFFIC2button);

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)
{

BITSTOC ELECTRONICS www.bitstoc.com 105 | P a g e



}

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:

goTrafficLight2() - Go (Green) TRAFFIC2 and Stop (Red) TRAFFIC1


then, delay 1 second
then, SwitchTrafficLight - both TRAFFIC1 and TRAFFIC 2 goes yellow
then, delay 1 second
then, goTrafficLight1() - Go (Green) TRAFFIC1 and Stop (Red) TRAFFIC2
then, set state checker variable previouserror to have equal value of the currenterror, which is 1.
//triggers when Traffic1 button is pressed (to LOW) and Traffic2button is not pressed
if (TLIGHT1trigger == LOW && TLIGHT2trigger == HIGH)
{
currenterror = 1;
if(currenterror != previouserror)
{
goTrafficLight2();
delay(lightpause);
SwitchTrafficLight();
delay(lightpause);
goTrafficLight1();
}
previouserror = currenterror; //previouserror value turns to 1
}

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:

goTrafficLight1() - Go (Green) TRAFFIC1 and Stop (Red) TRAFFIC2


then, delay 1 second
then, SwitchTrafficLight - both TRAFFIC1 and TRAFFIC 2 goes yellow
then, delay 1 second
then, goTrafficLight2() - Go (Green) TRAFFIC2 and Stop (Red) TRAFFIC1
then, set state checker variable previouserror to have equal value of the currenterror, which is 0.
//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
}

BITSTOC ELECTRONICS www.bitstoc.com 106 | P a g e


}

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);

BITSTOC ELECTRONICS www.bitstoc.com 107 | P a g e


}

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?

BITSTOC ELECTRONICS www.bitstoc.com 108 | P a g e


Appendix A
Arduino and Base Holder plate Assembly Guide

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.

2. Position the plate in this orientation, note the


small hole's location.

6. Insert the screws with the screw heads at the


top. Do this on all of the four sides of the
Arduino and the holes.

3. The orientation and alignment for the plate


to the Arduino and breadboard is:

4. Get the plastic ring spacer and place it on top


of the 4 holes.
7. Now hold them and lift up. Get the small nuts
then insert, turn and tighten. Do this on all of
the four sides. You may also use a screw driver
to tighten.

BITSTOC ELECTRONICS www.bitstoc.com 109 | P a g e


10. In this orientation (note where the
breadboard’s + red, - blue, 1, 30, a and i are
located), attach the breadboard onto the plate.
Press to breadboard to tighten. This orientation
will help you have more organized wiring. You
may want to also attach the breadboard in your
own orientation.

8. Get the rubber guards and stick them on all


of the four corners at the bottom.
Now your Arduino and Breadboard plate
platform will look like this.

9. Now, peel off the breadboard’s adhesive


cover at the bottom.

BITSTOC ELECTRONICS www.bitstoc.com 110 | P a g e


REFERENCES AND
RESOURCES
Arduino Programming Language commands and syntax detailed discussions
https://www.arduino.cc/reference/en/

List of Engineering, Electronics and Programming terms explained


https://www.arduino.cc/glossary/en/

List of other Arduino Libraries, extra codes bundled to use for other projects
https://www.arduino.cc/en/Reference/Libraries

Other Arduino Final Project inspiration


https://create.arduino.cc/projecthub
https://www.instructables.com/id/Arduino-Projects/
https://www.hackster.io/arduino/projects
https://maker.pro/arduino/projects

BITSTOC ELECTRONICS www.bitstoc.com 111 | P a g e

You might also like