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

PROJECT-IN-A-BOX

INTRODUCTION TO ARDUINO

DEVELOPERS: Tommy Truong, Phuong Truong, Jonathan Guerrero, and Jesse Soto
ADVISOR: Professor Truong Nguyen, ECE
PROJECT SEQUENCE: Introduction to Arduino
LAST UPDATED: 11/20/20
REQUIRED DOWNLOADS / INSTALLATION

1. Latest version of Arduino: https://www.arduino.cc/en/Main/Software


2. Latest version of Sublime Text Editor: https://www.sublimetext.com/
3. Quick Reference Guide: https://sites.google.com/a/eng.ucsd.edu/arduino101/home-1

A NOTE FROM THE DEVELOPERS

Dear Students,

This introduction to Arduino is a culmination of various open source circuits that the PiB team has collected
over the years as a repository of projects that will help you acclimate to the project building environment and
Arduino platform. We really hope you enjoy our collection of circuits! As always, have fun!

Sincerely,
P.I.B. Team

PROJECT-IN-A-BOX 2
INTRODUCTION

In this project, students will build a series of circuits that help them acclimate to the Arduino environment. They
will begin with a simple LED circuit and learn to build more creative circuits along the way! The intent behind
this project is to allow students to learn how to program in Arduino C and learn the basics of circuits.

OVERALL LEARNING OBJECTIVES

• Basic Circuits
• Building Libraries
• Learning Arduino C

REQUIRED PROJECT PARTS (ALL)

Part Name

1. Arduino Uno
2. A to B Cable
3. Resistor Packet; Resistors (10kΩ, 330Ω)
4. Breadboard
5. LEDs
6. RGB LED
7. Photo-resistor
8. Soft Potentiometer
9. Knob Potentiometer
10. Push Button

REQUIRED PROJECT TOOLS/EQUIPMENT

• Laptop Computer with Arduino IDE installed

PROJECT-IN-A-BOX 3
CHALLENGE #1: READING RESISTOR VALUES
Objective: In this challenge, we are going to learn a bit about resistance and how to read values from a
resistor value. Using the color code below, find out the resistance of an unknown resistor with the
following band colors: orange, orange, brown, gold

In short, a resistor is an electrical component that limits or regulates the flow of electrical current in an
electronic circuit. Its unit is ohm and the symbol is Ω. In electronics, sometimes we are provided a certain
voltage and would like to reduce current flow into our electrical components to prevent damaging the parts.

In order to read resistor values we must follow a color code based on the bands on the resistor:

Using the diagram above, you look at the color codes to help you determine the resistance value of your
resistor and its tolerance.

What’s the resistance of the unknown resistor above and its corresponding tolerance?

_______________ _______________ x _______________ ± _______________


st nd
1 Band Value 2 Band Value Multiplier Tolerance %

_________________________________________ ____________ ± _______________


Resistance Value Units Tolerance

Tolerance can be found by multiplying the resistance value with the tolerance percentage (.05 for gold and
.10 for silver).

To read more about resistors, visit this website: http://www.explainthatstuff.com/resistors.html

PROJECT-IN-A-BOX 4
CHALLENGE #2: SYMBOLS
Objective: A big part of electrical engineering is being understand the language and symbols that are used in
the field. In this challenge, you will learn about the symbols necessary to understand circuit schematics.

Based on your understanding of the symbols above, label the circuit schematic below:

PROJECT-IN-A-BOX 5
CHALLENGE #3: BLINKING LED
Objective: You are going to create a simple circuit using an LED light. The
goal is to have the LED light turn on for 2 seconds, and then turn off for 1
second.

Components:
1. 1 Arduino UNO
2. 1 Breadboard
3. 2 wires (choose one black for GROUND, and the other is any color)
4. 1 resistor (330 ohms)
5. LED light

Wiring: Using the circuit diagram provided, wire the Arduino.

Note: For the LED light, shorter leg goes to GND (ground), and longer leg goes to a pin. Ground is the
reference point in an electrical circuit which voltages are measured (usually zero).

Coding/Programming: Open the Arduino IDE software and write the following code:
// assign a value of your choice to the integer variable led
int led = ________;

// setup() function runs once when the Arduino turns on or is reset


void setup() {
// initialize the digital pin as output.
// assign variable led as this output
pinMode(led, OUTPUT);
}

// loop() function runs the code inside repeatedly while Arduino is still on
void loop() {
digitalWrite(led, HIGH); // turn the LED on (HIGH is the voltage level)
delay(2000); // wait for two seconds
digitalWrite(led, LOW); // turn the LED off by making the voltage LOW
delay(1000); // wait for a second
}

