You are on page 1of 77

INTRODUCTION TO

ARDUINO UNO
INTRODUCTION TO ARDUINO UNO
Features
 An open-source microcontroller board
 Microcontroller : ATmega328
 Operating Voltage : 5V
 Input Voltage (external) : 6-20V (7-12 recommended)
 Digital I/O Pins : 14 (6 PWM output)
 Analog Input Pins :6
 DC Current per I/O Pin : 40 mA
 DC Current for 3.3V Pin : 50 mA
 Flash Memory : 32 KB (0.5 KB for bootloader)
 Clock Frequency : 16 MHz
 Programming Interface : USB (ICSP)
MODULE - 3 ECE4003 – EMBEDDED SYSTEM DESIGN
INTRODUCTION TO ARDUINO UNO
Arduino Uno - Board Details

MODULE - 3 ECE4003 – EMBEDDED SYSTEM DESIGN


INTRODUCTION TO ARDUINO UNO
Arduino Uno - Pin Details

MODULE - 3 ECE4003 – EMBEDDED SYSTEM DESIGN


INTRODUCTION TO ATmega328
Features Architecture
 Instruction set Architecture : RISC
 Data bus size : 8-bit
 Address bus size : 16-bit
 Program memory (ROM) : 32 KB
 Data memory (RAM) : 2 KB
 Data memory (EEPROM) : 1 KB
 Input/output ports : 3 (B, C, D)
 General purpose registers : 32
 Timers : 3 (Timer0, 1 & 2)
 Interrupts : 26 (2 Ext. interrupts)
 ADC modules (10-bit) : 6 channels
 PWM modules :6
 Analog comparators :1
 Serial communication : SPI, USART, TWI(I2C)
MODULE - 3 ECE4003 – EMBEDDED SYSTEM DESIGN
PROGRAMMING I/P and O/P

Information exchange is done by input and output devices

It may be digital or analog signal

Digital signals will be directly interfaced to CPU

Analog devices requires some converter for interfacing with CPU

All peripherals can not be always on-chip

MODULE - 3 ECE4003 – EMBEDDED SYSTEM DESIGN


PROGRAMMING I/P and O/P

Internal I/O devices


 Physically silicon devices
 Small size
Ex: RTC, ADCs, memory
External I/O devices
 Have large size
 Has bus interface
Ex: LCD, keypad, MIC

MODULE - 3 ECE4003 – EMBEDDED SYSTEM DESIGN


PROGRAMMING INPUT & OUTPUT

 CPU communicates to the device by reading and writing to the registers.


 Data register – read and write, Status register – read only

Status
Register
CPU Device
Mechanism
Data
Register

MODULE - 3 ECE4003 – EMBEDDED SYSTEM DESIGN


PROGRAMMING INPUT & OUTPUT

 Microcontroller programming input and output


 I/O mapped I/O
 Memory mapped I/O (widely used)

 Memory mapped I/O –


 Common address shared by both memory and I/O

 Read and write instructions to communicate with the devices

 Example: In 8051 Timer Register - MOV TMOD,#01H

MODULE - 3 ECE4003 – EMBEDDED SYSTEM DESIGN


PROGRAMMING INPUT & OUTPUT

 Busy-Wait I/O
 Checking an I/O device if it has completed the task by reading its status register
often called polling.
 Example: AGAIN: JNB TF0, AGAIN

 Interrupts
 It enables I/O devices to signal the completion or status and force execution of a
particular piece of code.
 Example: MOV IE, #82H

MODULE - 3 ECE4003 – EMBEDDED SYSTEM DESIGN


PROGRAMMING
ADC & DAC
ANALOG TO DIGITAL (ADC) CONVERTER
 An ADC is an electronic circuit whose digital output is proportional to
its analog input.

 Effectively it “measures” the input voltage and gives a binary output


number proportional to its size.

 The list of possible analog input signals is endless, (e.g. audio and
video, medical or climatic variables)

 The ADC when operates within a larger environment, often called a


data acquisition system.

MODULE - 3 ECE4003 – EMBEDDED SYSTEM DESIGN


ANALOG TO DIGITAL (ADC) CONVERTER

 ADC conversion D=

