[Go to site: main page, start]

100% found this document useful (1 vote)
10 views89 pages

Arduino Programming and Basics Guide

The document provides an overview of Arduino, an open-source electronics platform, detailing its hardware components, programming environment, and basic programming concepts. It covers the Arduino board's capabilities, power methods, and essential programming functions, including digital and analog I/O operations. Additionally, it discusses debugging techniques and timing functions necessary for effective Arduino programming.

Uploaded by

suibhai102007
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
10 views89 pages

Arduino Programming and Basics Guide

The document provides an overview of Arduino, an open-source electronics platform, detailing its hardware components, programming environment, and basic programming concepts. It covers the Arduino board's capabilities, power methods, and essential programming functions, including digital and analog I/O operations. Additionally, it discusses debugging techniques and timing functions necessary for effective Arduino programming.

Uploaded by

suibhai102007
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Embedded Systems Hardware

(EED-308)

1
Arduino:
Introduction & Programming
Syllabus

DR. ROHIT SINGH AND PROF. SONAL SINGHAL 2


What is an Arduino?
Arduino is an open-source electronics platform based on easy-to-use
hardware and software.

Arduino is composed of two major parts:


the Arduino board, which is the piece of
Syllabus
hardware you work on when you build
your objects; and the Arduino Integrated
Development Environment, or IDE, the
piece of software you run on your
computer.

DR. ROHIT SINGH AND PROF. SONAL SINGHAL 3


What is an Arduino?

Arduino boards can read inputs - light


on a sensor, a pressure on a button, or
a Twitter message - and turn it into an
output - activating a motor, turning on
an LED, publishing something online
Syllabus

You use the IDE to create a sketch (a


little computer program) that you
upload to the Arduino board. The
sketch tells the board what to do

DR. ROHIT SINGH AND PROF. SONAL SINGHAL 4


Arduino Environment

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

DR. ROHIT SINGH AND PROF. SONAL SINGHAL 6


Arduino Board

Syllabus

DR. ROHIT SINGH AND PROF. SONAL SINGHAL 7


Arduino Board Familiarization

Syllabus

Analog Input
Pins/Digital I/O

DR. ROHIT SINGH AND PROF. SONAL SINGHAL 8


Various Ways to Power the Arduino Board

Why Powering Matters?


•Arduino needs stable power to function.
•Choosing the right power source ensures reliability, safety,
and efficiency.
•Different projects (portable, desktop, outdoor) need different
power methods.
•Avoid damage to the board
Powering Methods
•VIN Pin (Power Input and Output) or DC barrel jack (Power Input)
•Connect an external power source (e.g., a 9V battery or a 7-12V wall adapter) to the VIN pin
or the DC barrel jack.
•The onboard voltage regulator steps this voltage down to the 5V needed by the Arduino.
•This method automatically switches off the USB power source when connected.

•USB Port (Power Input):


•Connect the Arduino to a computer or a USB power adapter via the USB port.
•This method supplies a regulated 5V and allows for code uploading and serial monitoring.

•5V Pin (Power Input and Output):


•This pin is connected directly to the Arduino's 5V power rail, bypassing the onboard
regulator.
•Use this with a regulated 5V external power supply.

•3.3V Pin (Power Output):

•This pin provides a regulated 3.3V supply.


Power Connection

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”.

Dr. Rohit Singh 15


Arduino Programming

COMMENTS

SETUP

LOOP

16
Microcontroller Programming Essentials

Digital I/O Analog I/O

Debugging Timing

Serial
Communication

17
What We Will Be Building?

I have always been fascinated by light and the


ability to control different light sources through
technology. I have been lucky enough to work on
some interesting projects that involve controlling
light and making it interact with people. Arduino
is really good at this.

—Massimo
Pin mode configuration

Function: pinMode()

Description: Configures the specified pin to behave either as an input or an output.

Syntax: pinMode(pin, mode)


