Welcome to the Arduino
The Arduino was originally built for designers and artists—people with little
technical expertise.
Even without programming experience, the Arduino enabled them to create
sophisticated design prototypes and some amazing interactive artworks.
So, it should come as no surprise that the first steps with the Arduino are very
easy, even more so for people with a strong technical background.
One thing to understand before getting started is physical computing. If you
have worked with computers before, you might wonder what this means.
After all, computers are physical objects, and they accept input from physical
keyboards and mice.
They output sound and video to physical speakers and displays. So, isn’t all
computing physical computing in the end?
In principle, regular computing is a subset of physical computing: keyboard and
mouse are sensors for real-world inputs, and displays or printers are actuators.
But controlling special sensors and actuators, using a regular computer is very
difficult. Using an Arduino, it’s a piece of cake to control sophisticated and
sometimes even weird devices. In the rest of this book, you’ll learn how, and in
this chapter you’ll get started with physical computing by learning how to
control the Arduino.
What tools you need, and how to install and configure them. Then we’ll quickly
get to the fun part: you’ll develop your first program for the Arduino.
1 Superiors innovation Center
What exactly is an Arduino?
Figure 1-1. An Arduino Uno
Wikipedia states “An Arduino is a single-board microcontroller and a software suite for
programming it. The hardware consists of a simple open hardware design for the controller
with an Atmel AVR processor and on-board I/O support. The software consists of a standard
programming language and the boot loader that runs on the board.”
To put that in layman’s terms, an Arduino is a tiny computer that you can program to process
inputs and outputs between the device and external components you connect to it (see Figure
1-1).
The Arduino is what is known as a Physical or Embedded Computing platform, which means
that it is an interactive system that can interact with its environment through the use of
hardware and software.
For example, a simple use of an Arduino would be to turn a light on for a set period of time,
let’s say 30 seconds, after a button has been pressed. In this example, the Arduino would have
a lamp and a button connected to it.
The Arduino would sit patiently waiting for the button to be pressed; once pressed, the Arduino
would turn the lamp on and start counting.
Once it had counted for 30 seconds, it would turn the lamp off and then wait for another button
press. You could use this setup to control a lamp in a closet, for example.
2 Superiors innovation Center
What is Arduino?
• An open-source hardware and software platform for building electronics
projects
• A physical programmable circuit board (often referred to as a microcontroller)
• A piece of software, or IDE (Integrated Development Environment) that runs on
your computer, used to write and upload computer code to the physical board
(supports Mac/Windows/Linux)
Know your board
Microcontroller : ATmega168 / ATmega328
Operating Voltage : 5V
Input Voltage (recommended): 7-12V ( 9V is the best )
Input Voltage (Limits): 6-20V
Digital I/O Pins: 14 (of which 6 provide PWM output)
Analog Input Pins: 6
DC Current per I/O Pin: 40mA
DC Current for 3.3V Pin: 50mA
Flash Memory: 16 KB (ATmega168) or 32 KB (ATmega328) of which 2 KB used
by bootloader
SRAM: 1 KB (ATmega168) or 2 KB (ATmega328)
EEPROM: 512 bytes (ATmega168) or 1 KB (ATmega328)
Clock Speed: 16 MHz
3 Superiors innovation Center
Types of Arduino
Arduino Uno Arduino Micro
Arduino Mini Arduino Nano
Arduino Due Arduino Leonardo
Arduino Mega Arduino LilyPad
4 Superiors innovation Center
Power your board
Take power from your board
5 Superiors innovation Center
Talk to/listen to your board
6 Superiors innovation Center
Exploring the Arduino Board
Check this link : http://ardumap.everpi.net
To connect an Arduino to your computer, you just need an USB cable. Then you can
use the USB connection for various purposes:
Upload new software to the board.
Communicate with the Arduino board and your computer.
Supply the Arduino board with power.
As an electronic device, the Arduino needs power. One way to power it is to connect it to a
computer’s USB port, but that isn’t a good solution in some cases. Some projects don’t
necessarily need a computer, and it would be overkill to use a whole computer just to power
the Arduino. Also, the USB port only delivers 5 volts, and sometimes you need more.
In these situations, the best solution usually is an AC adapter supplying 9 volts (the
recommended range is 7V to 12V). Plug it into the Arduino’s power jack, and it will start
immediately, even if it isn’t connected to a computer. By the way, even if you connect the
Arduino to an USB port, it will use the external power supply if available.
7 Superiors innovation Center
Installing the Arduino IDE
www.arduino.cc
1) Download
2) Windows Installer
3) JUST DOWNLOAD
8 Superiors innovation Center
Connect the board
The Arduino Uno automatically draws power from either the USB connection to the computer
or an external power supply.
Install the driver
Installing drivers for Arduino Uno or Arduino Mega 2560:
i. Plug in your board and wait for Windows to begin its driver installation process. After a
few moments, the process will fail, despite its best efforts.
ii. Click on the Start Menu, and open up the Control Panel.
9 Superiors innovation Center
iii. While in the Control Panel, navigate to System and Security. Next, click on System.
Once the System window is up, open the Device Manager.
iv. Look under Ports (COM & LPT). You should see an open port named "Arduino UNO
(COMxx)". If there is no COM & LPT section, look under "Other Devices" for
"Unknown Device".
v. Right click on the "Arduino UNO (COmxx)" port and choose the "Update Driver
Software" option.
vi. Next, choose the "Browse my computer for Driver software" option.
vii. Finally, navigate to and select the driver file named "arduino.inf", located in the
"Drivers" folder of the Arduino Software download (not the "FTDI USB Drivers" sub-
directory). If you are using an old version of the IDE (1.0.3 or older), choose the Uno
driver file named "Arduino UNO.inf"
viii. Windows will finish up the driver installation from there.
Launch the Arduino application
Double-click the Arduino application (arduino.exe) you have previously downloaded. (Note: if
the Arduino Software loads in the wrong language, you can change it in the preferences dialog.
Open the blink example
Open the LED blink example sketch: File > Examples >01.Basics > Blink
10 Superiors innovation Center
Select your board
You'll need to select the entry in the Tools > Board menu that corresponds to your
Arduino.
Selecting an Arduino Uno
Select Serial port
Select the serial device of the Arduino board from the Tools | Serial Port menu. This is likely to
be COM3 or higher (COM1and COM2 are usually reserved for hardware serial ports). To find
out, you can disconnect your Arduino board and re-open the menu; the entry that disappears
should be the Arduino board. Reconnect the board and select that serial port.
11 Superiors innovation Center
Upload the program
Now, simply click the "Upload" button in the environment. Wait a few seconds - you should see
the RX and TX leds on the board flashing. If the upload is successful, the message "Done
uploading." will appear in the status bar.
A few seconds after the upload finishes, you should see the pin 13 (L) LED on the board start
to blink (in orange). If it does, congratulations! You've gotten Arduino up-and-running.
12 Superiors innovation Center
The Arduino IDE
The Serial Monitor
13 Superiors innovation Center
Concepts: INPUT vs. OUTPUT
Inputs is a signal / information going Output is any signal exiting the
into the board. board.
Almost all systems that use physical computing will have some form of
output
What are some examples of Outputs?
Examples: Buttons Switches, Examples: LEDs, DC motor,
Light Sensors, Flex Sensors, servo motor, a piezo buzzer,
Humidity Sensors, Temperature relay, an RGB LED
Sensors…
Concepts: Analog vs. Digital
Microcontrollers are digital devices – ON or off. Also
called – discrete
Analog signals are anything that can be a full range of
values.
5 5
V V
0 0
V V
14 Superiors innovation Center
All physical quantities are analog.
Analog means that the quantity can take any value between its
minimum value and maximum value.
Digital means that the quantity can take specific levels of
values with specific offset between each other.
Ex: 1- Digital:
English alpha consists of 26 letters; there is no letter between
A and B.
- Square waves are Digital.
Ex.: 2- Analog:
Temperature, can take any value [-1, 12.8, 25.002,… etc.].
- Sine waves are analog.
Digital I/O Pins the Arduino I/O board has 14 Digital pins that can be
configured and used individually as Inputs or Outputs from the program. When
a digital pin is configured as INPUT it can be used to read all kind of sensors
that give devices ON and OFF, like push buttons, touch sensors, switches …
etc.
When a pin is used as an
OUTPUT it can be used to turn
ON or OFF all sorts of devices,
like light bulbs, motors, home
appliances etc.
15 Superiors innovation Center
Analog Inputs
The Arduino I/O board has 6 Analog Inputs capable of reading voltages
between 0-5V. Internally the voltages are translated into number from 0 to
1023. These inputs can be used to measure continuous quantities like light
intensity, temperature, Proximity, Position etc. Depending on the type of
sensor.
PWM (Analog) Outputs
The Arduino I/O board has 6 PWM (Pulse Width Modulation) outputs. PWM
consist of switching something ON and off thousands of times per second,
allowing effects like dimming a light or control the speed of a motor.
16 Superiors innovation Center
PWM (Analog) Outputs
Indicators
The wiring I/O board has a power (green) LED indicator that is turned ON
when the board is powered. It also includes LEDs for the Serial port (USB)
data transmission reception.
17 Superiors innovation Center
Basic I/O – Digital Writes
Voltage Out
Digital Pins
• General Purpose I/O Pin are 2, 3, 4, 5, 6, 7,8, 9, 10, 11, 12, & 13
• Analog I/O can also be used as digital pings; analog input A0 as digital pin 14 through
analog input A5 as digital pin 19
• Pin 13 has a built-in LED connected to it
• When the pin is HIGH value, the LED is on, when the pin is LOW value, it's off
Digital Write – Key Concepts
pinMode(): Configures the specified pin to behave either as an input or an output
Syntax: pinMode(pin, mode)
Example: pinMode(13,OUTPUT) set pin 13 to output mode
Example: pinMode(13,INPUT) set pin 13 to input mode
digitalWrite(): Write HIGH or a LOW value to a digital pin
If set to OUTPUT with pinMode(), 5V for HIGH, 0V (ground) for LOW.
Syntax: digitalWrite(pin, value)
Example 1: digitalWrite(13,HIGH) is 5 volts to pin 13
Example 2: digitalWrite(13,LOW) is 0 volts to pin 13
18 Superiors innovation Center
Action Round #1-Blink LED
Project name: Blink LED
Goal: Turns LED on for one second, then off for one second
repeatedly
Software • Hardware
• pinMode() • 5mm LED (1)
• digitalWrite() • 220 Ohm Resister (1)
• delay() • Arduino Uno (1)
Breadboard
Jumper Wires
Breadboard Layout
Connected dots
represent connectivity
19 Superiors innovation Center
How NOT to burn your Arduino
Isolation
Never tie Arduino 3.3V power to 5V power
Never tie Arduino VIN to either 3.3V or 5V power
Never tie external power supplies to Arduino power
Ground
Never short any power to ground
All breadboard grounds together (common reference)
Noisy ground (ex. motor) can use separate Arduino ground pin
20 Superiors innovation Center
LED BASIC:
How to tell between anode and cathode?
Light Emitting Diodes
Features:
A basic 5mm LED with a red lens.
1.8-2.2VDC forward drop
Max current: 20mA
Suggested using current: 16-18mA
Luminous Intensity: 150-200mcd
Safety Tips:
Must use a pull-down resister to connect to 0V(ground)!
Math: (5V-1.8V)/16mA = 200 ohm
Pick: 220 ohm resister
Action Round #1-Blink LED
• Software
• int led = 13;
•
• // the setup routine runs once when you press reset:
• void setup() {
• // initialize the digital pin as an output.
• pinMode(led, OUTPUT);
• }
•
• // the loop routine runs over and over again forever:
• void loop() {
• digitalWrite(led, HIGH); // turn the LED on (HIGH is the
voltage level)
• delay(1000); // wait for a second
• digitalWrite(led, LOW); // turn the LED off by making the
voltage LOW
• delay(1000); // wait for a second
• }
21 Superiors innovation Center
Digital Design
• Using your own circuit design and Arduino sketch,
design a solution that solves the following challenges.
• Challenge 1a: Add a Second LED to the circuit and
make them Blink together.
• Challenge 1b: Then make them Blink alternating on
and off.
• Challenge 1a: Add a Second Software
int led1 = 13;
LED to the circuit and make int led2 = 12; // Additional LED Pin
them Blink together
void setup() {
// initialize the digital pin as an output.
pinMode(led1, OUTPUT);
pinMode(led2, OUTPUT); // Additional LED Pinmode
}
void loop() {
digitalWrite(led1, HIGH); // turn the LED on (HIGH is the
voltage level)
digitalWrite(led2, HIGH); // turn the LED on (HIGH is the
voltage level)
delay(1000); // wait for a second
digitalWrite(led1, LOW); // turn the LED off by making the
voltage LOW
digitalWrite(led2, LOW); // turn the LED off by making the
voltage LOW
delay(1000); // wait for a second
}
22 Superiors innovation Center
• Challenge 1b: Make them
Blink Alternating on and off.
Software
/*
Blink two LEDs together
Modified by Matt Royer May 5, 2014
*/
int led1 = 13;
int led2 = 12; // Additional LED Pin
// the setup routine runs once when you press reset:
void setup() {
// initialize the digital pin as an output.
pinMode(led1, OUTPUT);
pinMode(led2, OUTPUT); // Additional LED Pinmode
}
// the loop routine runs over and over again forever:
void loop() {
digitalWrite(led1, HIGH); // turn the LED on (HIGH is the voltage level)
digitalWrite(led2, LOW); // turn the LED on (HIGH is the voltage level)
delay(1000); // wait for a second
digitalWrite(led1, LOW); // turn the LED off by making the voltage LOW
digitalWrite(led2, HIGH); // turn the LED off by making the voltage LOW
delay(1000); // wait for a second
}
Arrays
Create an Array:
Syntax: int myInts[6];
int myPins[] = {2, 4, 8, 3, 6, 1};
int mySensVals[6] = {2, 4, -8, 3, 2, 0};
char message[6] = "hello!;
Access an Array:
Array index starts from 0.
int myArray[10]={9,3,2,4,3,2,7,8,9,11};
// myArray[9] contains 11
// myArray[10] is invalid and contains random information (other memory
address)
To assign a value to an Array:
mySensVals[0] = 10;
To retrieve a value from an array:
x = mySensVals[4];
23 Superiors innovation Center
Control structure
• for loop
Syntax: for (initialization; condition; increment) {
//statement(s);
}
Example:
void setup() { // no setup needed }
void loop()
{ for (int i=0; i <= 255; i++) {
analogWrite(PWMpin, i);
delay(10); } }
Arrays and for – loop
Arrays are often manipulated inside for loops, where the loop
counter is used as the index for each array element. For example, to
print the elements of an array over the serial port, you could do
something like this:
Example:
int i;
int myPins[3] = {0,1,2};
for (i = 0; i < 3; i = i + 1) {
digitalWrite(myPins[i], HIGH);
delay(2000); //delay for 2 seconds
}
24 Superiors innovation Center
Action Round #2- 3 LED s blink in
series and repeat
Goal: take turn
You’ll be using: for loop, array, delay()
Software Hardware
• pinMode() • 5mm LED (3)
• digitalWrite() • 220 Ohm Resister (3)
• array [ ] • Arduino Uno Board (1)
• for loop Breadboard
• delay() Jumper Wires
Software
const int numberOfLED = 3; // Number of LED in Array
const int lEDToBlink[numberOfLED] = { // Array to store LED Pins
13, 12, 11
};
// the setup routine runs once when you press reset:
void setup() {
for (int initalizeLED = 0; initalizeLED < numberOfLED; initalizeLED++){
pinMode(lEDToBlink[initalizeLED], OUTPUT);
}
}
void loop() {
for (int lightLED = 0; lightLED < numberOfLED; lightLED++){ // For each LED in Array,
digitalWrite(lEDToBlink[lightLED], HIGH); // turn the LED on (HIGH is the voltage level)
delay(1000);
digitalWrite(lEDToBlink[lightLED], LOW); // turn the LED on (HIGH is the voltage level)
}
}
25 Superiors innovation Center
Control structure
While
Syntax: while(expression){
// statement(s)
}
Example: var = 0;
while (var < 200) {
// do something repetitive 200 times
var++;
}
If
Syntax: if (boolean condition) {
//statement(s);
}
if else, if else if, else
Syntax: if (condition1) {
// do Thing A
} else if (condition2) {
// do Thing B
}
…
} else {
// do Thing C
}
26 Superiors innovation Center
Switch case
Syntax: switch (var) { Example: switch (var) {
case 1:
case label: //do something when var
// statements equals 1
break;
break;
case 2:
case label: //do something when var
// statements equals 2
break;
break; Default:
default: // if nothing else matches,
do the default
// statements
// default is optional
} }
BASIC I/O – ANALOG WRITES
• PWM pins ONLY
• 8 bit resolution
• (GPIO) pins
27 Superiors innovation Center
Pulse Width Modulation
• In Summary: PWM is a technique for getting analog results with digital means.
To be exact, a signal is switched between on and off to create a square wave, by
controlling the percentage of time the signal is on (duty cycle), we simulate “a
steady analog source” which can be considered as “the digital average”.
• Vanalog = Vdigital * DutyCycle
• The table shows relation between
• PWM duty cycle and simulated
• analog voltage, assume Vdigital = 5V
0V
1.25V
2.5V
3.75V
5V
• How to use in Arduino?
• Identify the pins: PWM is supported on Pin 3, 5, 6, 9, 10, 11 ,
with a “~”
• Modulate pulse width by calling analogWrite()
• analogWrite ranges from 0 -255, with 0 being 0% duty cycle,
255 being 100%
• For example, 50% duty cycle is 255*50% = 127,
analogWrite(PIN, 127) makes the analog output looks like it’s
connected to a steady 2.5V source
• Provide 8/12bit PWM output with the analogWrite() function.
The resolution of the PWM can be changed with the
analogWriteResolution() function.
28 Superiors innovation Center
Analog Write – Key Concepts
• Arduino Default PWM is 8 bit
void Setup()
• pinMode(): Configures the specified pin to behave either as an input or an output
• Example: pinMode(11, OUTPUT)
void loop()
• analogWrite(): Writes an analog value (Pulse Width Modulation wave) to a pin.
• Example: analogWrite (11, 64)
• Q: What’s the Duty Cycle does 64 represent, suppose PWM precision is 8 bit ?
• Hint: the max number can be represented by 8 bit is 28 − 1 = 255
Action Round #1-Fading LED using
analogWrite
Goal: Change the brightness of an LED using PWM to make it appear to fade in
and out by itself
You will be using: Analog Write
• Hardware
Software • 5mm LED (1)
• analogWrite() • 220 Ohm Resister (1)
Breadboard
Jumper Wires
Software
int led = 11; // the pin that the LED is attached to
int brightness = 0; // how bright the LED is
int fadeAmount = 5; // how many points to fade the LED by
void setup() {
// declare pin 11 to be an output:
pinMode(led, OUTPUT);
}
void loop() {
analogWrite(led, brightness);
brightness = brightness + fadeAmount;
if (brightness == 0 || brightness == 255) {
fadeAmount = -fadeAmount ;
} delay(30);
}
29 Superiors innovation Center
BASIC I/O – SERIAL WRITES
Refresher: Arduino Serial Interface
Used for communication between the Arduino board and a computer or
other devices
Arduino platform have at least one serial port ( also known as a UART
or Universal Asynchronous Receiver/Transmitter)
Serial Communicates through digital pins 0 (RX) & 1 (TX) and via USB
to Computer for Sketches
Serial Write – Key Concepts
Serial.begin(): Sets the data rate in bits per second (baud) for serial data
transmission
Syntax: Serial.begin(baud)
Example: Serial.begin(9600) sets serial baud rate to 9600 bits per
second
Serial.print(): Prints data to the serial port as human-readable ASCII text
without carriage return / Newline Feed character
Syntax: Serial.print(val) or Serial.print(val, format)
Parameters:
• val: the value to print - any data type
• format: specifies the number base or number of decimal places
• Example: Serial.print(”Hello world.“) gives "Hello world.“
• Example: Serial.print(1.23456, 2) gives “1.23”
• Serial.println(): Prints data to the serial port as human-readable ASCII
text followed by a carriage return and a newline character
• Syntax: Serial.println(val) or Serial.print(val, format)
• Parameters:
• val: the value to print - any data type
• format: specifies the number base or number of decimal places
• Example: Serial.println(”Hello world.“) gives "Hello world.“
• Example: Serial.println(1.23456, 2) gives “1.23”
30 Superiors innovation Center
• Serial.write(): Writes binary data to the serial port. This data is sent as a
byte or series of bytes
• Syntax: Serial.write(val)
• Example: Serial.wrtie(”Hello world“) writes "Hello world“
Bring up Serial Monitor
• Select “Tools” -> “Serial Monitor” or click Serial Monitor Icon
Note: Sketch must be loaded first; else, Serial Monitor will close on Sketch upload
31 Superiors innovation Center
Action Round #1- Serial Write –
Hello World!
Project Name: Hello World!
Objective: Print out 10 – 0 on every line, every second, and followed by
“Hello Wolrd!”
Software
• Serial.begin() Hardware
• Serial.print() • Arduino Uno Board (1)
• Serial.println()
• for loop
• delay()
Software
int i;
void setup() {
// initialize the serial interface
Serial.being(9600);
}
void loop(){
delay (2000); //borrow some time for opening
serial monitor
// Serial print
for (i=10; i>=0; i--) {
Serial.println(i);;
delay(1000);
}
Serial.print(“Hello World!\n”);
}
32 Superiors innovation Center
BASIC I/O – DIGITAL READS
Digital Read – Key Concepts
• Reminder pinMode(): Configures the specified pin to behave either as
an input or an output
• Syntax: pinMode(pin, mode)
• Example: pinMode(2, OUTPUT) set pin 2 to output mode
• Example: pinMode(2, INPUT) set pin 2 to input mode
• digitalRead(): Reads the value from a specified digital pin, either HIGH
or LOW
• Syntax: digitalRead(pin)
• Example 1: digitalRead(2) reads High or Low from pin 2
Action Round #1- Digital Read from
push button
• Project Name: LED Button Press
• Goal: Illuminate LE D when push button is being pressed
• Hardware
Software
• 5mm LED (1)
• pinMode()
• Momentary Switch/push button (1)
• digitalWrite()
• 220 Ohm Resister (1)
• digitalRead()
• 10k Ohm Resister (1)
• if / else
• Arduino (1)
Breadboard
Jumper Wires
33 Superiors innovation Center
Hardware Connection :
Action Round #1- Digital Read from
push button
Hardware
• Connect power rails to breadboard Software
// constants won't change. They're used here to
• D13>220 ohm->anode->cathode->GND // set pin numbers:
• Vcc->10k ohm-> pushbutton->GND const int buttonPin = 7;
const int ledPin = 13; // the number of the LED pin
• D2->pushbutton and resistor junction point // variables will change:
int buttonState = 0;
void setup() {
// initialize the LED pin as an output:
pinMode(ledPin, OUTPUT);
// initialize the pushbutton pin as an input:
pinMode(buttonPin, INPUT);
}
void loop(){
// read the state of the pushbutton value:
buttonState = digitalRead(buttonPin);
// check if the pushbutton is pressed.
// if it is, the buttonState is HIGH:
if (buttonState == HIGH) {
// turn LED on:
digitalWrite(ledPin, HIGH);
} else {
// turn LED off:
digitalWrite(ledPin, LOW);
}
}
34 Superiors innovation Center
Action Round #2- Blink LED
Continuously while button is
pressed
• Goal: when button is pressed, blink LED continuously
• You’ll be u sing: if , delay()
Software Hardware
• pinMode() • 5mm LED (1)
• digitalWrite() • Momentary Switch/push button (1)
• if • 220 Ohm Resister (1)
• delay() • 10k Ohm Resister (1)
• Arduino Uno Board (1)
Breadboard
Jumper Wires
Action Round #2- Blink LED
Continuously while button is
pressed
Software
const int buttonPin = 2; // the number of the pushbutton pin
const int ledPin = 13; // the number of the LED pin:
int buttonState = 0;
void setup() {
Hardware pinMode(ledPin, OUTPUT);
pinMode(buttonPin, INPUT);
• Connect power rails to breadboard }
• D13>220 ohm->anode->cathode- void loop(){
>GND buttonState = digitalRead(buttonPin);
if (buttonState == HIGH) {
• Vcc->10k ohm-> pushbutton->GND digitalWrite(ledPin, HIGH);
• D2->pushbutton and resistor delay(500);
digitalWrite(ledPin, LOW);
junction point delay(500);
}
digitalWrite(ledPin, LOW);
}
35 Superiors innovation Center
Action Round #3- press button to
turn on and off LED
• Goal: when button is pressed and released first time, turn
on LED; and the second time, turn off LED; and continues
turning on and off LED with each press and release of
button.
Software Hardware
• pinMode() • 5mm LED (1)
• digitalWrite() • Momentary Switch/push button (1)
• digitalRead() • 220 Ohm Resister (1)
• If • 10k Ohm Resister (1)
• boolean variable • Arduino Uno Board (1)
• boolean operation (!) Breadboard
• delay() Jumper Wires
Action Round #3- press button to
turn on and off LED
Software
const int buttonPin = 2; // the number of the pushbutton
const int ledPin = 13;
boolean ledState = false;
boolean buttondown = false;
void setup() {
pinMode(ledPin, OUTPUT);
pinMode(buttonPin, INPUT);
}
void loop(){
buttondown = digitalRead(pushbutton);
if(buttondown){
ledState = !ledState; digitalWrite(ledPin, ledState);
}
delay(200);
}
36 Superiors innovation Center
BASIC I/O ANALOG READ
Analog Signal
• Analog signal is any continuous signal Vs. time!
• Digital signal uses discrete (discontinuous) values.
Analog Read – Board Hardware
37 Superiors innovation Center
• 10 bit resolution .
• (GPIO) pins .
• 100 µs (0.0001 s) to
read an analog input .
reading rate = 10,000 /s
Analog Sensors
Potentiometer LM35
LDR
38 Superiors innovation Center
Analog Read – Key Concepts
analogRead(): Reads the value from the specified analog pin.
Syntax: analogRead(pin)
Example: analogRead(A0) reads analog value of pin A0
Action- Round #1- Read Value from
potentiometer
• Goal: Read the voltage adjusted by potentiometer and print out on Serial
Monitor
• You will be using: Analog Read and Serial Monitor
Software Hardware
• analogRead() • Potentiometer(1)
• Serial.println() Breadboard
Jumper Wires
Action- Round #1-Read Value from
potentiometer
Software
void setup() {
// initialize serial communication at 9600 bits
per second:
Serial.begin(9600);
}
// the loop routine runs over and over again fore
ver:
void loop() {
int sensorValue = analogRead(A0);
Serial.println(sensorValue);
delay(500);
}
39 Superiors innovation Center
Observation
• What is the range of potentiometer output?
• Why is it represented in numbers rather than actual
voltage?
Data Types — Floating point
• Syntax: A. float var = val;
B. (float) var -- type casting
• Example:
• A. float x= 1.25;
• B. int x;
• int y;
• float z;
• x = 1;
• y = x / 2; // y now contains 0, int can't hold
fraction
• z = (float)x / 2.0; // z now contains 0.5 (you have
to use 2.0, not 2)
Action- Round #2- Read Value from
POT and convert it to true floating
point value
Hint:
• The range of POT voltage output is 0 to 5V
• Define a floating point variable, ex. float vPOT;
• vPOT = sensorValue/sensorFullRange * 5.0
• Don’t forget the type casting!
40 Superiors innovation Center
Software:
void setup() {
// initialize serial communication at 9600 bits per second:
Serial.begin(9600);
}
// the loop routine runs over and over again forever:
void loop() {
// read the input on analog pin 0:
int sensorValue = analogRead(A0);
// print out the value you read:
Serial.println((sensorValue/1023 )* 5 );
// delay in between reads for stability
delay(500);
}
Action Round#3– Calibrating
analog input to fit digital range
Goal: Given an analog input source whose range is unknown,
map the range to the digital representation at initial setup time
You will be using: millis(), map(), Analog Read, Serial Monitor
Software • Hardware
• analogWrite() • Potentiometer
• pinMode() Breadboard
Jumper Wires
41 Superiors innovation Center
Action Round#3– Calibrating
analog input to fit digital range
Software
• First run the code
-> File->Example-> Analog->Calibration
• Add Serial Print to monitor
Print out the Sensor Min value and Sensor Max value to see how it
changes as flex sensor is being bent.
Serial.begin(9600);
Serial.print("Calibration time sensorMin = ");
Serial.println(sensorMin);
Serial.print("Calibration time sensorMax = ");
Serial.println(sensorMax);
Making the Calibration time longer and add delay function if necessary
to better observe in Serial Monitor.
while (millis() < 10000) {
…
delay(100);
}
Map() function
• map(): Re-maps a number from one range to another.
Value can be mapped to values that are out of range.
• Syntax: map(Source, fromLow, fromHigh, toLow, toHigh)
• Example: map(val, 0, 1023, 0, 255)
42 Superiors innovation Center
• Useful for dealing with different
precisions/representations, 5V is represented as 1023
previously, now as 255.
• For example:
• Arduino Default analog read (ADC) is 10bit precision, 5V
= 1023
• Arduino Default PWM is 8bit precision, 5V = 255
• Use map() to adapt one range to the other
Constrain() function
• Constrains a number to be within a range.
• Syntax: constrain(x, a, b)
• Returns:
• x: if x is between a and b
• a: if x is less than a
• b: if x is greater than b
• Example:
• sensVal = constrain(sensVal, 10, 150);
• // limits range of sensor values to between 10 and 150
43 Superiors innovation Center
LDR
Light Dependent Resistor
44 Superiors innovation Center
جيب توصيل مقاومة مع احلساس
voltage divider ...لعمل
لنمتكن من قياس تغري اجلهد عىل احلساس !
Schematic Diagram
45 Superiors innovation Center
LM35
The LM35 series are precision integrated-circuit temperature
devices with an output voltage linearly-proportional to the
Centigrade temperature.
Features
Calibrated Directly in Celsius (Centigrade)
Linear + 10-mV/°C Scale Factor
0.5°C Ensured Accuracy (at 25°C)
Rated for Full −55°C to 150°C Range
Suitable for Remote Applications
Low-Cost Due to Wafer-Level Trimming
Operates from 4 V to 30 V
Less than 60-μA Current Drain
Low Self-Heating, 0.08°C in Still Air
Non-Linearity Only ±¼°C Typical
Low-Impedance Output, 0.1 Ω for 1-mA Load
46 Superiors innovation Center
Software :
Action Round#4– Fading LED
using potentiometer
Software • Hardware
• analogWrite() • 5mm LED
• analogRead() • 220 Ohm Resister
• Potentiometer
Breadboard
Jumper Wires
47 Superiors innovation Center
Software:
Action Round#5– Fading LED
using LDR
Software
• Hardware
• analogWrite()
• 5mm LED
• analogRead()
• 220 Ohm Resister
• LDR
Breadboard
Jumper Wires
48 Superiors innovation Center
Examples:
Example1: Make a smart light system, using LRD & 4 LEDs
Goal: When the Lighting is very high all LEDs off, When the
lighting is high 1 LED ON, When the lighting is Medium 2 LED
ON, When the lighting is low 3 LED ON, When the lighting is
very low all LED ON
Hint: use map function and control structure (if / switch)
Example2: Make an alarm temperature system, using LM35
and buzzer, when the temperature reaches a specific value the
buzzer turn on else it's off
Example3: Make a traffic light system using 3 LED, green, red
and orange.
49 Superiors innovation Center
Buzzer
A buzzer or beeper is an audio signaling device.
The long leg is the
positive
50 Superiors innovation Center
Enough with LED,
Let’s play with motors!
• DC motors
Direct Current controlled motor, using two wires to connect to Power and
Ground
• Servo motors
A servomotor is a rotary actuator that allows for precise control of angular
position, velocity and acceleration.
0-180 degrees
DC Motor:
The most common actuator in mobile robots robotics is
the direct current (DC) motor
Advantages: simple, cheap, various sized and packages,
easy to interface, clean.
DC motors convert electrical energy into mechanical
energy.
51 Superiors innovation Center
DC motors consist of permanent magnets with loops of
wire inside
When current is applied, the wire loops generate a
magnetic field, which reacts against the outside field of
the static magnets
The interaction of the fields produces the movement of
the shaft-armature
A commutator switches the direction of the current flow,
yielding continuous motion
Problem!!!!
Motors need at least 200mA to start on how could I do
this from Arduino?!
Solution: Using transistor.
52 Superiors innovation Center
Transistor:
Transistor History:
• Invention: 1947,at Bell Laboratories.
• John Bardeen, Walter Brattain, and William Schockly developed the first model
of transistor (a Three Points transistor, made with Germanium)
• They received Nobel Prize in Physics in 1956 "for their researches on
semiconductors and their discovery of the transistor effect"
• First application: replacing vacuum tubes (big & inefficient).
• Today: millions of Transistors are built on a single silicon wafer in most
common electronic devices
What is a transistor?
• The Transistor is a three-terminal, semiconductor device.
• It’s possible to control electric current or voltage between
two of the terminals (by applying an electric current or
voltage to the third terminal). The transistor is an active
component.
53 Superiors innovation Center
With the Transistor we can make amplification devices or
electric switch. Configuration of circuit determines
whether the transistor will work as switch or amplifier
As a miniature electronic switch, it has two operating
positions: on and off. This switching capability allows
binary functionality and permits to process information in
a microprocessor.
Transistor symbols
54 Superiors innovation Center
Transistor operation
force – voltage/current
water flow – current
- amplification
Transistor Electrical symbol:
55 Superiors innovation Center
Connection:
Why we need the
diode?!
Action Round #1- Turn the motor
on and off
Connection on breadboard:
56 Superiors innovation Center
Speed of the Motor:
To control the speed of the motor we use PWM at the
base of the transistor.
Action Round #2- Control the
speed of the motor using
potentiometer
Connection on breadboard:
57 Superiors innovation Center
Direction of the Motor:
An H bridge is an electronic circuit that enables a voltage to be applied
across a load in either direction.
These circuits are often used in robotics and other applications to allow
DC motors to run forwards and backwards.
How to use this with Arduino?!
Solution: using transistor.
58 Superiors innovation Center
IC (L293D):
v
Connections:
59 Superiors innovation Center
Examples:
Example1: Control the direction of a DC motor using H-bridge
Example2: Control the speed and direction of a DC using H-
bridge and potentiometer
Servo Motor:
It is sometimes necessary to move a motor to a specific
position
DC motors are not built for this purpose, but servo motors are
Servo motors are adapted DC motors:
Gear reduction
Position sensor (potentiometer)
Electronic controller
Range of at least 180 degrees
60 Superiors innovation Center
Servo Motor types:
1) Continuous
2) Standard
Servo Motor contents:
61 Superiors innovation Center
Arduino Library:
Arduino libraries are a convenient way to share code
such as device drivers or commonly used utility functions.
The Arduino IDE comes with a set of standard libraries
for commonly used functionality.
These libraries support all the examples included with the
IDE.
Standard library functionality includes basic
communication functions and support for some of the
most common types of hardware like: Servo Motors and
LCD displays.
Servo Motor Library:
#include <Servo.h>
Servo myservo ;
myservo.attach(9);
myservo.write(pos);
Servo Motor Connection:
Servo motor has 3 wires:
Vcc, Ground, control signal
62 Superiors innovation Center
Servo Motor Code:
Action Round#1– Using POT to
control a servo motor
Goal: at POT max turn angle, servo motor at 180 degrees; at
POT min angle, servo motor at 0 degrees. POT position is
used to control Servo position
You will be using: Analog Write and Serial Monitor
Software
• Servo Object Hardware
Arduino has a Servo library <Servo.h> • Servo motor (1)
Once included, we can create a Servo • Potentiometer (1)
object and directly use a library function Breadboard
such as servo.write(val) Jumper Wires
• analogRead();
• analogWrite()
• map();
• pinMode();
63 Superiors innovation Center
Action Round#1– Using POT to
control a servo motor
Software
#include <Servo.h>
Servo myservo; // create servo object to control a servo
int potpin = 0; // analog pin used to connect the potentiometer
int val; // variable to read the value from the analog pin
void setup()
{
myservo.attach(9); // attaches the servo on pin 9 to the servo object
Serial.begin(9600);
}
void loop()
{
val = analogRead(potpin); // reads the value of the potentiometer (value between 0 and 1023)
Serial.println(val);
val = map(val, 0, 1023, 0, 179); // scale it to use it with the servo (value between 0 and 180)
myservo.write(val); // sets the servo position according to the scaled value
delay(15); // waits for the servo to get there
}
Ultrasonic Sensor
An ultrasonic transducer is a device that converts energy
into ultrasound, or sound waves above the normal range
of human hearing.
64 Superiors innovation Center
Systems typically use a transducer which generates
sound waves in the ultrasonic range, above 18,000 hertz,
by turning electrical energy into sound, then upon
receiving the echo turn the sound waves into electrical
energy which can be measured and displayed.
Ultrasonic operation
Ultrasonic sensors (also known as transceivers when they both send and
receive) work on a principle similar to radar or sonar which evaluate
attributes of a target by interpreting the echoes from radio or sound
waves respectively.
Ultrasonic sensors generate high frequency sound waves and evaluate
the echo which is received back by the sensor.
Sensors calculate the time interval between sending the signal and
receiving the echo to determine the distance to an object.
65 Superiors innovation Center
Interfacing & Features
• description: ultrasonic transducer - receiver
• Max. input voltage: 20Vrms
• operating temperature: -20°C to +85°C
• range: 0.04 to 4m
• nominal frequency: 40kHz
• Sensitivity: -67dB min.
• Sound pressure: 112dB min.
66 Superiors innovation Center
Applications for ultrasonic
Ultrasonic Library
#include "Ultrasonic.h“
Ultrasonic ultrasonic(TRIGGER_PIN ,ECHO_PIN);
ultrasonic.Ranging(CM);
Add a library to the Arduino
67 Superiors innovation Center
Examples:
Example1: Measure the distance and print it to the serial
monitor.
Example2: Make an alarm system if the distance is lower than
a specific value (use buzzer).
IR Sensor
• IR Sensors work by using a specific light sensor to detect
a select light wavelength in the Infra-Red (IR) spectrum.
• By using an LED which produces light at the same
wavelength as what the sensor is looking for, you can
look at the intensity of the received light.
• When an object is close to the sensor, the light from the
LED bounces off the object and into the light sensor.
• This results in a large jump in the intensity, which we
already know can be detected using a threshold.
68 Superiors innovation Center
IR Sensor operation
69 Superiors innovation Center
IR Sensor connection
Digital Read
Examples:
Example1: Connect the IR sensor and use serial monitor to
check the values.
Example2: Make a smart system for a Factory which calculates
the number of input persons and print it on the serial monitor
(use IR sensor).
What if we want to calculate the output and the input?!
70 Superiors innovation Center
Electricity
How can we use Arduino with electricity? (Relay)
Relay
• A relay is an electrically operated switch.
• Many relays use an electromagnet to mechanically
operate a switch, but other operating principles are also
used, such as solid-state relays.
• Relays are used where it is necessary to control a circuit
by a low-power signal (with complete electrical isolation
between control and controlled circuits), or where several
circuits must be controlled by one signal.
71 Superiors innovation Center
How it works?
72 Superiors innovation Center
Examples:
Example1: use the Arduino to turn the relay on and off, did you
hear any sound?!
Example2: use the relay to control a light bulb 220v AC
73 Superiors innovation Center
7-segment
Binary numbers are necessary, but very hard to read or interpret
What is available to display binary to decimal information?
A seven-segment L.E.D. display
A seven-segment display may have 7, 8, or 9 leads on the chip.
Usually leads 8 and 9 are decimal points.
The figure below is a typical component and pin layout for a seven
segment display.
The light emitting diodes in a seven-segment display are arranged in the figure
below.
74 Superiors innovation Center
There are two types of displays available, common anode
and common cathode.
Examples:
Example1: show the numbers from 0 to 9 on the 7 segment
Example2: use the 7-segment with the counter you did using
IR sensor.
75 Superiors innovation Center
LCD
A liquid-crystal display (LCD) is a flat panel display, electronic visual display, or video
display that uses the light modulating properties of liquid crystals. Liquid crystals do not
emit light directly.
Pins Configuration
76 Superiors innovation Center
Pin 1 and 2 are the power supply for the LCD.
Pin 3 is a control pin, Vee, which is used to alter the
contrast of the display. Ideally, this pin should be
connected to a variable voltage supply. A preset
potentiometer connected between the power supplies
lines, with its wiper connected to the control pin.
Pin 4 is the Register Select (RS) line, the first of the three
command control inputs, when the line is low, data bytes
transferred to the LCD as command, By setting the RS
line high, character data is transferred to the LCD.
Pin 5 is the Read/Write (R/W) line. This line is pulled low
in order to write commands or character data, or pulled
high to read character data or status information from its
register.
Pin 6 is the Enable (E) line. This is used to initiate the
actual transfer of commands.
Pins 7 to 14 are the eight data bus line (D0 to D7). Data
can be transferred to the display. Either as a single 8-bit
byte or as two 4-bit mode is beneficial.
Pins 15 & 16 are for the backlight.
77 Superiors innovation Center
LCD Library:
Check the examples in the LCD library
Auto scroll: Shift text right and left.
Blink: Control of the block-style cursor.
Cursor: Control of the underscore-style cursor.
Display: Quickly blank the display without losing what's on it.
Hello World: Displays "hello world!" and the seconds since
reset.
Scroll: Scroll text left and right.
Serial Display: Accepts serial input, displays it.
Set Cursor: Set the cursor position.
Text Direction: Control which way text flows from the
cursor.
Keypad:
78 Superiors innovation Center
Matrix Keypad Connections
Adding Keypad Library
79 Superiors innovation Center
Write here (Keypad)
Try the example (customKeypad) in the library
Basic I/O - Serial Reads
Serial Read – Key Concepts:
• Reminder Serial.begin(): Sets the data rate in bits per
second (baud) for serial data transmission
• Syntax: Serial.begin(baud)
• Example: Serial.begin(9600) sets serial baud rate to 9600
bits per second
• Serial.availible(): Get the number of bytes that have
already arrived and been stored in the serial receive
buffer (which holds 64 bytes).
• Syntax: Serial.availible()
80 Superiors innovation Center
• Serial.read(): Reads incoming serial data. Removes data
from serial buffer
• Syntax: Serial.read()
Action Round#1- Serial Read –
Read Input
• Project Name: Read Input
• Objective: Read input from Serial Monitor input and write
it back out
Software • Hardware
• Serial.begin() • Arduino Uno (1)
• Serial.availible()
• Serial.read()
• Serial.print()
• Serial.write()
• Serial.println()
Action Round#1- Serial Read–
Read Input
byte incomingByte;
void setup() {
// Turn the Serial Protocol ON
Serial.begin(9600);
}
void loop() {
if (Serial.available()) {
incomingByte = Serial.read();
Serial.write(incomingByte);
}
}
81 Superiors innovation Center
Action Round#2- Serial Read–
Read Entire Buffer
char character;
String content = "";
void setup() {
Serial.begin(9600); // opens serial port, sets data rate to 9600
bps
}
void loop() {
while(Serial.available()) {
character = Serial.read();
if (character != "") {
Serial.println(character); //Print string to serial
character = ""; //Empty string
Bluetooth
• Bluetooth is a wireless technology standard for
exchanging data over short distances (using short-
wavelength UHF radio waves in the ISM band from 2.4 to
2.485 GHz) from fixed and mobile devices and building
personal area networks (PANs).
• Invented by telecom vendor Ericsson in 1994, it was
originally conceived as a wireless alternative to RS-232
data cables.
• It can connect several devices, overcoming problems of
synchronization.
82 Superiors innovation Center
Bluetooth HC-06 Module
Examples:
Example1: Send the data from Bluetooth and print it to the
serial monitor.
Example2: use the Bluetooth to control LED & Buzzer.
Robotic Car Build and Control
83 Superiors innovation Center
What are robots used for?
Project Equipment
Arduino Uno.
Car Chassis Kit.
Motor Driver.
Batteries (power supply).
84 Superiors innovation Center
H-Bridge Module Wiring
Example:
Example1: Make car avoiding robot using ultrasonic.
Example2: Make a Bluetooth controlled robot.
85 Superiors innovation Center