Arduino and Microcontroller Overview
Arduino and Microcontroller Overview
(EI-3003)
Memory External memory (RAM, ROM connected externally). Built-in memory (Flash/ROM and RAM).
I/O Ports External chips required for I/O connections. Built-in I/O ports.
Cost Relatively high due to additional external components. Lower cost because most components are on-chip.
Power Consumption Higher power consumption. Low power consumption.
Speed Very high processing speed (used in computers). Moderate speed, suitable for real-time control.
Flexibility Highly flexible, supports multiple applications. Fixed for specific applications.
Arduino
➢Arduino is an open-source electronics platform based on easy-to-use hardware and
software.
➢Hardware: A physical programmable circuit board, often called a microcontroller.
➢Software: The Arduino IDE (Integrated Development Environment), used to write
and upload computer code to the physical board.
➢It's designed for artists, designers, or for the beginners who have no software or
electronic experience, or anyone interested in creating interactive objects or
environments.
➢It can interact with buttons, LEDs, motors, speakers, GPS units, cameras, the internet,
and even smart-phone or TV.
Contd..
Sense Think
• Working:
➢ A microcontroller-based system like Arduino works as a “Sense-Think-Act” device.
➢ Input (Sense):It detects changes in the environment using sensors or signals.
Act
➢ Examples: Light detected by a photoresistor or LDR sensor.
➢ A finger press detected by a push button.
➢ A message received from an online platform (Twitter API).
➢ Processing (Think):The Arduino’s microcontroller reads these signals, runs the programmed logic, and
decides what to do.
➢ Example: “If the light is low, turn on a lamp.”
➢ Output (Act):Based on the decision, it triggers output devices:
➢ Activates a motor to rotate a fan or robot wheel.
➢ Turns on an LED as a status indicator.
➢ Sends data online (publishes a tweet or updates a web server).
➢ Real-Life Example: A smart streetlight system: Light sensor detects darkness → Arduino decides to
switch on → LED streetlight turns on.
➢ Same system could tweet a maintenance alert if the light fails.
Why Arduino?
Inexpensive: Arduino boards are relatively inexpensive compared to other
microcontroller platforms.
Cross-platform: The Arduino software runs on Windows, Macintosh OSX, and Linux
operating systems. Most microcontroller systems are limited to Windows.
Open source and extensible software: The Arduino software is published as open-
source tools, available for extension by experienced programmers.
Open source and extensible hardware: The Arduino boards are published under a
Creative Commons license, so experienced circuit designers can make their own version
of the module, extending it and improving it.
Simple, clear programming environment: The Arduino Software (IDE) is easy-to-use
for beginners, yet flexible enough for advanced users to take advantage of as well.
History
• Arduino was developed at the Ivrea Interaction Design Institute in Italy in 2005.
• The goal was to create a simple, low-cost tool for students without an electronics background to create digital
projects.
Arduino LilyPad
Arduino Leonardo Arduino Mega
Contd..
Arduino Duemilanove
Arduino Uno
Arduino MICRO
Types of Arduino
Arduino Board Processor Memory Digital I/O Analogue I/O
5 Volt Voltage
Regulator
Flash memory of 32 KB
SCL\SDA
(with 0.5 KB used for the (I2C Bus)
GND
bootloader).
➢ It also has 2 KB of POWER
5V / 3.3V / GND
SRAM and 1 KB of Digital I\O
PWM (3, 5, 6, 9, 10, 11)
EEPROM.
Analog INPUTS
Download
based on
Software system
configuration
Website
[Link]
Steps to download Arduino IDE
➢ Setup():
➢ It is used to initialize the variables; input and output; pin
modes; and other libraries needed in sketch.
➢ It runs once when the board is powered or RESET.
➢ Loop():
➢ It runs continuously.
➢ It stores the main program.
Arduino IDE Preview
➢ It controls the board until the board is powered off or
RESET.
Key Features of Arduino IDE
Feature Description
Code Editor Simple editor to write Arduino sketches in C/C++.
Verify/Compile Button Checks for errors and compiles code.
Upload Button Sends compiled code to the Arduino board via USB.
Serial Monitor & Plotter Displays real-time sensor data and plots it graphically.
Board Manager Select and install support for different Arduino or third-party boards.
Library Manager Add extra libraries for sensors, displays, Wi-Fi, Bluetooth, etc.
Arduino Programming Language
➢It is divided into three parts:
Arduino
Programming
Language
➢ If Statement:
➢ Definition: Executes a block of code if a condition is true.
if (condition) {
// Code if condition is true
}
➢ If…Else Statement
➢ Definition: Executes one block if the condition is true, another if false.
if (condition) {
// Code if true
} else {
// Code if false
}
Contd.
➢If…Else If…Else Statement
➢ Definition: Checks multiple conditions in sequence.
if (condition1) {
// Code if condition1 is true
} else if (condition2) {
// Code if condition2 is true
} else {
// Code if none are true
➢ Switch-Case Statement }
Definition: Executes one code block based on a variable’s value.
switch (variable) {
case value1:
// Code
break;
case value2:
// Code
break;
default:
// Code if no match
}
Contd.
➢ Loop
➢ Definition: Repeats a block of code a set number of times.
for (int i = 0; i < 10; i++) {
// Code
} ➢ Continue Statement
➢ While Loop
Definition: Repeats while a condition is true. ➢ Definition: Skips current iteration and moves to
while (condition) { the next.
// Code for (int i = 0; i < 10; i++) {
} if (i == 5) continue;
➢ Do…While Loop }
➢ Definition: Runs at least once, then repeats while
condition is true.
do { ➢ Nested Loops
// Code ➢ Definition: A loop inside another loop.
} while (condition); for (int i = 0; i < 3; i++) {
➢ Break Statement for (int j = 0; j < 2; j++) {
➢ Definition: Exits a loop or switch early. // Code for every i, j combination
for (int i = 0; i < 10; i++) { }
if (i == 5) break; }
}
Operators
➢Operators are symbols used to perform operations on variables or values:
➢Arithmetic: +, -, *, /, % (e.g., sum = a + b;)
➢Relational: ==, !=, <, >, <=, >= (e.g., if (x > y))
➢Logical: &&, ||, ! (e.g., if(a > b && b > c))
➢Assignment: =, +=, -=, etc.
➢Bitwise: &, |, ^, ~, <<, >>
➢Compound Operator: ++, --, +=, -=, *=, /=, %=, |=, &=
➢ if (a > b) { } // Relational
Data Types And Variables
Data Type Size (on Uno) Range/Use Case
void N/A Used as a function return type when no value is returned.
boolean 1 byte true or false. Used for logic conditions.
char 1 byte Stores a single character. Range: -128 to 127 (signed).
unsigned char 1 byte Stores a single character. Range: 0 to 255.
byte 1 byte Same as unsigned char. Range: 0 to 255.
int 2 bytes Stores whole numbers. Range: -32,768 to 32,767.
unsigned int 2 bytes Stores whole numbers. Range: 0 to 65,535.
short 2 bytes Same as int. Range: -32,768 to 32,767.
word 2 bytes Same as unsigned int. Range: 0 to 65,535.
long 4 bytes Stores larger whole numbers. Range: -2,147,483,648 to 2,147,483,647.
unsigned long 4 bytes Large positive integers. Range: 0 to 4,294,967,295.
float 4 bytes Floating-point (decimal) numbers. Precision ~6-7 digits.
double 4 bytes (Uno) Same as float on Uno; higher precision on other boards.
array Depends on type Collection of variables of the same type. Index-based.
String (Object) Dynamic Class-based text handling with many functions (e.g., .length(), .concat()).
char array Fixed size A C-style string (null-terminated). Memory-efficient text handling.
Contd..
➢Array
➢ Definition: An array is a collection of variables (of the same type) stored in contiguous
memory locations, accessed using an index. Useful for handling multiple sensor values or
device states.
int values[5] = {10, 20, 30, 40, 50};
[Link](values[0]); // Access first element
➢ String
➢ Definition: A String is an object representing a sequence of characters. Provides built-in
functions to manipulate text easily.
String message = "Hello Arduino!";
[Link]([Link]()); // Get length of the string
➢ Character Arrays
➢ Definition: A character array is a null-terminated array of characters used to store text.
char text[] = "Arduino";
[Link](text); // Outputs: Arduino
Arduino functions
➢pinMode()
➢Definition: Sets a specific pin as INPUT, OUTPUT, or INPUT_PULLUP.
➢Syntax: pinMode(pin, mode);
➢Example: pinMode(13, OUTPUT);
digitalWrite()
➢ Definition: Sets a digital pin to HIGH or LOW.
➢ Syntax: digitalWrite(pin, value);
➢ Example:
digitalWrite(13, HIGH); // Turn LED on
➢digitalRead()
➢ Definition: Reads the value of a digital pin (HIGH or LOW).
➢ Syntax: int state = digitalRead(pin);
➢ Example:
int buttonState = digitalRead(2);
Contd..
➢analogRead()
➢ Definition: Reads a value (0–1023) from an analog pin.
➢ Syntax:int sensorValue = analogRead(pin);
➢ Example:
int temp = analogRead(A0);
➢ analogWrite()
➢ Definition: Outputs a PWM signal (0–255) to a pin marked with ~.
➢ Syntax:analogWrite(pin, value);
➢ Example:
analogWrite(9, 128); // 50% duty cycle PWM
➢ delay()
➢ Definition: Pauses the program for a given time in milliseconds.
➢ Syntax:delay(ms);
➢ Example:
delay(1000); // Wait for 1 second
Arduino functions
Digital I/O Math Bits and Bytes Analog I/O Trigonometry Characters Time
digitalRead() abs() bit() analogRead() cos() isAlpha() delay()
digitalWrite() constrain() bitClear() analogReadResolution() sin() isAlphaNumeric( delayMicro
pinMode() map() bitRead() analogReference() tan() ) seconds()
max() bitSet() analogWrite() isAscii() micros()
min() bitWrite() analogWriteResolution() isControl() millis()
pow() highByte() isDigit()
sq() lowByte() isGraph()
sqrt() isHexadecimalDi
git()
isLowerCase()
isPrintable()
isPunct()
isSpace()
isUpperCase()
isWhitespace()
Arduino Variables
Constants Data Types Variable Scope & Qualifiers Conversion
Floating Point array const byte()
Constants bool scope char()
HIGH | LOW boolean static float()
INPUT | byte volatile int()
INPUT_PULLUP | char long()
OUTPUT double (unsigned int)
Integer Constants float (unsigned long)
LED_BUILTIN int word()
true | false long
short
size_t
string
String()
unsigned char
unsigned int
unsigned long
void
word
Arduino Structure
Sketch Arithmetic Control Comparison Bitwise Boolean Compound Operators
Operators Structure Operators Operators Operators
loop() + (addition) break == (equal to) << (bitshift left) && += (compound addition)
setup() = (assignment continue > (greater than) >> (bitshift right) (logical &= (compound bitwise
operator) do...while >= (greater than & (bitwise AND) AND) AND)
/ (division) else or equal to) ~ (bitwise NOT) ! (logical |= (compound bitwise
* (multiplication) for < (less than) | (bitwise OR) NOT) OR)
% (remainder) goto <= (less than or ^ (bitwise XOR) || (logical ^= (compound bitwise
- (subtraction) if equal to) OR) XOR)
return != (not equal to) /= (compound division)
switch...case *= (compound
while multiplication)
%= (compound
remainder)
-= (compound
subtraction)
-- (decrement)
++ (increment)
Arduino Syntax
Syntax Meaning / Purpose Explanation Example
Sets pin as INPUT or Configures a digital pin to behave
pinMode(pin, mode); pinMode(13, OUTPUT);
OUTPUT as either an input or an output.
Write HIGH or LOW to Turns an LED ON/OFF or sends
digitalWrite(pin, value); digitalWrite(13, HIGH);
a pin HIGH(5V)/LOW(0V) to pin.
Reads digital input (HIGH or
digitalRead(pin); Reads pin state int x = digitalRead(2);
LOW).
Writes an analog value (0–255) on analogWrite(9, 128); // 50%
analogWrite(pin, value); PWM output
PWM pins (~ symbol). duty cycle
Reads 10-bit ADC (0–1023) from
analogRead(pin); Reads analog value int val = analogRead(A0);
analog input pin (A0–A5).
delay(ms); Pause program Waits for given milliseconds. delay(1000); // 1 sec
delayMicroseconds(us); Pause in microseconds More precise short delay. delayMicroseconds(10);
Number of ms since Arduino started
millis(); Returns time since start running. Useful for timing without unsigned long t = millis();
delay().
Contd..
Syntax Meaning / Purpose Explanation Example
int s =
map(value, fromLow, Converts a number from one range
Re-maps value range map(analogRead(A0), 0,
fromHigh, toLow, toHigh); to another.
1023, 0, 100);
constrain(x, a, b); Constrains value Keeps number within given range. y = constrain(y, 0, 255);
void loop(){
Function executed in a loop
loop() Runs repeatedly digitalWrite(13, HIGH);
forever.
delay(500); }
Arduino Serial Communication Syntax
Syntax Meaning / Purpose Explanation Example
Initializes the serial port at the given baud rate [Link](9600); //
[Link](baudrate); Starts serial communication (e.g., 9600, 115200). Both Arduino and PC must Start communication at
match this rate. 9600 bps
Displays numbers, characters, or strings without
Prints data to Serial Monitor [Link]("Value: ");
[Link](data); moving to a new line. Useful for continuous
(same line) [Link](100);
output.
Same as [Link]() but appends a newline
[Link](data); Prints data + moves to new line [Link]("Hello");
(\n). Each output appears on a new line.
Returns the first byte of incoming data (-1 if no
[Link](); Reads incoming serial data data available). Used for communication from char c = [Link]();
PC → Arduino.
Returns number of bytes available to read from
if([Link]() > 0) {
[Link](); Checks if data is available serial buffer. Always check before using
char c = [Link](); }
[Link]().
Used to send binary data (not human-readable [Link](65); // Sends
[Link](data); Sends raw data (bytes)
text). Different from print() which is formatted. ASCII 'A'
Waits for outgoing data to be Ensures all data is transmitted before continuing
[Link](); [Link]();
sent program execution.
Disables serial port and frees pins 0 (RX) and 1
[Link](); Stops serial communication [Link]();
(TX) for general I/O use.
Arduino Programming
➢LED Blinking Program
➢This program turns an LED ON for 1 second, then OFF for 1 second, repeatedly.
// The setup() function runs once when the board is powered on or reset
void setup() {
// Initialize pin 13 as an OUTPUT (pin 13 is connected to the built-in LED on Arduino Uno)
pinMode(13, OUTPUT); Explanation:
} ➢ pinMode(13, OUTPUT); → tells Arduino we’ll use
pin 13 to send a signal (output).
// The loop() function runs repeatedly after setup() ➢ digitalWrite(13, HIGH); → sends 5V to pin 13 →
void loop() { LED ON.
digitalWrite(13, HIGH); // Turn the LED ON (HIGH = 5V) ➢ delay(1000); → pauses the program for 1 second.
delay(1000); // Wait for 1000 milliseconds (1 second) ➢ digitalWrite(13, LOW); → sends 0V to pin 13 →
LED OFF.
➢ loop(); repeats forever → LED keeps blinking.
digitalWrite(13, LOW); // Turn the LED OFF (LOW = 0V)
delay(1000); // Wait for 1000 milliseconds (1 second)
}
Distance Measurement Using Ultrasonic Sensor
➢ How the Experiment Works
➢ Triggering the Ultrasonic Sensor // -------------------------------
➢ Arduino sets TRIG pin HIGH for 10 µs. // Pin definitions
➢ This makes the sensor emit an ultrasonic burst at 40 kHz. // -------------------------------
➢ Waiting for Echo // TRIG pin sends the ultrasonic wave
const int trigPin = 9;
➢ The ultrasonic wave travels through air.
// ECHO pin receives the reflected wave
➢ If it hits an object, it bounces back.
const int echoPin = 10;
➢ The ECHO pin goes HIGH until the wave returns.
➢ Measuring Time void setup() {
➢ pulseIn(echoPin, HIGH) gives the time (in microseconds) that // Start the serial communication with computer
the ECHO pin was HIGH. // Baud rate: 9600 bits per second
➢ This corresponds to the round-trip travel time of the wave. [Link](9600);
➢ Calculating Distance
// Set TRIG pin as OUTPUT because Arduino will send
➢ Speed of sound ≈ 343 m/s = 0.034 cm/µs.
signal
➢ Distance = (duration × 0.034) / 2. pinMode(trigPin, OUTPUT);
➢ Example:
➢ If duration = 1000 µs, // Set ECHO pin as INPUT because Arduino will receive
➢ Distance = (1000 × 0.034) / 2 = 17 cm. signal
pinMode(echoPin, INPUT);
➢ Displaying Output
}
➢ Distance values are printed in cm.
Contd.. // Step 3: Read the ECHO pin
void loop() { // -------------------------------
long duration; // Stores time taken for pulse to return // pulseIn() measures the time (in microseconds) for which
long distance; // Stores calculated distance in cm // the ECHO pin stays HIGH (when echo returns)
// ------------------------------- duration = pulseIn(echoPin, HIGH);
// Step 1: Clear the TRIG pin // -------------------------------
// ------------------------------- // Step 4: Convert time into distance
// Ensure the TRIG pin is LOW for at least 2 microseconds // -------------------------------
digitalWrite(trigPin, LOW); // Formula: distance = (time × speed of sound) / 2
delayMicroseconds(2); // - Speed of sound ≈ 0.034 cm/µs
// ------------------------------- // - Divide by 2 because sound travels forward and back
// Step 2: Send a 10 µs HIGH pulse distance = duration * 0.034 / 2;
// ------------------------------- // -------------------------------
// This generates the ultrasonic "ping" (8-cycle sound burst at // Step 5: Display result
40 kHz) // -------------------------------
digitalWrite(trigPin, HIGH); [Link]("Distance: ");
delayMicroseconds(10); [Link](distance);
digitalWrite(trigPin, LOW); [Link](" cm");
// -------------------------------
// Small delay before next reading
delay(500);
}