Introduction To Arduino Programming: Jinasena Innovation & Technology Institute - Ekala
Introduction To Arduino Programming: Jinasena Innovation & Technology Institute - Ekala
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)
4
What is Arduino Not?
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)
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
AC/DC adapter
jack DC voltage
6 analog
supply
inputs
(IN/OUT) 9
Download and Install
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
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)
16
Activity 1: LED Blink
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) }
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
20
Activity 2: LED Bargraph
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
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
}
27
Activity 3: Switching
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
30
Activity 4: Loop Counter
31
OPTIONAL
Activity 5: Switch Counter
32
For Loops
33
For Loops
Can you draw the flow chart to the sketch in the previous for
loop example?
35
Activity 6: For Loops
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
40
Activity 7: Volume Knob
41
OPTIONAL
Activity 8: Speed Varying Knight Rider
42
Activity 7: Photo Resistor Module
43
if statements
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
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
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
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)
54
Activity 11 : PWM LED Dimmer
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
57
Controlling Relays and Solenoids
• Electromechanically
-actuated switch
• Provides electrical
isolation
• Typically few ms
response time