0% found this document useful (0 votes)
27 views39 pages

Arduino and Microcontroller Overview

The document provides an overview of embedded systems, focusing on microprocessors, microcontrollers, and the Arduino platform. It details the architecture, components, and applications of microcontrollers and microprocessors, as well as the features and programming of Arduino boards. Additionally, it includes information about the Arduino IDE, programming language, and various types of Arduino boards.

Uploaded by

sankeerthsnk
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
0% found this document useful (0 votes)
27 views39 pages

Arduino and Microcontroller Overview

The document provides an overview of embedded systems, focusing on microprocessors, microcontrollers, and the Arduino platform. It details the architecture, components, and applications of microcontrollers and microprocessors, as well as the features and programming of Arduino boards. Additionally, it includes information about the Arduino IDE, programming language, and various types of Arduino boards.

Uploaded by

sankeerthsnk
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

(EI-3003)

Dr. Abhinav Kumar


Assistant Professor
Dept. of ECE, IIIT Ranchi
Syllabus
Module-II
Arduino: The Arduino Platform, Block diagram, Architecture, Pin functions,
overview of main features such as I/O Ports, timers, interrupts serial port,
PWM and Arduino programming.
Microprocessor
➢ The microprocessor is a programmable integrated circuit that employs a central processing unit (CPU) to process the
data.
➢ It fetches, decodes, and executes program instructions to perform arithmetic and logical operations.
➢ key components:
➢ Arithmetic Logic Unit (ALU): Performs all arithmetic operations (addition, subtraction, multiplication, division)
and logic operations (AND, OR, NOT, etc.).
➢ Control Unit (CU): Directs the execution of instructions, manages timing, and coordinates data movement.
➢ Registers: Small, high-speed storage units inside the CPU for temporary data and instruction storage.
➢ Clock Unit: Provides timing signals to synchronize operations within the processor.
➢ Bus Interface (Data, Address, and Control Buses): Facilitates communication between the processor, memory,
and I/O devices. Microprocessor
ALU

Input Device Control Unit Output Device


Register Array

Fig: Block Diagram of Key Components of Microprocessor Memory Unit


Microcontroller
➢ A microcontroller is a small-scale computer that integrates a
processor (CPU), memory (RAM and ROM), and
programmable input/output (I/O) peripherals onto one
integrated circuit.
➢ Key Components: Registers
➢ Processor (CPU): Executes instructions and performs
calculations. I/O Ports
➢ Memory: Memory
➢ ROM/Flash: Stores the program (firmware). CPU
➢ RAM: Temporary storage for data during execution.
➢ I/O Ports: Interfaces for connecting sensors, actuators,
and other devices.
Timing &
➢ Timers and Counters: Handle time-based operations. Counters
Controls
Interrupt
➢ Embedded in Devices: Microcontrollers are built into systems
like washing machines, microwaves, cars, and IoT devices Fig: Block Diagram of Key Components of Microcontroller
to control specific tasks.
Microprocessors Vs Microcontrollers
Feature Microprocessor Microcontroller
A general-purpose computing unit used in PCs, A compact integrated chip designed for controlling
Definition laptops, and high-end applications. specific embedded applications.
e.g., 8085, 8086 e.g., 8051
CPU, RAM, ROM, I/O ports, and peripherals on a
Components CPU only (requires external RAM, ROM, I/O).
single chip.

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.

Embedded systems: washing machines, cars, IoT


Applications Desktops, laptops, servers, gaming consoles.
devices, robots.
Complexity More complex system design (needs external parts). Simple, compact design for dedicated tasks.

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

Arduino Uno 16Mhz 2KB SRAM, 14 6 input, 0 output


ATmega328 32KB flash
Arduino Due 84MHz 96KB SRAM, 54 12 input, 2 output
AT91SAM3X8E 512KB flash
Arduino Mega 16MHz 8KB SRAM, 54 16 input, 0 output
ATmega2560 256KB flash
Arduino 16MHz 2.5KB SRAM, 20 12 input, 0 output
Leonardo ATmega32u4 32KB flash
Arduino UNO Board USB PORT
(to Computer)
➢ The Arduino Uno is a
POWER JACK
microcontroller board
based on the ATmega328 .
RESET
➢ The ATmega328 has

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

ATmega328 In-circuit Serial