Where,
 Vi is the input voltage
 Vr the reference voltage
 n the number of bits in the converter output
 D the digital output value.

 The output binary number D is an integer


 For an n-bit number can take any value from 0 to (2n - 1).
MODULE - 3 ECE4003 – EMBEDDED SYSTEM DESIGN
ANALOG TO DIGITAL (ADC) CONVERTER

 ADC has maximum and minimum permissible input values.

 Resolution is a measure of how precisely an ADC can convert and


represent a given input voltage.
Resolution =

 Arduino ADC is 10-bit. This leads to a resolution of 5/1024, or 4.88 mV.

MODULE - 3 ECE4003 – EMBEDDED SYSTEM DESIGN


ANALOG TO DIGITAL (ADC) CONVERTER
 Not all the pins on a microcontroller have the ability to do analog to
digital conversions.

 In Arduino board, analog pins have an ‘A’ in front of their label (A0
through A5).

 A 10-bit device a total of 1024 different values.

 An input of 0 volts would result in a decimal 0.

 An input of 5 volts would give the maximum of 1023.

MODULE - 3 ECE4003 – EMBEDDED SYSTEM DESIGN


ANALOG TO DIGITAL (ADC) CONVERTER
 ADC value to voltage conversion

 ADC value – 434

434 =

= 2.12 V

MODULE - 3 ECE4003 – EMBEDDED SYSTEM DESIGN


ANALOG TO DIGITAL (ADC) CONVERTER

Analog I/O
 AREF pin and analogReference(type) ADC reference other than 5 V.
 Increase the resolution available to analog inputs
 That operate at some other range of lower voltages below +5
 Must be declared before analogRead()
analogReference(type)

Parameters type:
which type of reference to use (DEFAULT,
INTERNAL, INTERNAL1V1, INTERNAL2V56, or
EXTERNAL)
Returns
None
MODULE - 3 ECE4003 – EMBEDDED SYSTEM DESIGN
ANALOG TO DIGITAL (ADC) CONVERTER

Analog I/O
analogRead(pin)
 Reads the value from a specified analog pin with a 10-bit resolution.
 Works for analog pins (0–5).
 It will return a value between 0 to 1023.
analogRead(pin)
 100 microseconds for one reading.
 Reading rate 10000 per sec. Parameters pin:
the number of the analog input pin to read
 INPUT nor OUTPUT need not be declared. from (0-5)

Returns
int(0 to 1023)
MODULE - 3 ECE4003 – EMBEDDED SYSTEM DESIGN
ANALOG TO DIGITAL (ADC) CONVERTER
analogWrite(pin,value)
Analog I/O
Parameters pin: the number of the pin you
analogWrite(pin,value) want to write
value: the duty cycle between 0 (always off,
 Write an analog output on a digital pin. 0%) and 255 (always on, 100%)

 This is called Pulse Width Modulation. Returns


None
 PWM uses digital signals to control analog devices.

 Digital Pins # 3, # 5, #6, # 9, # 10, and # 11 can be used as PWM pins.

 No need to configure pin as an OUTPUT.

MODULE - 3 ECE4003 – EMBEDDED SYSTEM DESIGN


ANALOG TO DIGITAL (ADC) CONVERTER

EXAMPLE 1

Program an Arduino board to read analog value from an analogy input pin,
convert the value into digital value and display it in a serial window.

MODULE - 3 ECE4003 – EMBEDDED SYSTEM DESIGN


ANALOG TO DIGITAL (ADC) CONVERTER

CODE int sensorValue = 0;

void setup()
{
//monitor output in serial port
Serial.begin(9600); //intitating serial communication with 9600 baud rate
}

void loop()
{
sensorValue = analogRead(A0);
//analog input is read from A0 pin
Serial.println(sensorValue);
//printing the output in serial port
delay(100); // simple delay of 100ms
}

MODULE - 3 ECE4003 – EMBEDDED SYSTEM DESIGN


ANALOG TO DIGITAL (ADC) CONVERTER

CODE

MODULE - 3 ECE4003 – EMBEDDED SYSTEM DESIGN