Digital
Parameters I/O
Syllabus
Pin: The Arduino pin number e.g. 1, 2, …,13, A0,…,A5.

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.

This technique is called pulse-width


modulation, or PWM, because you are
changing the LED’s brightness by
modulating (or changing) the width of
the pulse.

This works because our eyes can’t


see distinct pictures if they change
too fast.
Analog I/O Analog
I/O
Analog Write

✓ It is a built-in Arduino function that generates a Pulse Width Modulation (PWM)


signal on a specified pin.

✓ 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!

This makes an LED smoothly fade in and out using PWM.


Debugging
Function: [Link]()
Description: Sets the data rate in bits per second (baud) for serial data transmission.
For communicating with Serial Monitor, make sure to use one of the baud rates listed
here.

Syntax: [Link](speed) or [Link](speed, config)

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

Dr. Rohit Singh 28


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.

Syntax: [Link]() Debugging

Dr. Rohit Singh 29


Debugging

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.

Dr. Rohit Singh 33


Problem Statement:
Create a program that blinks an LED connected to pin 13 every 1 second, but without
using delay(). This allows the Arduino to perform other tasks simultaneously.

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 }

void setup() { // Control LED 2


pinMode(led1Pin, OUTPUT); if (currentMillis - previousMillis2 >= interval2)
pinMode(led2Pin, OUTPUT); {
} previousMillis2 = currentMillis;
digitalWrite(led2Pin, !digitalRead(led2Pin));
}
}
Create a system where:
1. An LED blinks every 500 milliseconds.
2. A message is printed to the Serial Monitor every 700 milliseconds.
3. The Arduino must remain responsive to a push button press at any
time — when pressed, it toggles an indicator LED immediately.

Try it using Delay function!


This cannot be done properly with delay()!
delay() blocks the processor. During a delay(500), the
button won't be read.

Why delay() Fails Here:


•delay() stops all code execution.
•You can't check the button or print serial messages while delayed.
•Timing overlaps cause missed inputs.
unsigned long previoustimeled = 0;
void loop()
unsigned long previoustimemessage = 0;
{
unsigned long intervalled = 500;
// put your main code here, to run repeatedly:
unsigned long intervalmessage = 700;
currenttime = millis();
unsigned long currenttime;
if(currenttime - previoustimeled >= intervalled)
{
#define LED 4
digitalWrite(LED, !digitalRead(LED));
#define buttonLED 5
previoustimeled = currenttime;
#define Button 7
}
if(currenttime - previoustimemessage >= 700)
void setup()
{
{
[Link]("Welcome Shiv Nadar University,
// put your setup code here, to run
Delhi-NCR");
once:
previoustimemessage = currenttime;
[Link](9600);
}
pinMode(LED, OUTPUT);
if(digitalRead(Button) == 0)
pinMode(Button, INPUT_PULLUP);
{
pinMode(buttonLED, OUTPUT);
digitalWrite(buttonLED, !digitalRead(buttonLED));
}}
}
Some more Functions
Syllabus

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.

It is not possible to generate tones lower than 31Hz and


Syllabus
maximum crystal_frequency/2.
Syntax
tone(pin, frequency), tone(pin, frequency, duration), and
noTone(pin)

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:

Plays a simple melody (Twinkle Twinkle Little Star) using buzzer

const int speakerPin = 8;


// Notes: frequencies in Hz
#define NOTE_C4 262
#define NOTE_D4 294
#define NOTE_E4 330 Syllabus
#define NOTE_F4 349
#define NOTE_G4 392
#define NOTE_A4 440
#define NOTE_B4 494
#define NOTE_C5 523
#define REST 0 // For silence
Dr. Rohit Singh 42
// Twinkle Twinkle Little Star - Note void loop() {
sequence // Play each note in the melody
int melody[] = { int numNotes =
NOTE_C4, NOTE_C4, NOTE_G4, sizeof(melody)/sizeof(melody[0]);
NOTE_G4, NOTE_A4, NOTE_A4,
NOTE_G4, for (int i = 0; i < numNotes; i++) {
NOTE_F4, NOTE_F4, NOTE_E4,
int note = melody[i];
NOTE_E4, NOTE_D4, NOTE_D4,
NOTE_C4
int duration = noteDurations[i];
};
if (note == REST) {
// Duration of each note (in // If it's a rest, just wait
milliseconds) delay(duration);
int noteDurations[] = { } else {
500, 500, 500, 500, 500, 500, 1000, // Play the tone
500, 500, 500, 500, 500, 500, 1000 tone(speakerPin, note, duration);
}; }
void setup() { // Add a small gap between notes
// No setup needed for pins; tone() delay(duration + 50);
handles it }
[Link](9600);} // Wait a few seconds before playing again
delay(2000);}
pulseIn() functions
Reads a pulse (either HIGH or LOW) on a pin. For example, if value is
HIGH, pulseIn() waits for the pin to go from LOW to HIGH, starts timing,
then waits for the pin to go LOW and stops timing. Returns the length of
the pulse in microseconds or gives up and returns 0 if no complete pulse
was received within the timeout.