Programming Header
Components of Arduino Board
➢ USB Port
• Used to upload code from your computer to the Arduino.
• Also powers the board (5V) when connected via USB.
➢ Power Jack (Barrel Jack)
• Allows powering the board externally using a 7–12V DC adapter.
➢ Microcontroller (ATmega328P)
• The “brain” of the Arduino board.
• Executes the program, handles I/O, and controls all components.
➢ Power Pins
• VIN: Input voltage to the Arduino when using an external power source.
• 5V: Provides regulated 5V output.
• 3.3V: Provides 3.3V output.
• GND: Ground pins.
➢ Digital I/O Pins (0–13)
• Can be used as input or output for digital signals (HIGH/LOW).
• Pins 0 and 1 are used for Serial Communication (RX, TX).
Components Description
➢PWM Pins (~)
•Pins marked with ~ (3, 5, 6, 9, 10, 11) can output Pulse Width Modulated (PWM) signals.
•Useful for controlling motor speed or LED brightness.
➢Analog Input Pins (A0–A5)
•Reads analog signals (0–5V) from sensors.
•Converts them to a digital value using the board’s 10-bit ADC.
➢Reset Button
•Restarts the microcontroller and re-runs the uploaded program.
➢Crystal Oscillator (16 MHz)
•Provides the clock signal to keep the microcontroller running accurately.
➢Voltage Regulator
•Ensures the board gets a safe and stable voltage (5V).
➢ICSP Header
•Used for programming the microcontroller directly or uploading bootloader.
Component Description
➢ TX/RX LEDs
•Indicate when data is being transmitted (TX) or received (RX) via serial communication.
➢ ON LED
•A small LED that glows when the board is powered.
➢ Pin Headers
•Black strips of female connectors where jumper wires or sensors are plugged in.
Summary
Component/Pin Function/Description Details
The main chip that runs your code and controls 32 KB Flash, 2 KB SRAM, 1 KB
Microcontroller (ATmega328P)
the board. EEPROM, 16 MHz clock.
Power Arduino via USB (5V) or Barrel Jack (7–
Power Sources Includes onboard voltage regulator.
12V).
VIN: Input voltage if using external supply; Use 5V for sensors, 3.3V for low-
Power Pins
5V/3.3V: Regulated outputs; GND: Ground. voltage modules.
Read analog sensor values (0–5V) and convert to Double as SDA (A4) and SCL (A5)
Analog Input Pins (A0–A5)
10-bit digital values (0–1023). for I²C.
General-purpose input/output for digital signals
Digital I/O Pins (0–13) Configurable via pinMode().
(HIGH/LOW).
PWM Pins (~3, ~5, ~6, ~9, ~10, Generate analog-like signals for motor speed,
PWM resolution: 8-bit (0–255).
~11) LED brightness, etc.
Contd..
Component/Pin Function/Description Details
Used for UART serial communication (TX, Also used for USB-to-PC
Serial Pins (0,1)
RX). communication.
Used for SPI communication with devices like
Pin 10: SS, Pin 11: MOSI, Pin 12: MISO,
SPI Pins (10–13)
SD cards, displays. Pin 13: SCK.
Can connect multiple devices on a single
I²C Pins (A4, A5) Two-wire communication (SDA=A4, SCL=A5).
bus.
Reset Button Resets the board and restarts your program. Handy for troubleshooting.
Provides clock signal for timing and
Crystal Oscillator (16 MHz) Located near the microcontroller.
synchronization.
Used to program the microcontroller directly or Has MISO, MOSI, SCK, RESET, VCC,
ICSP Header
upload bootloader. GND.
Blink during data transmission or
TX/RX LEDs Indicate serial communication activity.
reception.
ON LED Indicates that the board is powered. Always ON when powered.
Female connectors to plug in jumper wires,
Pin Headers Labeled clearly for easy prototyping.
sensors, and shields.
MCQ
Q1. What is Arduino? Q2. Which microcontroller is used in Arduino Uno?
A) A programming language A) ATmega328P
B) A microcontroller-based open-source platform B) ATmega16
C) A mobile operating system C) PIC16F877A
D) A type of resistor
D) ARM Cortex-M4
Ans: B Ans: A
Q3. What is the function of the USB port on Arduino Q4. What does the pin labelled “VIN” represent?
Uno? A) Voltage Input from external supply
A) Only to supply power B) Voltage Indicator
B) Only for uploading code C) Variable Internal Node
C) Both power supply and code upload D) Virtual Interface Node
D) For wireless communication Ans: A
Ans: C
Q5. The crystal oscillator on Arduino Uno has a frequency Q6. What type of pin is used for PWM output in Arduino
of: Uno?
A) 8 MHz A) Pins labeled with a “~” symbol
B) 10 MHz B) Pins A0–A5
C) 12 MHz C) Only pin 13
D) 16 MHz D) Pins with VIN label
Ans: D Ans: A
Arduino Integrated Development Environment
➢Arduino Integrated Development Environment (IDE) is an open-source IDE that allows
users to write code and upload it to any Arduino board.
➢It is compatible with Windows, macOS and Linux operating systems.

Download
based on
Software system
configuration
Website
[Link]
Steps to download Arduino IDE

Arduino IDE Preview


Arduino IDE Set Up
➢ Power up the board by connecting it to a PC via USB cable.
➢ Launch the Arduino IDE.
➢ Set the board type and the port for the board.
➢ Tools > Board >Select Your Board
➢ Tools > Port >Select Your Port

First ways to select the board and ports


Second ways to select the board and ports
Arduino IDE Overview
➢ Program coded in Arduino IDE to control an Arduino board is Sketch
called a SKETCH.
➢ It’s written in C/C++ but simplified with Arduino’s built-in
libraries and functions.
➢ Every Arduino sketch must have two main functions:
➢ Setup() ➢Setup()
➢ Loop() ➢Loop()

➢ 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

Control statements Operators Functions


Control Statement
➢Used to control the flow of a program:
➢ if, else if, else: Execute code blocks conditionally.
➢ switch-case: Choose from multiple options.
➢ break, continue: Exit or skip iterations in loops.
➢ return: Exit from a function.

➢ 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: ++, --, +=, -=, *=, /=, %=, |=, &=

➢ int sum = a + b; // Arithmetic ➢ if (x && y) { } // Logical

➢ 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

Returns random number between


random(min, max); Generates random number min (inclusive) and max int r = random(1, 10);
(exclusive).

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 setup(){ pinMode(13,


setup() Runs once Function executed once at start.
OUTPUT); }

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);
}

You might also like