ANALOG TO DIGITAL (ADC) CONVERTER

EXAMPLE 2

Code an Arduino board to read a temperature sensor connected to an


analog input A0 and display the temperature value in serial window. Each
time the value goes beyond 40 degree Celsius an LED connected to a digital
output glows as warning.

MODULE - 3 ECE4003 – EMBEDDED SYSTEM DESIGN


ANALOG TO DIGITAL (ADC) CONVERTER
const int lm35_pin = A0; /* LM35 O/P pin */
CODE const int ledPin = 13;
void setup() {
Serial.begin(9600);
pinMode(ledPin,OUTPUT);
}

void loop() {
int temp_adc_val;
float temp_val;
temp_adc_val = analogRead(lm35_pin); /* Read Temperature */
temp_val = (temp_adc_val * 4.88); /* Convert adc value to equivalent voltage */
temp_val = (temp_val/10); /* LM35 gives output of 10mv/°C */
if (temp_val > 40) {
digitalWrite(ledPin, HIGH); // turn LED on:
} else {
digitalWrite(ledPin, LOW); // turn LED off:
}
Serial.print("Temperature = ");
Serial.print(temp_val);
Serial.print(" Degree Celsius\n");
delay(1000);
}

MODULE - 3 ECE4003 – EMBEDDED SYSTEM DESIGN


ANALOG TO DIGITAL (ADC) CONVERTER

CODE

MODULE - 3 ECE4003 – EMBEDDED SYSTEM DESIGN


DIGITAL TO ANALOG (DAC) CONVERTER

 A digital-to-analog converter is a circuit which converts a binary input


number into an analog output.

 DAC has a digital input, represented by D, and an analog output,


represented by Vo.
𝑽𝒓
+

+
𝑫 DAC =
-

Control Lines
MODULE - 3 ECE4003 – EMBEDDED SYSTEM DESIGN
DIGITAL TO ANALOG (DAC) CONVERTER

 For each input digital value, there is a corresponding analog output.

 The number of possible output values is given by 2 n.

 The step size by Vr/2n this is called the resolution.

 The maximum possible output value occurs when D = (2n-1), so the


value of Vr as an output is never quite reached.

MODULE - 3 ECE4003 – EMBEDDED SYSTEM DESIGN


DIGITAL TO ANALOG (DAC) CONVERTER

MODULE - 3 ECE4003 – EMBEDDED SYSTEM DESIGN


ANALOG TO DIGITAL (ADC) CONVERTER

MODULE - 3 ECE4003 – EMBEDDED SYSTEM DESIGN


PULSE WIDTH MODULATION (PWM)
EXAMPLE 1
Code an Arduino board to control the speed of a DC motor using
potentiometer.
CODE int potvalue;
void setup()
{
pinMode(A0, INPUT);
pinMode(6, OUTPUT);
}

void loop()
{
potvalue=analogRead(A0)/4;
analogWrite (6, potvalue);
}

MODULE - 3 ECE4003 – EMBEDDED SYSTEM DESIGN


ANALOG TO DIGITAL (ADC) CONVERTER

MODULE - 3 ECE4003 – EMBEDDED SYSTEM DESIGN


PROGRAMMING
TIMERS/COUNTER
TIMER / COUNTER

 Digital timer/counters are used throughout embedded designs


 To provide a series of time or count related events within the system
 With the minimum of processor and software overhead

 Most embedded systems have a time component within them such as


 Timing references for control sequences
 To provide system ticks for operating systems and
 Even the generation of waveforms
 Serial port baud rate generation and audible tones.

MODULE - 3 ECE4003 – EMBEDDED SYSTEM DESIGN


TIMER / COUNTER

 Timers and counters are distinguished from one another largely by


their use, not their logic.

 Timer – Periodic Signal


 Counter – Aperiodic signal

MODULE - 3 ECE4003 – EMBEDDED SYSTEM DESIGN


TIMER / COUNTER

 The central timing is derived from a clock input.


 Internal to the timer/counter
(or)
 External and thus connected via a separate pin.

 The clock may be divided using a simple divider


 A pre-scalar - effectively divides the clock by the value that is