Works on pulses from 10 microseconds to 3 minutes in


length.
Syllabus
Syntax
pulseIn(pin, value)
pulseIn(pin, value, timeout)

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.

Dr. Rohit Singh 45


Our first sensor !
Problem Statement: Measure Distance with Ultrasonic Sensor (HC-
SR04)
Concept: The HC-SR04 sends out a high-frequency sound pulse and
listens for its echo. We use pulseIn() to measure the time it takes
for the echo to return. From this time, we calculate the distance to an
object in front of the sensor.

What is Ultrasonic sensor?


The HC-SR04 is a popular ultrasonic distance sensor used in
Arduino and robotics projects to measure the distance to an object
without physical contact. It works by sending out high-frequency
sound waves and measuring how long they take to bounce back.
It's like a miniature sonar system — similar to how bats or
submarines detect objects!
The sensor uses the time-of-flight principle:
[Link] out a short ultrasonic pulse (40 kHz frequency — beyond
human hearing).
[Link] pulse travels through the air.
[Link] it hits an object, it bounces back as an echo.
[Link] sensor detects the echo and calculates the distance based on
how long the round trip took.
Distance = (Speed of Sound × Time) / 2
(Divide by 2 because the sound goes to the object and back)
Pin
Name Function
VCC 5V
Trigger pin: Arduino sends a pulse here to start
Trig measurement
Echo Sensor sends back a pulse
GND 0V
Method:

✓ Send a 10 µs HIGH pulse to the Trig pin → tells the sensor to


send a sound burst.

✓ The sensor automatically sends pulses of 40 kHz.

✓ The Echo pin goes HIGH when the pulse is sent and stays HIGH
until the echo returns.

✓ Use pulseIn(echoPin, HIGH) to measure how long the Echo pin


stays HIGH (in microseconds).

✓ Calculate distance using the time and speed of sound.


/*
Ultrasonic Distance Measurement using pulseIn()
Sensor: HC-SR04; Displays distance in centimeters and inches via Serial Monitor*/

const int trigPin = 9; // Trigger pin


const int echoPin = 10; // Echo pin

long duration; // To store pulse duration


float distanceCm; // Distance in centimeters
float distanceIn; // Distance in inches

