INTRODUCTION TO ARDUINO
PROGRAMMING
Jinasena Innovation & Technology Institute - Ekala
Content Courtesy
DEC 2014
What is a Microcontroller ?
(µC, MCU)
• Computer on a single integrated chip
– Processor (CPU)
– Memory (RAM / ROM / Flash)
– I/O ports (USB, I2C, SPI, ADC)
• Companies that manufacture microcontrollers :
– Intel: 4004, 8008, etc.
– Atmel: AT and AVR
– Microchip: PIC
– Freescale: (multiple manufacturers)
• Used in:
– Cellphones,
– Toys
– Household appliances
– Cars
– Cameras
2
Shrinking a Microcontroller
Kinetis KL02
• 1.9 x 2.00 x 0.56 millimetres
• Good match for 'internet of things' devices
3
The ATmega328P Microcontroller
(used by Arduino UNO)
• AVR 8-bit RISC architecture
• Available in DIP package
• Up to 20 MHz clock
• 32kB flash memory
• 1 kB SRAM
• 23 programmable I/O channels
• Six 10-bit ADC inputs
• Three timers/counters
• Six PWM outputs
4
What is Arduino Not?
• It is not a chip (IC)
• It is not a board (PCB)
• It is not a company or a manufacturer
• It is not a programming language
• It is not a computer architecture
(although it involves all of these things...)
5
So what is Arduino?
It’s a movement, not a microcontroller:
• Founded by Massimo Banzi and David
Cuartielles in 2005
• Based on “Wiring Platform”, which dates to
2003
• Open-source hardware platform
• Open source development environment
– Easy-to learn language and libraries (based
on Wiring language)
– Integrated development environment (based
on Processing programming environment)
– Available for Windows / Mac / Linux
6
The Many Flavors of Arduino
• Arduino Uno
• Arduino Leonardo
• Arduino LilyPad
• Arduino Mega
• Arduino Nano
• Arduino Mini
• Arduino Mini Pro
• Arduino BT
7
Arduino Add-ons (Shields)
• TFT Touch Screen
• Data logger
• Motor/Servo shield
• Ethernet shield
• Audio wave shield
• Cellular/GSM shield
• WiFi shield
• Proto-shield
• ...many more
8
Getting to know the Arduino:
Electrical Inputs and Outputs
LED 14 digital inputs/outputs
Input voltage: 7-12 V (6 PWM outputs)
(USB, DC plug, or Vin) Power
Max output current per pin: 40 mA indicator
USB connection Reset
Button
16 MHz clock
Voltage regulator ATmega328P
AC/DC adapter
jack DC voltage
6 analog
supply
inputs
(IN/OUT) 9
Download and Install
• Download Arduino compiler and development environment from:
http://arduino.cc/en/Main/Software
• Current version: 1.0.1
• Available for:
– Windows
– MacOX
– Linux
• No installer needed... just unzip to a convenient location
• Before running Arduino, plug in your board using USB cable
(external power is not necessary)
• When USB device is not recognized, navigate to and select the
appopriate driver from the installation directory
• Run Arduino
10
Select your Board
11
Select Serial Port
12
Elements of the Arduino IDE
• Text editor
– syntax and keyword
colouring
– automatic
indentation
– programming
shortcuts
• Compiler
• Hardware Interface
– Uploading programs
– Communicating with
Arduino via USB
13
Using the Arduino IDE
Name of sketch
Compile sketch
Upload to board
Serial Monitor
Program area
Save
Open
New
Messages /
Errors
14
Arduino Reference
Arduino Reference is installed locally
or available online at http://arduino.cc/
15
Arduino Sketch Structure
• void setup()
void setup() {
– Will be executed only // put your setup code here, to run once:
when the program
}
begins (or reset button
void loop() {
is pressed) // put your main code here, to run repeatedly:
• void loop() }
– Will be executed
repeatedly
Text that follows // is a comment
(ignored by compiler)
Useful IDE Shortcut: Press Ctrl‐/
to comment (or uncomment) a
selected portion of your program.
16
Activity 1: LED Blink
Load the “Blink” example
(FileExamplesBasicsBlink)
Use pin 13 as digital output void setup() {
// initialize the digital pin as an output.
// Pin 13 has an LED connected on most Arduino boards:
pinMode(13, OUTPUT);
Set output high (+5V) }
void loop() {
digitalWrite(13, HIGH); // set the LED on
Wait 1000 milliseconds delay(1000); // wait for a second
digitalWrite(13, LOW); // set the LED off
delay(1000); // wait for a second
Set output low (0V) }
• Compile, then upload the program.
• Congratulations! You are now blinkers!
• Adding Comments in your code is good practice !!!
17
Now connect your own LED
Anatomy of an LED:
Notes:
• Resistor is needed to limit current
• Resistor and LED may be
interchanged
(but polarity of LED is important)
http://www.wikipedia.org/ • Pin 13 is special: has built-in
resistor and LED
• Change program and upload
18
Example: Using a Solderless
Breadboard
19
Experimenting
• Change the blink rate
– how fast can the LED blink (before you can no
longer perceive the blinking?)
20
Activity 2: LED Bargraph
• Connect an LED bargraph to the arduino.
• Try to implement the
Knight Rider Light on it.
21
Activity 2: LED Bargraph
Experimenting
How would you change the speed of the Knight Rider
Light?
Is there another easy way to change it with minimal
change to the code?
Hint : Variables
22
Variables
A variable is a way of naming and storing a value for later use by the
program, such as data from a sensor or an intermediate value used in a
calculation.
It has a type, a name & a value.
Variable Declaration
Variable Type Variable Name Variable Stored Value
Int stands for integer User determined Int type can only
stores a 16-bit (2-byte) No spaces save integer values
value
23
Activity 2: LED Bargraph
Experimenting
If your knight rider light is to modified so that a single LED travels twice
before changing direction, (Left – left – right - right), how would you
implement it?
Is there any alternate method to achieve this easily?
Hint : Functions
24
Functions
Segmenting code into functions allows a programmer to create modular
pieces of code that perform a defined task and then return to the area of
code from which the function was "called". The typical case for creating a
function is when one needs to perform the same action multiple times in a
program.
Functions must be created outside of ‘Setup’ & ‘Loop’.
The contents within the function is executed only if it is ‘called’ within setup
or loop.
Fun Fact : There are two required functions in any Arduino sketch, setup() and
loop().
25
Digital Input: Reading Switches and
Buttons
Writing HIGH to an input pin:
enables an internal pull-up resistor
void setup() {
pinMode(11, OUTPUT); // Use pin 11 for digital out
pinMode(12, INPUT); // Use pin 12 for digital input
digitalWrite(12, HIGH); // Enable pull‐up resistor
}
void loop() {
boolean state;
state = digitalRead(12); // read state of pin 12
digitalWrite(11, state); // set state of pin 11 (LED)
delay(100); // wait for a 1/10 second
}
• Turn on/off LED based on switch
• Pin 12 reads LOW when switch is closed
• Pin 12 reads HIGH when switch is open (pull-up)
Without the internal pull-up resistor,
unconnected digital inputs could read
either high or low
26
Digital Input: Reading Switches and
Buttons
Change the line :
digitalWrite(11, state);
Into :
digitalWrite(11, !state);
How has this changed the performance of the
system?
27
Activity 3: Switching
Implement a sketch so that two LEDs are controlled with two
different push buttons.
28
Serial Communication - Writing
IMPORTANT: • Serial.begin(baud)
USB serial
communication is Initialize serial port for communication (and sets baud
shared with rate)
Arduino pins 0
and 1 (RX/TX) Example:
– Serial.begin(9600); // 9600 baud
Serial.print(val), Serial.print(val,fmt)
Format can be:•
BIN, HEX, OCT,
Prints data to the serial port
or an integer Examples:
specifying the – Serial.print(“Hi”); // print a string
number of digits
to display – Serial.print(78); // works with numbers, too
– Serial.print(variable); // works with variables
– Serial.print(5,BIN); // will print 1001110
• Serial.println(val)
Same as Serial.print(), but with line-feed
29
Serial Communication - Writing
Serial Monitor
Use the Serial Monitor
to see the output
(Ctrl + Shift + M)
30
Activity 4: Loop Counter
Implement a sketch to count and display
the number of loop counts that occurred.
A loop is executed every two seconds.
Refer to the flow chart.
31
OPTIONAL
Activity 5: Switch Counter
Implement a sketch to count the number of times a
switch is pressed.
The current counter value is displayed every half a
second.
32
For Loops
Try the following example
sketch :
Can you describe the
performance of the LED?
33
For Loops
The for statement is used to repeat a block of statements
enclosed in curly braces. An increment counter is usually used
to increment and terminate the loop. The for statement is
useful for any repetitive operations.
Declare Variable & Initialize – initial value of the counter
Test – Condition so that the next iteration is executed
Increment or Decrement – Change to the counter value done at
t++ is a short form of• each iteration
t=t+1 which means
increment by 1
34
For Loops
Experimenting
Make the following changes in the above sketch and do
monitor the changes.
Add Serial.print() within the for loop and after it.
Change the intial value into negative & positive numbers.
Change the test condition.
Change the increment / decrement value.
Can you draw the flow chart to the sketch in the previous for
loop example?
35
Activity 6: For Loops
Write a flowchart & sketch to incorporate 2 Blinking LEDs.
A single LED should blink 5 times where after the 2nd LED
should blink another 5 times.
After both LEDs have blinked 5 times each both LEDs should
be off for 1 second and then remain in the ON state
indefinitely.
36
Analog Input and Sensors
Reference Voltage (optional) • Six analog inputs:
A0, A1, A2, A3, A4, A5
• AREF = Reference voltage
(default = +5 V)
• 10 bit resolution:
– returns an integer from 0 to
1023
– result is proportional to the
pin voltage
• All voltages are measured
relative to GND
Note: If you need additional
Analog Inputs digital I/O, the analog pins can be
re-assigned for digital use:
pinMode(A0, OUTPUT); 37
Potentiometers
(variable resistors, rheostats)
38
Volume Knob
• Connect the potentiometer from 5V to GND
• Use analogRead(A0) to measure the voltage on the center pin
• Set the LED blink rate depending on the reading
39
Reading Analog Values
value = analogRead(pin)
Reads the analog measurement on pin & returns integer
between 0 and 1023
Note: Do NOT use
pinMode(A0, INPUT) unless
you want to use A0 for DIGITAL
input.
40
Activity 7: Volume Knob
Write a sketch to vary a LED blink rate using analog inputs.
How would you write a flow chart to this sketch?
41
OPTIONAL
Activity 8: Speed Varying Knight Rider
• Using the analog input and a LED bargraph & write a
sketch to control the speed of the knight rider circuit
according to the analog input.
42
Activity 7: Photo Resistor Module
The photo resistor module gives a analog voltage according
to the light intensity it senses.
Use your earlier program to interface this sensor module to
change the blinking rate of your LED.
Use the Serial Monitor to check between what
values the Arduino receives.
43
if statements
The if() statement is the most basic of all programming
control structures. It allows you to make something happen
or not depending on whether a given condition is true or not.
Some methods of
implementing an if
statement are as follows :
44
if statements
Let's try the
following example
using a analog input
45
if statements
Let's try to draw a flow chart for this example
46
if statements
Other comparison operators
47
Nested if statements : Water Tank
Example
Imagine a water tank where different lights are to be
illuminated according to the water level in it.
There are 3 sensors to
detect the water level
namely A, B & C
How would you draw a
flow chart for it?
48
Nested if statements : Water Tank
Example
Flow Chart for the previous problem.
49
Nested if statements : Water Tank
Example
If statement code for the previous problem.
50
Activity 10 : IF Statements
Using the analog input and a LED bargraph write a program
to on a single LED according to the value taken from the
analog input.
HINT : Use your knowledge on if loops and functions
51
Analog Output?
• Most microcontrollers
have only digital outputs
• Pulse-width Modulation:
Analog variables can be
represented by the duty-
cycle (or pulse-width) of
a digital signal
http://arduino.cc/en/Tutorial/PWM
52
PulseWidth Modulation (PWM)
PWM available on pins 3, 5, 6, 9, 10, 11
• analogWrite(pin,val)
set the PWM fraction:
– val = 0: always off
– val = 255: always on
• Remember to designate pin
for digital output:
pinMode(pin,OUTPUT);
(usually in setup)
• Default PWM frequency:
– 16 MHz / 215 = 488.28125 Hz
Note: the PWM frequency and
resolution can be changed by
re-configuring the timers
53
PulseWidth Modulation (PWM)
Try the following sketch
Try changing the values
of the PWM and
observe the LED.
How would you describe
the LED’s brightness?
54
Activity 11 : PWM LED Dimmer
• Use PWM to control the brightness of an LED
– connect LED to pin 3, 5, 6, 9, 10 or 11
– remember to use 220 Ω current-limiting resistor
• Set the brightness from the potentiometer.
Useful:
• newValue = map(oldValue, a, b, c, d)
Converts/maps a number in the range (a:b) to a new number in the range (c:d)
Example:
– newValue = map(oldValue,0,1023,0,255);
55
Servomotors
http://www.parallax.com/
• Standard servo:
– PWM duty cycle controls direction:
– 0% duty cycle 0 degrees
– 100% duty cycle 180 degrees
• Continuous-rotation servo:
– duty cycle sets speed and/or direction
56
Activity 12 : Servomotor Control
• Build a program that turns a servomotor from
0 to 180 degrees, based on potentiometer
reading
• Report setting to the serial monitor
57
Controlling Relays and Solenoids
• Electromechanically
-actuated switch
• Provides electrical
isolation
• Typically few ms
response time
Note: Arduino cannot supply
enough current to drive relay coil
58
Relay Driver Circuit
• NPN transistor: acts like a current-controlled switch
• MOSFET will also work
• Diode prevents back-EMF (associated with inductive
loads)
• Coil voltage supply and Arduino share common GND
59
60