written into the pre-scalar register

 The divided clock is then passed to a counter


 count-down operation or count-up operation
MODULE - 3 ECE4003 – EMBEDDED SYSTEM DESIGN
TIMER / COUNTER

 When a zero count is reached, an event occurs.


 such as an interrupt of an external line changing state.

 The final block is an I/O control block


 It generates interrupts
 Can control the counter based on external signals

MODULE - 3 ECE4003 – EMBEDDED SYSTEM DESIGN


TIMER / COUNTER

Timers on the Arduino


 The Arduino Uno has 3 timers: Timer0, Timer1 and Timer2
1. Timer 0 – 8 bit timer ; Functions – delay(), millisec().
2. Timer 1 – 16 bit timer; Servo library
3. Timer 2 – 8 bit timer; Function – tone()

 Arduino Uno has a 16Mhz internal clock.


 It takes 62 nano seconds for a single count.
 Update the pre-scalar to alter the frequency and various counting
modes.
 Generate interrupts when the timer reaches a specific count
MODULE - 3 ECE4003 – EMBEDDED SYSTEM DESIGN
TIMER / COUNTER

Control Registers

 Timer/Counter Control Registers A: (TCCRnA)


 Timer/Counter Control Registers B: (TCCRnB)
 Timer CounNT: TCNTn
 Output Compare Register A: OCRnA
 Output Compare Register B: OCRnB
n= C/T number 0,1,2
http://www.avrbeginners.net/architecture/timers/timers.html

MODULE - 3 ECE4003 – EMBEDDED SYSTEM DESIGN


TIMER / COUNTER

Timer/Counter Modes

 Normal : Counter count up to maximum value and reset to 0


 Phase correct PWM: symmetric with respect to system clock using
PWM
 Clear Time on Compare (CTC): Used in interrupt generation
 Fast PWM: PWM goes as fast as clock but not synchronized with
timing clock
http://www.avrbeginners.net/architecture/timers/timers.html

MODULE - 3 ECE4003 – EMBEDDED SYSTEM DESIGN


TIMER / COUNTER

Timers on the Arduino


 Timer/Counter Control Registers (TCCRnA/B)
 Controls the mode of timer
 Contains the pre-scalar values of timers
 Prescalars values 1, 8, 64, 256, 1024
To calculate preloaded value for timer1
 Timer/Counter Register (TCNTn) for time of 2 Sec:
 Control the counter value TCNT1= 65535-(16xx time(s)/ Prescalar
 Set the pre-loader value value)
TCNT1 = 65535 – (16x x2 / 1024) =
34285

MODULE - 3 ECE4003 – EMBEDDED SYSTEM DESIGN


TIMER / COUNTER

Timers on the Arduino


 delay(ms)
 Pauses the program for the amount of time.

 Time is specified in milliseconds


delay(ms)
 A delay of 1000 ms equals 1 s
Parameters
ms: the number of milliseconds to pause
(unsigned long)

Returns
None
MODULE - 3 ECE4003 – EMBEDDED SYSTEM DESIGN
TIMER / COUNTER

Timers on the Arduino


 delayMicroseconds()
 Used to delay for a much shorter time.

 A time period of 1000 µs would equal 1 ms.


delayMicroseconds()

Parameters
us: the number of microseconds to pause
(unsigned int)

Returns
None
MODULE - 3 ECE4003 – EMBEDDED SYSTEM DESIGN
TIMER / COUNTER

Timers on the Arduino


 millis()
 Use of one of internal timer1 to maintain a running counter.
 How many milliseconds the microcontroller has been running since the
last time it was turned on or reset.
 It returns a value in milliseconds millis()

Parameters
None

Returns
Number of milliseconds since the program
started (unsigned long)
MODULE - 3 ECE4003 – EMBEDDED SYSTEM DESIGN
TIMER / COUNTER

Timers on the Arduino


 micros()
 Returns the value in microseconds.

micros()

Parameters
None

Returns
Number of microseconds since the program
started (unsigned long)
MODULE - 3 ECE4003 – EMBEDDED SYSTEM DESIGN
TIMER / COUNTER

EXAMPLE