void setup() {
// Initialize serial communication
[Link](9600);

// Set pin modes


pinMode(trigPin, OUTPUT); // Trigger pin sends pulse
pinMode(echoPin, INPUT); // Echo pin receives response
}
// Calculate distance in cm and inches
// Speed of sound = 340 m/s = 34000
void loop() { cm/s = 0.034 cm/μs
// Clear the trigger pin // Sound travels to object and back →
digitalWrite(trigPin, LOW); round trip
delayMicroseconds(2); distanceCm = (duration * 0.034) / 2;
// Divide by 2 for one-way distance
// Send a 10-microsecond pulse distanceIn = distanceCm / 2.54;
to trigger
digitalWrite(trigPin, HIGH); // Print results to Serial Monitor
delayMicroseconds(10); [Link]("Distance: ");
digitalWrite(trigPin, LOW); [Link](distanceCm);
[Link](" cm (");
// Wait for the echo pulse and [Link](distanceIn);
measure its duration [Link](" in)");
duration = pulseIn(echoPin,
HIGH); // Small delay between readings
delay(500);
}
Interrupt

Think of it like a doorbell:


You're cooking (main program), the doorbell rings
(interrupt), you quickly answer the door (ISR), then go
back to cooking.
Interrupt
An interrupt is a hardware or software event that temporarily
pauses the main program (the loop()) to execute a specific function
called an Interrupt Service Routine (ISR). Once the ISR finishes, the
Arduino resumes the main program exactly where it left off.

Interrupts are used when you need to respond instantly to an


important event — even if the Arduino is busy doing something
else.
Interrupt

Common Use Cases:

Detecting a button press immediately

Avoiding missed events in fast-changing signals

Without interrupts, you'd have to constantly check


(digitalRead()) in the loop (aka Polling Method) —
which leads to waste of processing time.
External Interrupts
Triggered by a change on a specific pin.
Arduino Board Supported Pins Interrupts
interrupts INT0 mapped to pin no.
Uno, Nano, Mini Pins 2 and 3 2 , INT1 mapped to pin no. 3
Not all pins support external interrupts

You can trigger an interrupt on:

RISING – when the pin goes from LOW → HIGH


FALLING – when the pin goes from HIGH → LOW
CHANGE – when the pin changes (either way)
LOW – while the pin is LOW (level-triggered)
noInterrupts(): It is like DND. It void setup() {}
disables the Pin No. 2 and 3 for
accepting any interrupt.

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.

Dr. Rohit Singh 57


attachInterrupt()

Syntax
attachInterrupt(digitalPinToInterrupt(pin), ISR, mode);

Modes: Four constants are predefined as valid values:

Mode When Triggered Syllabus


RISING When the pin goes from LOW → HIGH
FALLING When the pin goes from HIGH → LOW
CHANGE When the pin changes state (LOW→HIGH or HIGH→LOW)
LOW While the pin is LOW (level-triggered)

HIGH: Not valid for all types of Arduino Board

Dr. Rohit Singh 58


Interrupts
detachInterrupt() functions
✓ The detachInterrupt() function is used to disable or turn off an
interrupt that was previously enabled using attachInterrupt().

✓ Once detached, the Interrupt Service Routine (ISR) will no


longer execute when the trigger condition occurs — allowing
Syllabus
you to temporarily or permanently stop responding to that
event.

✓ Generally written as a condition

Syntax
detachInterrupt(digitalPinToInterrupt(pin);

Dr. Rohit Singh 59


Problem Statement:
Toggle an LEDs when the button is pressed. Do not use the Polling method.

const byte ledPin = 13;


const byte interruptPin = 2; // input pin that the interruption will be attached to
volatile byte state = LOW; // variable that will be updated in the ISR

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
}

Dr. Rohit Singh 60


Example:
This example demonstrates how to use an Infrared (IR)
Obstacle Detection Sensor with external interrupts to
detect objects instantly, without constantly polling the
sensor.

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*/

const int irSensorPin = 2; // Must be interrupt-capable pin (e.g., D2)