Note: Everything behind these slashes // are just comments, not actual code. The // indicates that everything
after it will be seen as a comment and ignored by the compiler in the Arduino software.

Terminology:
LED (Light Emitting Diode): A diode is a device that only allows for the flow of electricity to pass in one
direction. It has a cathode/negative (-) lead and an anode/positive (+) lead. An LED is a diode that generates
a specific wavelength of light when a voltage is applied across its leads.
digitalWrite(): Is a built in function that outputs to a specific pin to turn something ON (HIGH) OR OFF (LOW).
In Arduino Coding, HIGH translates to ON and LOW translates to OFF.
pinMode(): Is a built in function that initializes a pin as an input or output (default is output). Meaning, it tells
the ARDUINO, “Hey! This pin will be your target for input or output!”
delay(): Is a built in function that does what the name says: delays. It stops everything in the Arduino and holds
for however many milliseconds specified. In the code above, the LED is turned on with digitalWrite, then, delay
of two seconds occurs, then digitalWrite turns the LED off, and the delay of one second occurs before looping
back up. Normally, depending on the circuit, a delay will be problematic for sensors because once a delay
occurs, this stops everything in the Arduino, including the reading of data.

PROJECT-IN-A-BOX 6
CHALLENGE #4: SCHEMATIC VS. DIAGRAM
Objective: Congratulations! You just completed a challenge. Let’s tie it back to the symbols you’ve learned.
We need to understand the difference between a schematic and a diagram. Your objective is to label the
schematic based on the diagram.

Current flow in
closed loop

A1 A2

Schematic Diagram

What are the two unknown components in the schematic? Do they agree with the diagram?

A1: _______________________________________

A2: _______________________________________

PROJECT-IN-A-BOX 7
CHALLENGE #5: ELECTRONIC DIE
Objective: Our goal is to light one of six LEDs
randomly to mimic the throw of a die. We’ll choose a
random number between 1 and 6, and then turn on the
corresponding LED to indicate the result. We’ll create a
function to select one of six LEDs on the Arduino
randomly and to keep the LED on for a certain period
of time. When the Arduino running the sketch is turned
on or reset, it should rapidly show random LEDs for a
specified period of time and then gradually slow until
the final LED is lit. The LED matching the resulting
randomly chosen number will stay on until the Arduino
is reset or turned off (this circuit is an excerpt from the
book Arduino Workshop by John Boxall).

Components:
1. 6 LEDs of any color
2. 1 resistor (330 ohm)
3. Jumper Wires
4. 1 Breadboard
5. Arduino and USB Cable

Wiring: Using the circuit diagram provided, wire the Arduino.

Terminology:

randomSeed(): initializes the pseudo-random number generator, causing it to start at an arbitrary point in its
random sequence. This sequence, while very long, and random, is always the same.

If it is important for a sequence of values generated by random() to differ, on subsequent executions of a


sketch, use randomSeed() to initialize the random number generator with a fairly random input, such as
analogRead() on an unconnected pin.

Conversely, it can occasionally be useful to use pseudo-random sequences that repeat exactly. This can be
accomplished by calling randomSeed() with a fixed number, before starting the random sequence.

PROJECT-IN-A-BOX 8
Coding/Programming: Open the Arduino IDE software and write the following code:

int randomval;
int LEDs;
int a;

void setup()
{
randomSeed( _______________ ); // seed the random number generator
for ( LEDs = 1 ; LEDs < 7 ; LEDs++ ) // LEDs on pins 1-6 are output
{
pinMode(LEDs, OUTPUT);
}
}

void randomLED(int del)


{

randomval = random( ______ , ______ ); // get a random number from 1 to 6


// output to the matching LED on digital pin 1-6
digitalWrite(randomval, HIGH);
if (del > 0)
{
delay(del); // hold the LED on for the delay received
}
else if (del == 0)
{
// the delay entered was zero, hold the LED on forever
do {}
while (1);
}
digitalWrite(randomval, LOW); // turn off the LED
}

void loop()
{
// cycle the LEDs around for effect
for ( a = 0 ; a < 100 ; a++ )
{
randomLED(50);
}
// slow down
for ( a = 1 ; a <= 10 ; a++ )
{
randomLED(a * 100);
}
// and stop at the final random number and LED
randomLED(0);
}

PROJECT-IN-A-BOX 9
CHALLENGE #6: BLINKING LED & BUTTON
Objective: Building from the last circuit
you’ve created, you are going to take what
you learned to construct a more complicated
circuit involving both a button and LED
(simply integrating a button circuit into the
existing LED circuit). The goal is to turn the
LED on and off at the press of a button.
When you press the button, the button stays
on, when you let go, it should stay off.