Code an Arduino board to read a pushbutton connected to a digital input to


display millis() when ON and display micros() when OFF. Blink an LED
connected to a digital output with 500 ms delay.

MODULE - 3 ECE4003 – EMBEDDED SYSTEM DESIGN


TIMER / COUNTER
#define LED 13
CODE int buttonState = 0;
void setup() {
Serial.begin(9600);
pinMode(LED, OUTPUT);
pinMode(7, INPUT);}
void loop() {
digitalWrite(LED, HIGH);
delay(500);
digitalWrite(LED, LOW);
delay(500);
buttonState = digitalRead(7);
if(buttonState==LOW) {
Serial.write("micros()=");
Serial.println(micros());
}else {
Serial.write("millis()=");
Serial.println(millis());
}}

MODULE - 3 ECE4003 – EMBEDDED SYSTEM DESIGN


TIMER / COUNTER

MODULE - 3 ECE4003 – EMBEDDED SYSTEM DESIGN


PROGRAMMING
LED & SWITCHES
PROGRAMMING LED & SWITCHES

Digital I/O
 Read the state of an input pin

 Produce a logical high or low at an output pin

 Each bit of a port can be programmed independently


 As input
 As output
 All for the same purpose

 ATmega 328P - Three 8-bit i/o ports and one 7-bit i/o port
PROGRAMMING LED & SWITCHES

Digital I/O
 Input:
 Read voltage applied to them

 Small amount of current to change an INPUT pin’s state

 Change state due to electronic interference like static discharges (I/P pin
with no connection)

 Pull-down resistor (going to ground) all ways connect unused I/P pin to
ground
PROGRAMMING LED & SWITCHES

Digital I/O

 Output:
 Up to 40 mA current can be delivered to output circuits,.

 Can power LED but not a motor (need driver circuit).

 Cannot read sensors.

 Connecting output pin directly to 5V or 0V is not advised.


PROGRAMMING LED & SWITCHES
Digital
Input I/O
Pullup:

 Sets a pin as I/P and connects an internal resistor.

 Inverts the behavior of the INPUT mode.

 If the button is pressed, pulled to ground resulting in zero.

 If the button is not pressed, connected to 5 volts resulting one.

 Internal resistor is atleast 20 kilohms.


https://www.arduino.cc/en/Tutorial/InputPullupSerial#:~:text=When%20your%20button%20is%20not,%220%22%2C%20or%20LOW.
PROGRAMMING LED & SWITCHES

Pin Configuration
 Inform the controller how it should operate
 In Arduino based embedded system - pinMode(pin,mode)
 Pin – number or variable (e.g. 1 to 13 or A0 to A5)
 Digital pins are input by default pinMode(pin,mode)

Parameters
pin: the number of the pin whose mode you
wish to set
mode: INPUT, OUTPUT, or INPUT_PULLUP
Returns
None
PROGRAMMING LED & SWITCHES

digitalWrite(pin,value)
Pin Configuration
Parameters
 digitalWrite(pin, value) Pin: the number of the pin you want to write
value: HIGH or LOW
 Output pin
 Write on or off Returns
None

digitalRead(pin,value)
 digitalRead(pin, value)
Parameters
 Input pin Pin: the number of the pin you want to read (int)
 Read a state of a pin Returns
HIGH or LOW
PROGRAMMING LED & SWITCHES

EXAMPLE

Code an Arduino board to read a pushbutton connected to a digital input


and turn on an LED connected to a digital output when the button is
pressed.
PROGRAMMING LED & SWITCHES
const int buttonPin = 2; // the number of the pushbutton pin
CODE const int ledPin = 13; // the number of the LED pin
int buttonState = 0; // variable for reading the pushbutton status

void setup() {
pinMode(ledPin, OUTPUT); // initialize the LED pin as an output:
pinMode(buttonPin, INPUT); // initialize the pushbutton pin as an input:
}

void loop() {
buttonState = digitalRead(buttonPin); // read the state of the pushbutton value:
// check if the pushbutton is pressed. If it is, the buttonState is HIGH:
if (buttonState == HIGH) {
digitalWrite(ledPin, HIGH); // turn LED on:
} else {
digitalWrite(ledPin, LOW); // turn LED off:
}
}
PROGRAMMING LED & SWITCHES
INTRODUCTION TO SERIAL PORT
 Serial communication protocol is used by computers and electronic modules