const int ledPin = 13; // Built-in LED on most boards
volatile bool objectDetected = false; // Flag set by interrupt
void setup() {
// Set pin modes
pinMode(irSensorPin, INPUT);
pinMode(ledPin, OUTPUT);
// Initialize serial for debugging
[Link](9600);
// Attach interrupt to pin 2: trigger on FALLING edge (object detected)
attachInterrupt(digitalPinToInterrupt(irSensorPin), detectObject,
FALLING);
[Link]("IR Sensor with Interrupt - Ready!");
}
void loop() {
// Main loop runs continuously // Interrupt Service Routine (ISR)
if (objectDetected) { void detectObject() {
// Toggle LED objectDetected = true; // Set flag (fast and
digitalWrite(ledPin, safe)
!digitalRead(ledPin)); }

[Link]("Object Detected!");

objectDetected = false; // Reset flag


}

// Other tasks (non-blocking)


[Link]("Arduino is free..");
delay(1000); // Simulate background
task
}
Important Notes

• Use volatile for variables shared between ISR and


loop().
• Keep ISR short — only set a flag or increment a counter
• Avoid delay() inside ISR — use it in loop() if needed
• Do not accept any argument in ISR.
• ISR do not return anything
• IR Sensor Output: Most modules are active-low (LOW
when object detected).
Example: Button Counter Using Interrupts in Arduino

Objevtive: Every time you press a button, the Arduino increases a


counter by 1 — instantly and without missing any presses, even if it's
doing something else.
Use an interrupt so the Arduino doesn’t have to keep checking the
button all the time.
/*
Student Example: Button Counter with Interrupt
Counts how many times a button is pressed using interrupt
*/

const int buttonPin = 2; // Interrupt-capable pin


const int ledPin = 13; // Built-in LED

volatile int count = 0; // 'volatile' because changed in interrupt

void setup() {
// Set up pins
pinMode(buttonPin, INPUT);
pinMode(ledPin, OUTPUT);

// Start serial communication


[Link](9600);
[Link]("Button Counter Ready!");
// Attach interrupt: when button is pressed (HIGH), call countPress()
attachInterrupt(digitalPinToInterrupt(buttonPin), countPress, RISING);}