A button acts like a switch. When button is


pressed, the switch closes, forming a closed
circuit allowing current to flow through. When
the button is released, the circuit is when the
switch is open.

Components:
6. 5 wires (choose 2 black for GROUND, 2 red for 5V and the other any color)
7. 1 push button
8. 1 resistor (330 ohms)
9. Components from Challenge 3

Wiring: The beauty of the Arduino is the fact that it will allow you to integrate both circuits without needing to
disconnect the LED circuit. Using the circuit from the previous challenge, and the circuit in the figure, wire the
ARDUINO (essentially add the circuit on the right to the circuit from the previous example). You will not be
connecting the button and LED in series! They are two separate circuits communicating with each other
via the Arduino!

Coding/Programming: Open the Arduino IDE software and write the following code:

int buttonPin = ___________; // Set button pin


int ledPin = ___________; // Set LED pin
int buttonState; // Declare a buttonState

void setup(){
pinMode(buttonPin, INPUT); // Initialize button pin
pinMode(ledPin, ____________); // Initialize LED pin
}

void loop() {
buttonState = digitalRead(buttonPin); // Read whether or not the button is on or off
if (buttonState == 1){ // State of the button is either ON = 1, or OFF = 0
digitalWrite( ___________, ___________); // Turn LED on
}
else {
digitalWrite( ___________, ___________); // Turn LED off
}
}

Note: KEEP THE CIRCUIT!! DO NOT TAKE APART! YOU WILL NEED IT FOR CHALLENGE 8!

PROJECT-IN-A-BOX 10
CHALLENGE #7: HELLO, WORLD!

The serial monitor is a pop-up window that acts as a separate terminal that communicates by receiving and
sending Serial Data. Its job is to allow you to both send messages from your computer to an Arduino board
(over USB) and also to receive messages from the Arduino.

This challenge will make use of the serial monitor and allow you to print text. As indicated in the figure, to
access the text printed, click on the icon in the top right corner of the Arduino IDE (software interface). The
serial monitor will open as a new window if the Arduino is connected to the computer and there is text to
display. Make use of the serial monitor to view data or debug your program!

Objective: Using the following code, print the line “HELLO, WORLD!” into the serial port once, print an empty
line, and lastly, print the names of the members in your group repeatedly. No wiring of electrical components
is necessary in this challenge. You are simply going to connect the Arduino to the computer.

Begin by placing the following line in the void setup() function:

Serial.begin( 9600 );

This opens the serial line for data transmission via printing. The 9600 is the baud rate, which is the number of
bits per second being transferred to the serial line for printing (data transmission rate).

Serial.print(“_____________insert text_______________”);
// Prints the text between the quotation to the serial monitor

Serial.print(“\n”);

Note: The \n means “to the next line”. This is equivalent to hitting the enter/return key on Microsoft Word. How
many of these do you need to print an empty line?

To see the text in the serial monitor, simply click on the button on the top right hand corner of the Arduino IDE
window.

PROJECT-IN-A-BOX 11
CHALLENGE #8: DUTY CYCLE CHALLENGE
Objective: We’re going to now use the last circuit to learn
about duty cycle simply by tuning our code. Keeping the
circuit from Challenge #6

Components:
1. Components from Challenge #6

Wiring: Keep the circuit from the last challenge! You will
need the button and LED circuits.

Coding/Programming: Open the Arduino IDE software and write the following code:

int buttonState;
int buttonPin = _________ ;
int ledPin = _____________;
int count = -1;
int dutycycle;
int button_out[7] = { 0, 51, 102, 153, 204, 255, 0 };