to send and receive control information and data.

 Serial communication is the process of transmitting data one bit at a time.

 A universal asynchronous receiver/transmitter (UART) is a block of circuitry


responsible for implementing serial communication in microcontrollers.

 Arduino boards communicate with the PC via USB cable(using inbuilt USB
to TTL converter chip) or to other serial devices using the serial pins.

 Arduino Uno has one serial port at digital pins 0 (Tx) and 1(Rx).
Arduino Uno - Board Details

Image credit: Pinrest, Ref. URL : https://in.pinterest.com/pin/817192294868619357/


INTRODUCTION TO SERIAL PORT
 “SoftwareSerial” Library can been used to replicate the functionality of the
hardwired RX and TX pins on other digital pins using software.

 You can use the Arduino environment's built-in serial monitor to


communicate with an Arduino board.

 Serial channels have a number of configurable parameters Baud Rate, Data


length, Parity and Stop Bits; Default is 8 data bits, no parity, 1 stop bit.
INTRODUCTION TO SERIAL PORT
API required:
 Serial.begin(speed) - Configures a serial port with specified baud rate.
- Serial: To access serial port in Arduino Uno.
- begin: To configuring serial port.
- speed: To specify the baud rate for serial communication.

 Serial.println(val) - Prints data on serial port as human-readable ASCII text.


- println: To perform printing text followed by a newline character.
- val: Specify value or text to be printed on serial monitor.

 Serial.readString() - reads characters from the serial buffer into a String.


- readString: A String read from the serial buffer.
.
TASK-1
Transmit a message to Serial port
Write a program to transmit a message “VIT SENSE” using serial port (Tx and
Rx pins) to PC serial monitor window for every 2 seconds. Simulate and verify
this logic on Arduino Uno using Tinkercad circuits simulator.
TASK-1
Output
TASK-2
Write a program to transmit a message on serial window based on the slide
switch state.
Connect the slide switch on one of the digital pins
If the slide switch state is HIGH print your name on serial window
If the slide switch state is LOW print your reg. no. on serial window
Simulate and verify this logic on Arduino Uno using Tinkercad circuits simulator.

Connect the slide switch on one of the digital pins


If the slide switch state is HIGH print your name on serial window
If the slide switch state is LOW print your reg. no. on serial window
Simulate and verify this logic
TASK-2
int ss;
void setup()
{
pinMode(12, INPUT);
Serial.begin(9600);
}

void loop()
{
ss= digitalRead(12);
if(ss == HIGH){
Serial.println("SHRUDHI");
delay(1000); //wait for 1000 milliseconds
}
else if(ss == LOW){
Serial.println("19BLC1166");
delay(1000); //wait for 1000 milliseconds
}
}
TASK-3

Controlling LED using user input via serial port


Write a program to control the LED connected at pin 12 of digital pin based on
the input string received from user via serial port
 If the string is “ON”, print “ON” on serial window and switch ON the LED for 5 Seconds
 If the string is “OFF”, print “OFF” on serial window and switch ON the LED for 5 Seconds
 Otherwise print “BLINK” on serial window and blink the LED with the delay of 1 second

Simulate and verify this logic on Arduino Uno using Tinkercad circuits
simulator.
TASK-3
Progra Output Design
m
INTRODUCTION TO ULTRASONIC SENSOR
 An ultrasonic sensor is an electronic device that measures the distance of a
target object by emitting ultrasonic sound waves, and converts the reflected
sound into an electrical signal.
 Ultrasonic sensors have two main components:
 Transmitter (which emits the sound using piezoelectric crystals)
 Receiver (which encounters the sound after it has travelled to and from the target).

 In order to calculate the distance between the sensor and the object, the
