Arduino Programming and Basics Guide
Arduino Programming and Basics Guide
(EED-308)
1
Arduino:
Introduction & Programming
Syllabus
A software environment
A development board Syllabus
➢ 8-bit microcontroller ➢ Cross-compiler
➢ Programming hardware ➢ Debugger
➢ USB Programming ➢ Programmer
Interface
➢ I/O Pins
DR. ROHIT SINGH AND PROF. SONAL SINGHAL 5
Arduino Environment
Shields are boards that can be plugged on top of the Arduino PCB extending its
Syllabus
capabilities. The different shields follow the same philosophy as the original toolkit:
they are easy to mount, and cheap to produce.
➢ Daughter boards
➢ Unique functionalities
➢ Easy to attach
➢ Good libraries provided
Syllabus
Syllabus
Analog Input
Pins/Digital I/O
5V pin caution!
Arduino ATmega328
Microcontroller ATmega328 (8-bit microprocessor)
Operating Voltage 5V
Input Voltage (Recommended) 7-12V
Input Voltage (Limit) 6-20V
Digital I/O Pins 14 (of which 6 provide PWM output)
Analog Input Pins 6 (one 8-channel 10-bit ADC)
DC Current per I/O Pin Syllabus
40 mA
DC Current for 3.3V Pin 50 mA
Flash Memory 32 KB (of which 0.5 KB used by
bootloader)
SRAM 2 KB
EEPROM 1 KB
Clock Speed 16 MHz
12
Arduino IDE
Syllabus
13
Arduino Basic Programming Setup
• Connect the Arduino board to your laptop/desktop using USB
cable.
• Launch the Arduino IDE.
• Upload the blink example on the board and test whether that is
working.
Run a Program
• Select your Arduino in the Tools > Board menu
Syllabus
• Select your serial port in the Tools > Port menu
There should be only one selection (e. g. COM3)
• Upload the program with the upload button
This writes the program onto the Flash of the Arduino
• The LED near pin 13 of the Arduino should blink
14
Arduino Programming
Bare minimum code
void setup()
{
// put your setup code here, to run
once:
}
void loop()
Syllabus
{
// put your main code here, to run
repeatedly:
}
setup : It is called only when the Arduino is powered on or reset. It is used to
initialize variables and pin modes
loop : The loop functions runs continuously until the device is powered OFF.
The main logic of the code goes here. Like “while (1) loop”.
COMMENTS
SETUP
LOOP
16
Microcontroller Programming Essentials
Debugging Timing
Serial
Communication
17
What We Will Be Building?
—Massimo
Pin mode configuration
Function: pinMode()
Mode:
❑ INPUT,
Analog
❑ OUTPUT, I/O
❑ INPUT_PULLUP
19
Pin mode configuration
Syntax: pinMode(pin, mode)
Syllabus
Key points:
✓ Only digital pins have pullup resistors
✓ Analog pins don’t have internal pullup resistors.
✓ For analog pins the INPUT and INPUT_PULLUP are same.
Digital
Caution: Floating! I/O
20
Digital I/O
Digital Read
Function: digitalRead()
Description: Reads the value from a specified digital pin, either HIGH or LOW.
Syntax: digitalRead(pin)
Pin: The Arduino pin number e.g. 1, 2, 13, A1, etc.
Returns: HIGH or LOW
Syllabus
Digital Write
Function: digitalWrite()
Description: Write a HIGH or a LOW value to a digital pin.
Syntax: digitalWrite(pin, value)
Pin: The Arduino pin number e.g. 1, 2, 13, A1, etc.
Value: HIGH or LOW Digital
I/O
21
Analog
Analog I/O I/O
Analog
Analog Read I/O
Function: analogRead()
Description: Reads the value from the specified analog pin.
Syntax: analogRead(pin)
Pin: The Arduino analog pin number e.g. A0- A5.
Returns: The analog reading on the pin. Although it is
limited to the resolution of the A/D converter (0-1023 for 10-
bit ADC). Data type: int.
22
Blink
LED!
If you experiment with this, you will
notice that if you make the ON delay
different from the off delay, you can
make the LED brighter by leaving it on
for longer, and you can make the LED
dimmer by leaving it off for longer.
✓ Despite the name, it does not produce a true analog voltage — instead, it
simulates an analog output by rapidly switching a digital signal on and off,
varying the duty cycle to control the average power delivered.
✓ This gives the effect of variable voltage, which is useful for applications like
dimming LEDs or controlling motor speed.
Caution ! The analogWrite function has nothing to do with the analog pins or
the analogRead function
25
Analog I/O Analog
I/O
Function: analogWrite()
Description: Writes an analog value (PWM wave) to a pin.
Syntax: analogWrite(pin, value)
Pin: The PWM-capable digital pin (3, 5, 6, 9, 10, 11 mard with ~)
Value: the duty cycle: between 0 (always off) and 255 (always on).
Allowed data types: int.
26
Light Control!
Parameters Syllabus
speed: baud rate (Supported baud rates are 300, 600, 1200, 2400, 4800,
9600, 14400, 19200, 28800, 31250, 38400, 57600, and 115200).
config: sets data, parity, and stop bits. Valid values are SERIAL_5N1,
SERIAL_7E1, SERIAL_6O1, and default one is SERIAL_8N1.
Debugging
Function: if(Serial)
Description: This will check the USB serial connection and it always return True.
Syntax: if(Serial)
Syllabus
Function: [Link]()
Description: The first byte of incoming serial data available (or -1 if no data
is available). Data type: int.
Function: [Link]()
Description: It returns the number of bytes available to read.
Syntax: [Link]()
void setup() { Open Serial Monitor, type Hello, and you’ll see
[Link](9600); // Start
serial communication at 9600 bps
} You sent: H
You sent: e
void loop() { Syllabus You sent: l
if ([Link]() > 0) { You sent: l
// Check if data is available You sent: o
char receivedChar =
[Link](); // Read one
character
[Link]("You sent: ");
[Link](receivedChar);
// Send it back
Debugging
}
}
30
Debugging
Function: [Link]()
Description: The [Link]() function is used to send data from the Arduino to the computer
(or another device) over the serial communication port. It send raw bytes (characters, numbers,
or binary data) from the Arduino to the receiving end — typically the Serial Monitor on your
computer, or another microcontroller/PC.
Syntax: [Link](val), [Link](str), and [Link](buf, len)
Parameters
val: a value to send as a single byte, str: a string to send as a series of bytes
buf: an array to send as a series of bytes, len: theSyllabus
number of bytes to be sent from the array.
Returns: write() will return the number of bytes written, though reading that number is optional.
Type Example
Single character [Link]('A'); → Sends ASCII 65
Integer (as byte) [Link](65); → Sends byte with value 65
Array of bytes [Link](buffer, 5); → Sends 5 bytes from buffer
String (character array) [Link]("Hello");
Debugging
31
Debugging
Try it Out!
[Link]()
Syllabus
[Link]()
[Link]()
Debugging
32
Timing
Blocking
Function: delay(val)
Description: It produces delays in milli-second.
Function: delayMicroseconds(val)
Description: It produces delays in micro-second.
Non-blocking
Function: millis()
Description: Returns the number of milliseconds passed since the Arduino board began
running the current program. This number will overflow (go back to zero), after approximately
50 days. Its resolution is 1 milliseconds.
Function: micros()
Description: Returns the number of microseconds passed since the Arduino board began
running the current program. This number will overflow (go back to zero), after approximately
71 minutes. Its resolution is 4 microseconds.
void loop() {
const int ledPin = 13; unsigned long currentMillis =
// Built-in LED millis();
unsigned long previousMillis
= 0; // Stores last time LED if (currentMillis -
was updated previousMillis >= interval) {
const long interval = 1000; // Save the last time we
// Interval in milliseconds toggled the LED
(1 second) previousMillis =
currentMillis;
void setup() { // Toggle the LED
pinMode(ledPin, OUTPUT); digitalWrite(ledPin,
} !digitalRead(ledPin));
}
// Other tasks can run here
without being blocked
}
Using millis() allows us to check how much time has passed since the
last LED toggle. This avoids blocking the processor, enabling
multitasking.
Problem Statement:
Blink two LEDs (on pins 12 and 11) at different intervals (500ms and
800ms) simultaneously without using delay()
const int led1Pin = 12;
const int led2Pin = 11; void loop() {
unsigned long currentMillis = millis();
unsigned long previousMillis1 = 0;
unsigned long previousMillis2 = 0; // Control LED 1
if (currentMillis - previousMillis1 >= interval1)
const long interval1 = 500; // 0.5 {
seconds previousMillis1 = currentMillis;
const long interval2 = 800; // 0.8 digitalWrite(led1Pin, !digitalRead(led1Pin));
seconds }
40
tone() and noTone() functions
Generates a square wave of the specified frequency (and 50% duty cycle)
on a pin. A duration can be specified, otherwise the wave continues until
a call to noTone().
Only one tone can be generated at a time. If a tone is already playing on a
different pin, the call to tone() will have no effect. If the tone is playing on
the same pin, the call will set its frequency.
Parameters
pin: the Arduino pin on which to generate the tone.
frequency: the frequency of the tone in hertz. Allowed data types: unsigned int.
duration: the duration of the tone in milliseconds (optional). Allowed data types: unsigned
long.
41
Problem Statement:
Parameters
pin: the number of the Arduino pin on which you want to read the pulse. Allowed data types: int.
value: type of pulse to read: either HIGH or LOW. Allowed data types: int.
timeout (optional): the number of microseconds to wait for the pulse to start; default is one
second. Allowed data types: unsigned long.
44
Example of pulseln function
Measure the duration of external pulse.
✓ The Echo pin goes HIGH when the pulse is sent and stays HIGH
until the echo returns.
void setup() {
// Initialize serial communication
[Link](9600);
void loop ()
Maskable Interrupt: For Arduino
{
Uno, the external interrupts are
maskable interrupts.
noInterrupts();
//code
Interrupts()
interrupts(): It will enable the Pin
No. 2 and 3 for accepting the //code
interrupts.
}
attachInterrupt()
Syntax
attachInterrupt(digitalPinToInterrupt
(pin), ISR, mode);
Parameters Syllabus
pin: Arduino pin number (2 or 3).
ISR: the ISR to call when the interrupt occurs; this
function must take no parameters and return nothing. This
function is sometimes referred to as an interrupt service
routine.
mode: defines when the interrupt should be triggered.
Syntax
attachInterrupt(digitalPinToInterrupt(pin), ISR, mode);
Syntax
detachInterrupt(digitalPinToInterrupt(pin);
void setup() {
pinMode(ledPin, OUTPUT);
pinMode(interruptPin, INPUT_PULLUP);
Syllabus
attachInterrupt(digitalPinToInterrupt(interruptPin), blink, CHANGE);
}
void loop() {
digitalWrite(ledPin, state);
}
void blink() {
state = !state; // ISR, use volatile data type modifier
}
Objective
Detect when an object comes in front of the IR sensor
and immediately toggle an LED using an interrupt — no
delays, no missed events.
•The IR sensor emits infrared light and detects reflection.
•When an object is detcted, it reflects the IR light → sensor
output goes LOW (active-low).
•We attach an interrupt to detect the FALLING edge (HIGH →
LOW). And the interrupt service routine (ISR) runs immediately.
/* IR Sensor with Interrupt Detects object using external interrupt on pin 2
Toggles LED on pin 13 when object is detected*/
[Link]("Object Detected!");
void setup() {
// Set up pins
pinMode(buttonPin, INPUT);
pinMode(ledPin, OUTPUT);
void loop() {
// Main program keeps running
[Link]("Button Pressed: ");
[Link](count);
[Link](" times");
#include <EEPROM.h>
Standard Libraries: EEPROM
• read()
• write()
• update()
• get()
• put() Syllabus
• EEPROM[]
void loop() {}
void loop() {}
Function: [Link]()
Description: Similar to write(), but checks if the new value
differs from the old [Link]:
[Link](address,value)
Syllabus
Parameters
address: the location to read from, starting from 0-1023
value: the value to be written, from 0 to 255 (byte)
Syllabus
EEPROM[address] = value; // Write
value = EEPROM[address]; // Read
void setup() {
[Link](9600);
[Link](address, variable) // Save float to EEPROM
[Link](10, temperature);
[Link]();
// Retrieve it
float temp;
[Link](10, temp);
[Link](address, variable)
[Link]("Temperature: ");
[Link](temp);
}
void loop() {}
Don't Forget This!
Even though update() and put() call commit()
automatically, write(), and [] do not.
[Link](0, 42);
// OR
EEPROM[0] = 42;
[Link]();
Auto-
Function Purpose commit? Best For
read() Read a byte No Simple reads
write() Write a byte No Single-byte writes
Where:
•I = Desired current through LED
(e.g., 15 mA)
•Vsupply = Voltage from Arduino
pin (5V or 3.3V)
•Vf = Forward voltage of the LED
(typically 1.8V–3.3V depending on
color)
•R = Resistor value (in ohms)
Let’s say:
•Arduino pin voltage = 5V
•LED color = Red
•Forward voltage (Vf ) = 2.0V
•Desired current (I ) = 15 mA = 0.015 A (check specification sheet
for the LED current value which provide maximum brightness)
Consequence Explanation
LED burns out Excessive current overheats and destroys the LED junction
Arduino pin damaged Drawing more than 40mA can permanently damage the microcontroller
High power draw Can affect stability of the whole board
PWM
PWM stands for Pulse Width Modulation. It’s a technique
used to simulate an analog voltage using a digital output
that rapidly switches between HIGH (5V or 3.3V) and
LOW (0V).
Arduino PWM Output Voltage Levels
Even though the signal is digital, the average DC voltage over time behaves like
an analog level.
Formula: DC Average Voltage of PWM
𝑇𝑂𝑁
𝐷𝐶 𝐴𝑣𝑒𝑟𝑎𝑔𝑒 𝑉𝑜𝑙𝑡𝑎𝑔𝑒 = × 𝑉𝐻𝐼𝐺𝐻 − 𝑉𝐿𝑂𝑊
𝑇𝑂𝑁 + 𝑇𝑂𝐹𝐹
𝑇𝑂𝑁
𝐷𝑢𝑡𝑦 𝐶𝑦𝑐𝑙𝑒 =
𝑇𝑂𝑁 + 𝑇𝑂𝐹𝐹
Syllabus