Project 2 - Measuring distance of an object using ultrasonic sensor (HC-SR04)
In this project, the implementation of code for “Measuring distance of an object using ultrasonic distance sensor (HC-SR04)
AIM:
To implementation the code for "Measuring the distance of an object using ultrasonic distance sensor.
PROCEDURE:
- To create a new project in the arduino IDE and create a required header files.
- The header files like <avr/io.h>, <util/delay.h> and "avr/interrupt.h".
- Using macro we are defining the PB1 and PB0 pins as trigger and Echo pins.
- We are declaring the function prototypes like trigger() and Timer_Intialization() and declaring an unsigned integer variable named as "pulse_width".
- In main function we are declaring an unsigned interger variable named as "distance".
- Using the DDR register we are making the Port B 1st pin as output pins. Using infinite while loop we are calling trigger function.
- Also we are calling the Timer_Intialization() function and calculating the distance value using a formula 34*pulse_width divided by two.
- Using serial.print function we are printing the distance value and unit as "cm" and delay of 50millisecond is given.
- In the function definition of trigger we are making the PB1 pin as high, a delay of 15 microsecond is given and making PB1 pin as low.
- In the function definition of Timer_Intialization() we are making the ACSR register's ACIC bit has high value.
- Also the ICF1 flag is set in the TIFR1 register and making TCNT1 as 0.
- The TCCR1A register is given a value of 0x00 and the TCCR1B register is given a value of 0x04.
- The register TIMSK1 is given a value of 0x20 in order to enable interrupt and for enabling the global interrupt we are using sei() function.
- In the Interrupt subroutine ISR of TIMER1_CAPT_Vect we are calculating the pulse_width using the formula ((ICR1 - 12)*10)/625.
CODE:
#include <avr/io.h>
#include <util/delay.h>
#include "avr/interrupt.h"
#define TRIG PB1
#define ECHO PB0
void trigger();
void Timer_Intialization();
unsigned int pulse_width;
void trigger()
{
PORTB |= (1<<1);
_delay_us(15);
PORTB &=~ (1<<1);
}
void Timer_Intialization()
{
ACSR = (1<<ACIC);
TIFR1 |= (1<<ICF1);
TCNT1 = 0;
TCCR1A = 0x00;
TCCR1B = 0x04;
TIMSK1 = 0x20;
sei();
}
int main()
{
unsigned int distance = 0;
DDRB |= (1<<1);
while(1)
{
trigger();
Timer_Intialization();
distance = (34*pulse_width)/2;
Serial.print(distance);
Serial.print("cm");
_delay_ms(50);
}
}
ISR(TIMER1_CAPT_vect)
{
pulse_width = ((ICR1 - 12)*10)/625;
}
SIMULATION:

RESULT:
Thus the code is executed and the distance of an object is measured using ultrasonic sensor.