sensor measures the time it takes between the emission of the sound by the
transmitter to its contact with the receiver.
 The formula for this calculation is D = ½ T x C (where D is the distance, T is
the time, and C is the speed of sound ~ 343 meters/second).
DAY-5 Arduino Programming Workshop 68
INTRODUCTION TO ULTRASONIC SENSOR
 Ultrasonic sensors are used primarily as proximity sensors.
 They can be found in automobile self-parking technology, anti-collision
safety systems, robotic obstacle detection systems also used as level sensors
to detect, monitor, and regulate liquid levels in closed containers.
 The HC-SR04 ultrasonic sensor offers excellent non-contact range detection
with high accuracy and stable readings from 2 cm to 400 cm.
 It comes complete with ultrasonic transmitter and receiver module.

 The HC-SR04 Ultrasonic Module has 4 pins, Ground (Gnd), VCC (5V) , Trig
and Echo. The trig and echo pins to any Digital I/O pin on the Arduino Board.

DAY-5 Arduino Programming Workshop 69


INTRODUCTION TO ULTRASONIC SENSOR
 Steps involved in measuring distance using HC-SR04 Ultrasonic module are,
 Transmit trigger pulse of at least 10 us to the HC-SR04 Trig Pin.

 Then the HC-SR04 automatically sends Eight 40 kHz sound wave and wait for rising
edge at Echo pin.

 When the rising edge capture occurs at Echo pin, start the Timer and wait for falling
edge on Echo pin.

 As soon as the falling edge is captured at the Echo pin, read the count of the Timer.
This time count is the time required by the sensor to detect an object and return back
from an object (to and from). Distance = (Speed x Time)/ 2
Distance = (0.034 cm/µs x 500 µs) / 2
Distance = 8.5 cm
DAY-5 Arduino Programming Workshop 70
INTRODUCTION TO ULTRASONIC SENSOR
Distance = (Speed x Time)/ 2
Distance = (0.034 cm/µs x 500 µs) / 2
Distance = 8.5 cm

When no obstacles then timeout after 38ms When obstacle detected pulse width of 50 µS to 25 mS received
DAY-5 Arduino Programming Workshop 71
LAB TASK-1
Read the distance value from HC-SR04 and print it on serial monitor

Write a program to read distance value from HC-SR04 ultrasonic sensor module in
cm and print it on the serial monitor. Simulate and verify this logic on Arduino Uno
using Tinkercad circuits simulator.

pulseIn() - 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.
DAY-5 Arduino Programming Workshop 72
int trig = 11;
int echo = 10;
float timeduration;
float distance;
void setup()
{
Serial.begin(9600);
pinMode(trig, OUTPUT);
pinMode(echo, INPUT);
}
void loop()
{
digitalWrite(trig, LOW);

delayMicroseconds(2);
digitalWrite(trig, HIGH);
delayMicroseconds(10);
digitalWrite(trig, LOW);
timeduration = pulseIn(echo, HIGH);
distance = 0.034 * timeduration / 2;
Serial.print("Distance in cm: ");
Serial.println(distance);
delay(500);
}
LAB TASK-1
Program & output Design

DAY-5 Arduino Programming Workshop 74


WRITE A PROGRAM FOR AUTOMATIC STAIRCASE LIGHT USING PIR SENSOR IN
WHICH THIS SYSTEM SWITCH ON THE STAIRCASE LIGHT AUTOMATICALLY WHEN
SOMEONE ENTERS ON THE STAIRS AND GETS OFF AFTER 5 SECONDS.
SIMULATE AND VERIFY THIS LOGIC ON ARDUINO UNO USING TINKERCAD
CIRCUITS SIMULATOR.
• int sensor_pin=13;
• int relay_pin=2;
• int output;
• void setup()
• {
• Serial.begin(9600);
• pinMode(sensor_pin,INPUT);
• pinMode(relay_pin,OUTPUT);
• digitalWrite(relay_pin,LOW);
• }
• void loop(){
• //read output of our PIR sensor
• output = digitalRead(sensor_pin);
• //if output is HIGH if(output==1)
• {
• digitalWrite(relay_pin,HIGH); delay(5000);
• }
• //if output is LOW
• if(output==0)
• {
• digitalWrite(relay_pin,LOW);
• }
• Serial.println(output);
• delay(100);
• }

You might also like