void loop() {
// Main program keeps running
[Link]("Button Pressed: ");
[Link](count);
[Link](" times");

// Blink LED slowly to show main program is still running


digitalWrite(ledPin, HIGH);
delay(200);
digitalWrite(ledPin, LOW);
delay(200);
}
// This runs ONLY when button is pressed (ISR)
void countPress() {
count++; // Increase the counter}
Overview: This section discusses the AVR® core architecture in
general. The main function of the CPU core is to ensure
correct program execution. The CPU must therefore be able to
access memories, perform calculations, control peripherals,
and handle interrupts.

ATmega328P Memory Bus


EEPROM
EEPROM (Electrically Erasable Programmable Read-Only Memory) in
the Arduino ATmega328P is a type of non-volatile memory that retains
data even when the power is turned off. It is separate from the flash
memory (used for storing the program code) and SRAM (used for
variables during runtime).

Key Features of EEPROM in ATmega328P:


•Size: 1024 bytes (1 KB)
•Non-volatile: Data persists after power loss
•Byte-level erase and write: You can write to or erase individual bytes
•Limited write endurance: ~ 100,000 write/erase cycles per byte
•Slower write speed: Writing to EEPROM takes longer than reading from
or writing to RAM
•Ideal for storing small amounts of persistent data, such as calibration
values, user settings, device IDs, or state information.
Use Cases of EEPROM:
•Saving configuration settings (e.g., brightness, volume,
Wi-Fi credentials)
•Storing sensor data
•Counting events (e.g., number of times a device was
turned on)
•Remembering the last state of a system
How to Use EEPROM in ATmega328P:

The Arduino IDE has the EEPROM library <EEPROM.h>


by default, making it easy to read from and write to
EEPROM

You need to include the library in the program to use the


EEPROM library

#include <EEPROM.h>
Standard Libraries: EEPROM

Some functions available in this library

• read()
• write()
• update()
• get()
• put() Syllabus
• EEPROM[]

Dr. Rohit Singh 74


Standard Libraries: EEPROM
Function: [Link]()
Description: Reads a byte (0–255) from the EEPROM. For the first time access, the read
operations the returns the 255. Default status is all HIGH.
Syntax: [Link](address)
Parameters:
address: the location to read from, starting from 0 (int).
#include <EEPROM.h>

void setup() { Syllabus


[Link](9600);

// Read a byte from address 0


byte value = [Link](0);
[Link]("Value at address
0: ");
[Link](value);
}

void loop() {}

Dr. Rohit Singh 75


Standard Libraries: EEPROM
Function: [Link]()
Description: Write a byte to the EEPROM.
Syntax: [Link](address, value)
Parameters
Address: the location to write into, starting from 0-1023
Value: the value to be written, from 0 to 255 (byte)

#include <EEPROM.h> Syllabus


void setup() {
[Link](9600);

// Write the number 75 to address 0


[Link](0, 75);
[Link]("Data written to EEPROM.");
}

void loop() {}

Dr. Rohit Singh 76


Standard Libraries: EEPROM

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)

Dr. Rohit Singh 77


Standard Libraries: EEPROM
Function: EEPROM[]
Description: Provides array-style access to EEPROM memory using the []
operator. It's a convenient shorthand.
Syntax: EEPROM[address]
Parameters
address: the location to read/write from, starting from 0-1023

Syllabus
EEPROM[address] = value; // Write
value = EEPROM[address]; // Read

Dr. Rohit Singh 78


#include <EEPROM.h>

float temperature = 23.5;

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;

You must call:

[Link]();
Auto-
Function Purpose commit? Best For
read() Read a byte No Simple reads
write() Write a byte No Single-byte writes

update() Write only if different Yes Frequent updates


Structs, floats,
get() Read complex data No ints
Saving structured
put() Write complex data Yes data
Array-style access Quick access to
EEPROM[] (read/write) No bytes
Why is a Resistor Necessary?
We connect a resistor in series with an LED when connecting it to an
Arduino GPIO (General Purpose Input/Output) pin to limit the
current flowing through the LED and prevent damage to both the
LED and the Arduino
LEDs are Current-Driven Devices

1. An LED doesn’t behave like a


resistor. Its voltage-current
relationship is non-linear:

Once the voltage across the LED


reaches its forward voltage (Vf), it
starts conducting heavily.

A small increase in voltage causes a


large increase in current.

If you connect an LED directly to a 5V


GPIO pin without a resistor, too much
current will flow — potentially
destroying the LED or the Arduino
pin.
Why is a Resistor Necessary?

2. Arduino GPIO Pins Have Current Limits

The ATmega328P (used in Arduino Uno) can safely supply only:

• Maximum 40 mA per GPIO pin (absolute maximum)


• Recommended: ≤ 20–25 mA for reliable operation
• Most standard LEDs (like red or green 5mm LEDs) operate
safely at around 10–20 mA.

Without a resistor, the current could easily exceed 100 mA —


burning out the LED or damaging the microcontroller.
The resistor limits the current using
Ohm’s Law:

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

•Digital HIGH voltage: Typically 5V (for 5V boards like Arduino Uno)

•Digital LOW voltage: 0V

•PWM frequency: ~490 Hz or 980 Hz depending on the pin (on Uno)

Even though the signal is digital, the average DC voltage over time behaves like
an analog level.
Formula: DC Average Voltage of PWM

𝑇𝑂𝑁
𝐷𝐶 𝐴𝑣𝑒𝑟𝑎𝑔𝑒 𝑉𝑜𝑙𝑡𝑎𝑔𝑒 = × 𝑉𝐻𝐼𝐺𝐻 − 𝑉𝐿𝑂𝑊
𝑇𝑂𝑁 + 𝑇𝑂𝐹𝐹
𝑇𝑂𝑁
𝐷𝑢𝑡𝑦 𝐶𝑦𝑐𝑙𝑒 =
𝑇𝑂𝑁 + 𝑇𝑂𝐹𝐹
Syllabus

Dr. Rohit Singh 89

You might also like