void setup()
{
pinMode( ____________ , OUTPUT);
pinMode( ____________, INPUT);
Serial.begin( _______________ );
}
void loop()
{
buttonState = digitalRead(buttonPin);

if (buttonState == 1)
{
count = count + 1;
analogWrite(ledPin, button_out[count]);
dutycycle = map(button_out[count], ____ , ____ , ____ , ____ );
Serial.print("Duty Cycle: ");
Serial.print(dutycycle);
Serial.println(" %");
delay(300);
if (count == 6)
{
count = 0;
}
}

PROJECT-IN-A-BOX 12
Terminology:

map(): Re-maps a number from one range to another. An in-depth explanation is provided on the next page. The
terminology preceding the in-depth explanation (including the rest of this page) provides context for the example.
However, it is unnecessary to read everything to understand how the function works in general.

analogWrite(): Generates a PWM wave at the specified digital pin. The resulting average output voltage can be
treated as a continuous/analog signal. Can be used to light a LED at varying brightness or drive a motor at various
speeds. https://www.arduino.cc/en/Reference/AnalogWrite. 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. Continue reading the terminology for a better understanding of what all of this means.

Analog Signal: A continuous, real world signal (e.g., sound, light, voltage) used to represent another continuous
real-world signal. For example, using voltage and how it changes over time to indirectly measure/represent changes
in brightness (something you will do in Challenge #11). Note that it is the actual/real-world voltage and brightness
that are analog signals. The signal we obtain by measuring the voltage is a digital signal.

Digital Signal: A signal created by sampling (i.e., measuring) an analog signal over time. The original signal cannot
be obtained in its entirety. However, taking more samples per unit of time results in a higher resolution. You can
think of a single frame in a video as an example of a sample. The more frames per second, the smoother the video
becomes, and the more it looks like the events are happening in front of you/in real time. This concept is also
demonstrated in the image below:

Analog vs Digital Signal & Sampling Visualization:

!
Note: The time division is the time between samples; the inverse of time division ! " is the sample rate.
"#$% '#(#)#*+

A digital signal can also refer to signals limited to a discrete number of states/categories (e.g., ON/OFF, HIGH/LOW,
TRUE/FALSE, 1/0, 0/1/2/3/4/5/6, etc.). If a numerically describable signal has a maximum of 1 and a minimum of
0, an analog signal could be any value between 0 and 1 (e.g., 0, 1, 0.5, 0.9999900123, 0.0000….01), while a digital
signal would be limited to a countable set of values (e.g., 0 and 1, or 0, 0.5, and 1).

Further Reading:
[1] https://tinyurl.com/digital-audio-sampling
[2] https://tinyurl.com/signal-characteristics

Square Wave: A periodic waveform (a signal that repeats over


time) with two states: HIGH and LOW. A square wave is HIGH
for half of each cycle, and LOW for the other half of each cycle.

PROJECT-IN-A-BOX 13
Pulse-width modulation (PWM) and Duty Cycle: A technique used to imitate an analog signal using digital signals.
It consists of generating a square wave, where the amount of time in each cycle for which the signal is HIGH is
adjustable. The percentage of the time in each cycle that the signal is HIGH is called the duty cycle. A duty cycle
of 100% means “always HIGH” and a duty cycle of 0% means “always LOW.” A duty cycle of 50% produces a
normal square wave.

The effective output voltage from an Arduino digital pin that is generating a PWM
signal is equal to the HIGH voltage (5 V) multiplied by the duty cycle:

𝑉!"#, &'( = 𝑑𝑢𝑡𝑦 𝑐𝑦𝑐𝑙𝑒 ∗ 𝑉)*+) = 𝐷 ∗ 5 𝑉

Example: Duty cycle of 60%

𝑉!"#, &'( = 0.6 ∗ 5 𝑉 = 3 𝑉

How the map() function works:


The map function transforms the input X in the first range r1 to an equivalent
value Y in the second range r2:

r, = 4𝑟,!"# , 𝑟,!$% 7, 𝑤ℎ𝑒𝑟𝑒 𝑟,!"# ≤ 𝑋 ≤ 𝑟,!$% ; 𝑋 𝑖𝑠 𝑘𝑛𝑜𝑤𝑛

𝑟- = 4𝑟-!"# , 𝑟-!$% 7, 𝑤ℎ𝑒𝑟𝑒 𝑟-!"# ≤ 𝑌 ≤ 𝑟-!$% ; 𝑌 𝑖𝑠 𝑢𝑛𝑘𝑛𝑜𝑤𝑛

𝑟- − 𝑟-!"#
Code: Y = mapLX, 𝑟,!"# , 𝑟,!$% , 𝑟-!"# , 𝑟-!$% N → Calculation: Y = L𝑋 − 𝑟,!"# N W !$% X + 𝑟-!"#
𝑟,!$% − 𝑟,!"#

𝑌 − 𝑟-!"# 𝑋 − 𝑟,!"#
=
𝑟-!$% − 𝑟-!"# 𝑟,!$% − 𝑟,!"#

If 𝑟,!"# = 𝑟-!"# = 0, then you get an equation that may look a bit more familiar:
r, = 40, 𝑟,!$% 7

𝑟- = 40, 𝑟-!$% 7

𝑟- −0
Y = (𝑋 − 0) W !$% X+0
𝑟,!$% − 0

𝑟- 𝑋 𝑌
𝑌 = 𝑋 W !$% X → =
𝑟,!$% 𝑟,!$% 𝑟-!$%

Example based on the code for Challenge #8:

If count = 1, then:
button_count[count] = button_count[1] = 51

Resulting dutycycle calculation (Why out of 255? Read the description for analogWrite() provided above):
51 𝑑𝑢𝑡𝑦𝑐𝑦𝑐𝑙𝑒(%) 51
= → 𝑑𝑢𝑡𝑦𝑐𝑦𝑐𝑙𝑒(%) = ∗ 100% = 20%
255 100 % 255
Further Reading:
[1] https://tinyurl.com/simple-synthesis-PWM
[2] https://tinyurl.com/electronics-waveforms
[3] https://www.arduino.cc/en/Tutorial/PWM

PROJECT-IN-A-BOX 14
Challenge #9: Soft Potentiometer and RGB LED
Objective: You are going to create a soft
potentiometer based circuit. The goal is to
turn on the LED based on the position of
where you put your hand on the soft
potentiometer.

Components:
1. Arduino Uno
2. Bread-board
3. 9 wires
4. 3 Resistors (330 Ohms)
5. 1 10kΩ Resistor
6. 4 Legged RGB LED
7. Soft potentiometer

Wiring: The longest leg of the RGB LED goes to ground! This is a common cathode LED. RGB stands for
red, green, blue, all of the wavelengths it’s able to emit!

Coding/Programming: Open the Arduino IDE software and write the following code:

int potPin = _______________ ; // Potentiometer analog pin


int L1 = _______________ ; // LED Pin #1
int L2 = _______________ ; // LED Pin #2
int L3 = _______________ ; // LED Pin #3
int val;

void setup() {
Serial.begin(9600);
pinMode( L1 , OUTPUT);
pinMode( L2 , OUTPUT);
pinMode( L3 , OUTPUT);

}
void loop() {
val = analogRead(potPin);
Serial.print("Potentiometer: ");
Serial.println(val);

if (val >= ____________ && val < ____________ ) {


digitalWrite( L1, HIGH);
}
else if(val >= ____________ && val < ____________) {
digitalWrite( L2, HIGH);
}
else {
digitalWrite( L3, HIGH);
}

delay(200);
digitalWrite( L1, LOW);
digitalWrite( L2, LOW);
digitalWrite( L3, LOW);
}

In order to complete this code, you must understand what type of values are coming out of the analogRead()
function. What is the range? Break up the range into three relatively equal sections.

PROJECT-IN-A-BOX 15
Challenge #10: Voltage Divider Basics

Objective: Voltage dividers are indispensable


circuits in electronics. When you’re working with a
voltage that’s too high or needs to be modulated, a
variable resistor such as a potentiometer comes in
handy. Voltage dividers brings a high voltage down to
a small one and can be tuned by what resistors you
use. In this challenge, we will make a basic voltage
divider and read the values of the voltage from our
Arduino!

Let’s first start with V_in. The Arduino can supply 5V using the 5V pin (V_in). In your kit, you should have a 10
kΩ resistor and a 330 Ω resistor.

If 10 kΩ is R1 and 330 Ω is R2, what is your V_out value theoretically (use equation)?

V_out_theoretical = ___________________ ; V_out_actual = ___________________

If 10 kΩ is R2 and 330 Ω is R1, what is your V_out value theoretically (use equation)?

V_out_theoretical = ___________________ ; V_out_actual = ___________________

If 330 Ω is R1 and 330 Ω is R2, what is your V_out value theoretically (use equation) ?

V_out_theoretical = ___________________ ; V_out_actual = ___________________

Now wire your Arduino based on the schematic above. In order to read your V_out value, wire the V_out to
analog pin zero. Values coming out of the analog pin are straight from the analog digital converter (ADC)
and will need to be converted back to voltage! CONFIRM YOUR THEORETICAL WITH YOUR ACTUAL.

int analog_pin = __________ ;


float analog_val;
float analog_conv;

void setup() {
Serial.begin(9600);
analog_val = analogRead(analog_pin);
Serial.print("Raw Values: "); Serial.print(analog_val, 2);
analog_conv = map(analog_val, _____ , _____ , _____ , _____ );
Serial.print(" | Converted Value: "); Serial.println(analog_conv);
Serial.print(" mV"); // note: 1000 mV = 1 V
}

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

Why millivolts? map() uses integer arithmetic, which truncates decimal values (e.g., 5/2 evaluates to 2 instead of
2.5). With this in mind, it is better to use a larger range that can accommodate a greater number of integer
increments. E.g., 1/8 = 0.125 would evaluate to 0. However, 1000/8 evaluates to 125, keeping the lost values.

PROJECT-IN-A-BOX 16
So, how does a voltage divider work?
The diagram in Challenge #10 is the simplest form of a voltage divider. It consists of a voltage source (Vin) and
two resistors (R1 and R2) connected in series. The resistor with the highest resistance will have the highest
voltage drop across it. The general relationships between R1, R2, VR1, and VR2 are as follows:

𝑖𝑓 𝑅, > 𝑅- , 𝑡ℎ𝑒𝑛 𝑉.& > 𝑉.'

𝑖𝑓 𝑅, = 𝑅- , 𝑡ℎ𝑒𝑛 𝑉.& = 𝑉.'

𝑖𝑓 𝑅, < 𝑅- , 𝑡ℎ𝑒𝑛 𝑉.& < 𝑉.'

Deriving the equation to calculate Vout (VR2)


The total voltage drop across R1 and R2 is equal to the voltage of Vin:

𝑉.& + 𝑉.' = 𝑉/0

We can re-write this as

𝑉.& = 𝑉/0 − 𝑉.'

Using Ohm’s Law ( 𝑉 = 𝐼𝑅 ):

𝑉.& 𝑉/0 − 𝑉.'


𝐼.& = =
𝑅, 𝑅,

𝑉.'
𝐼.' =
𝑅-

The current flowing through 𝑅, and 𝑅- is the same (which is true for any set of components connected in series):

𝐼.& = 𝐼.' = 𝐼

Hence, we can set the two equations for 𝐼.& and 𝐼.' equal to one another and solve for 𝑉.' . In addition, notice how
the analog pin is connected to the voltage divider: It reads the voltage across 𝑅- . As such, 𝑉!"# = 𝑉.' :

𝑉/0 − 𝑉.' 𝑉.'


= , 𝑉 = 𝑉.'
𝑅, 𝑅- !"#

𝑉/0 − 𝑉!"# 𝑉!"#


=
𝑅, 𝑅-

𝑉/0 𝑉!"# 𝑉!"#


= +
𝑅, 𝑅- 𝑅,

1 1 1
𝑉!"# d + e = 𝑉/0
𝑅- 𝑅, 𝑅,

𝑅, + 𝑅- 1
𝑉!"# d e = 𝑉/0
𝑅, 𝑅- 𝑅,

𝑅, 𝑅- 𝑅-
𝑉!"# = 𝑉/0 = 𝑉/0
𝑅, (𝑅, + 𝑅- ) (𝑅, + 𝑅- )

PROJECT-IN-A-BOX 17
Challenge #11: Personal Nightlight
Objective: You are going to create a photo-resistor
and LED light-based circuit. Look at the photo-
resistor diagram on the right. Does this look
familiar? It’s a voltage divider! A photo-resistor
changes its resistance based on how much light it
detects from the environment. The resistance of the
photo-resistor normally decreases with increasing
light intensity. The goal is to use the photo-resistor
to turn on the LED (when you cover the photo-
resistor, the LED should turn brighter and brighter
until the photo-resistor is completely covered; just
like a nightlight!).
https://learn.adafruit.com/photocells/overview

Components:
1. Challenge 3 components
2. Photo-resistor
3. 1 10kΩ Resistor

Coding/Programming:

int sensorPin = _______________ ;


int ledPin = __________________ ;
int mapped;
int lightLevel;

void setup()
{
pinMode(ledPin, OUTPUT);
Serial.begin( 9600 );
}
void loop()
{
lightLevel = analogRead(sensorPin); // What values are coming out of the analog pin?
Serial.println(lightLevel);
mapped = map( ___________, ___________ , ___________ , ___________, ___________ );
analogWrite(ledPin, mapped);
}

Note: In order to fill in the map line, you must understand what values you are mapping. You are trying to map the
lowest value and highest value coming out of the photo-resistor, to your PWM values. What are PWM values? What
number means off and what number means on?

*Write down the average lightLevel value printed on the Serial Monitor when you cover the photoresistor with your
hand. This will be used in the next challenge!

Value: _________

PROJECT-IN-A-BOX 18
Terminology:

Pulse-width modulation (PWM): https://www.arduino.cc/en/Tutorial/PWM (READ THIS!)

map(): Re-maps a number from one range to another. (refer to page 14 for in-depth explanation)

analogWrite(): Writes a PWM wave to a pin (refer to pages 13 & 14 for in-depth explanation). Can be used to light
a LED at varying brightness or drive a motor at various speeds. https://www.arduino.cc/en/Reference/AnalogWrite

analogRead(): Reads the value from a specified analog pin. Arduino contains a 6 channel, 10-bit analog to digital
converter. This means that it will map input voltages between zero to five volts into integer values between 0 and
1023. https://www.arduino.cc/en/Reference/AnalogRead

What are we measuring in this circuit?


The analog pin measures the voltage drop from where it is connected in the circuit to ground and assigns it a
value between 0 and 1023. As such, we can take this value and map it to a value between 0 V and 5 V (the
voltage supplied by the Arduino is 5 V).

For the circuit in the diagram, the 10 kΩ is between the analog pin connection and ground. As such, we are
reading the voltage drop across the 10 kΩ resistor. If you switched the placement of the photoresistor and the 10
kΩ resistor, we would be measuring the voltage drop across the photoresistor.

How does the photoresistor’s behavior under different lighting conditions affect the analogRead() output?
Using the diagram from Challenge #10 as a reference:

𝑉/0 = 5 𝑉, 𝑅, = 𝑅12!#!345/5#!3 , 𝑉.& = 𝑉12!#!345/5#!3 , 𝑅- = 10𝑘𝛺, 𝑉.' = 𝑉,6 89 = 𝑉!"#

The resistance of the photoresistor increases as its exposure to light decreases (i.e., the darker the room, the
higher the resistance; the brighter the room, the lower the resistance).

Now, we know that the following relationship must hold:

𝑅- 10 𝑘𝛺
𝑉!"# = 𝑉/0 → 𝑉!"# = (5 𝑉)
(𝑅, + 𝑅- ) L𝑅12!#!345/5#!3 + 10 𝑘𝛺N

Thus,
𝑖𝑓 𝑅12!#!345/5#!3 ≫ 10 𝑘𝛺, 𝑡ℎ𝑒𝑛 𝑉!"# ≈ 0 𝑉

𝑖𝑓 𝑅12!#!345/5#!3 ≪ 10 𝑘𝛺, 𝑡ℎ𝑒𝑛 𝑉!"# ≈ 5 𝑉

10 𝑘𝛺 50
𝐸𝑥𝑎𝑚𝑝𝑙𝑒 1: 𝑅12!#!345/5#!3 = 1 𝑀𝛺 → 𝑉!"# = (5 𝑉) = 𝑉 ≈ 0.0495 𝑉
(1,000 𝑘𝛺 + 10 𝑘𝛺) 1,010
,6 89 >6
𝐸𝑥𝑎𝑚𝑝𝑙𝑒 2: 𝑅12!#!345/5#!3 = 100 𝛺 → 𝑉!"# = (5 𝑉) (6.6, 89<,6 89) = ,6.6, 𝑉 ≈ 4.995 𝑉

The overall relationships between light level, photoresistor resistance, and voltage drop across the photoresistor
and 10 kΩ resistor can be summarized as follows:

𝑙𝑖𝑔ℎ𝑡𝐿𝑒𝑣𝑒𝑙 ↑ , 𝑅12!#!345/5#!3 ↓ , 𝑉.()*+*,-.".+*, ↓ , 𝑉,6 89 ↑

𝑙𝑖𝑔ℎ𝑡𝐿𝑒𝑣𝑒𝑙 ↓ , 𝑅12!#!345/5#!3 ↑ , 𝑉.()*+*,-.".+*, ↑ , 𝑉,6 89 ↓

PROJECT-IN-A-BOX 19
Challenge #12: Smart Nightlight
Objective: We’re going to build a
smart nightlight using an RGB LED.
The objective is to build on top of the
last circuit and replace the LED with
an RGB LED to change colors when
the night light turns on!

Components:
1. 1 Arduino
2. Jumper Wires
3. 1 Breadboard
4. 1 RGB LED
5. 1 Photoresistor
6. 3 Resistors (330 ohms)
7. 1 Resistor (10K ohms)

Wiring: The longest leg of the RGB LED goes to ground! This is a common cathode LED. RGB stands for
red, green, blue, all of the wavelengths It’s able to emit!

Remember: The photoresistor's resistance should be several magnitudes larger in low-light conditions than
it is in well-lit conditions

PROJECT-IN-A-BOX 20
Coding/Programming:

int photoSensorPin = A0;


int Led1 = _______________; // PWM Pins ONLY! The Digital Pins with ~ next to it!
int Led2 = _______________; // PWM Pins ONLY! The Digital Pins with ~ next to it
int Led3 = _______________; // PWM Pins ONLY! The Digital Pins with ~ next to it
int Led1Val = 0;
int Led2Val = 0;
int Led3Val = 0;
boolean isLedOn = false;

int brightness; // Stores the value measured by the analog pin


int darkThreshold = ________________ ; // Avg value when you cover your photoresistor
int changeColorTime = 2000;

long lastUpdate = 0;

void setup()
{
randomSeed(analogRead(1));
Serial.begin(9600);
}

void loop()
{
brightness = analogRead( __________________ ); // Get's Photoresistor Value
Serial.println(brightness);

if (brightness < darkThreshold)


{
Serial.println("Good night!");

if (!isLedOn)
{
LedOn(); isLedOn = true; lastUpdate = millis();
}
else if (millis()>lastUpdate+changeColorTime)
{
LedOn();
isLedOn = true;
lastUpdate = millis();
}
}
else
{
Serial.println("Rise and Shine!");
LedOff();
isLedOn = false;
}

delay(1000);
}

void LedOn()
{
Led1Val = random(1,128);
Led2Val = random(1,128);
Led3Val = random(1,128);

analogWrite(Led1,Led1Val);
analogWrite(Led2,Led2Val);
analogWrite(Led3,Led3Val);
}

void LedOff()
{
analogWrite(Led1,LOW);
analogWrite(Led2,LOW);
analogWrite(Led3,LOW);}

PROJECT-IN-A-BOX 21
Challenge #13: Servo Control with Knob Potentiometer

Objective: In this challenge, you will learn how to utilize


a servo and control it with a knob potentiometer! A knob
potentiometer is a variable resistor that changes
resistance when you turn the knob (a voltage divider!).

Components:
1. Arduino Uno
2. Micro Servo
3. Knob Potentiometer

First, hook up the servo according to the schematic.


Make sure you attach a small handle on the shaft of
the servo (comes with the servo).

Coding/Programming:
#include <Servo.h>

int servo_pin = ________________ ;

Servo servoMain; // Create object

void setup() {
servoMain.attach( servo_pin );
}
void loop() { Note:
servoMain.write( ______________ ); // Highest angle A micro-servo (small) typically
delay(1000);
servoMain.write( ______________ ); // Lowest angle has a degree range of 0 to
delay(1000); 180 degrees.
}

Objective: Using what you know from


Challenge 8 about the soft potentiometer,
program the knob potentiometer to take the
analog values and map them from zero to 90.
Next, take the mapped values and send it to
the servo. As you turn the potentiometer, the
servo angle turns with it!

You will need a combination of the


analogread() function, the map() function, and
the above code to accomplish this.

If you find yourself stuck, utilize this tutorial to


your advantage!

https://www.arduino.cc/en/Tutorial/Knob

To learn more about servos, go to the


following link:

https://tinyurl.com/intro-to-servos

PROJECT-IN-A-BOX 22
Challenge #14: Building a Library!

Objective: In this challenge, you will build external functions and libraries. If you are working in a team, each
student expected to complete this challenge individually.

To begin, make sure you download and install Sublime text editor:

https://www.sublimetext.com/

Next, recreate Challenge #1 on your breadboard, but this time, hook up your LED pin to pin 13.

Follow the Writing a Library for Arduino tutorial provided by the Arduino website:

https://www.arduino.cc/en/Hacking/LibraryTutorial

Next, follow the tutorial to develop your own libraries written in C++. In the end, you will have one .cpp file and
one .h file (build these library files using Sublime Text Editor). Have a tutor or TA check your circuit, sketch,
and file libraries.

Answer these questions briefly:

What is #include?
__________________________________________________________________________________________
__________________________________________________________________________________________
__________________________________________________________________________________________
__________________________________________________________________________________________
__________________________________________________________________________________________

What is an object?
__________________________________________________________________________________________
__________________________________________________________________________________________
__________________________________________________________________________________________
__________________________________________________________________________________________
__________________________________________________________________________________________

What is a constructor?
__________________________________________________________________________________________
__________________________________________________________________________________________
__________________________________________________________________________________________
__________________________________________________________________________________________
__________________________________________________________________________________________

PROJECT-IN-A-BOX 23
REFERENCES
1. Please visit Sparkfun to learn more about how breadboards work!
https://learn.sparkfun.com/tutorials/how-to-use-a-breadboard

2. The Arduino website is a very good resource for grasping circuits and Arduino in general. Use the following
link and click on the “Learning” tab, where you will find how to get started, tutorials, and other useful
references!
https://www.arduino.cc/en/Main/Documentation#

3. SparkFun is a vendor that sells a variety of platforms, one of them Arduino. Luckily, they have great
resources on the site to help you learn Arduino.
https://learn.sparkfun.com/tutorials/what-is-an-arduino

4. Adafruit is a DIY (Do-It-Yourself) vendor that sells and utilizes a variety of platforms. Luckily, they have a
section dedicated to Arduino! Simply click on the “Learn” tab and follow the Arduino links. It will take you
to a large amount of projects for you to build on your own!
https://www.adafruit.com

5. Instructables is a good project-based resource with a variety of platforms just like Adafruit. Check the
website out for more interesting projects!
http://www.instructables.com

PROJECT-IN-A-BOX 24

You might also like