Project 2 - Measuring distance of an object using ultrasonic sensor (HC-SR04)
Overview of the Project:
In this project, the implementation of code for “Measuring distance of an object using ultrasonic distance sensor (HC-SR04)
Goals:
- Measuring the distance of an object using Ultrasonic Distance Sensor (HC-SR04)
- Usage of Input Capture Mode
Key Highlights of the Project:
- Measuring the distance travelled by the wave to the object and gets bounced back from the object to sensor.
- Measuring Pulse width using Input Capture Mode
Deliverables of this project:
- The distance travelled by a wave to the object for which we want to measure the distance using Ultrasonic Distance Sensor (HC-SR04).
- Measuring Pulse width using Input Capture Mode of Timer 1.
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() //making PB1 high, after a delay of 15 microseconds, making PB1 low
{
PORTB |= (1<<1);
_delay_us(15);
PORTB &=~ (1<<1);
}
void Timer_Intialization()
{
ACSR = (1<<ACIC); //Making ACIC pin high in ACSR register
TIFR1 |= (1<<ICF1);
TCNT1 = 0;
TCCR1A = 0x00;
TCCR1B = 0x04;
TIMSK1 = 0x20;
sei(); //Enabling global interrupt
}
int main()
{
unsigned int distance = 0;
DDRB |= (1<<1); //Making PB1 as output using DDR
while(1)
{
trigger(); //calling trigger function
Timer_Intialization(); //calling initializaton function
distance = (34*pulse_width)/2; // calculating the distance
Serial.print(distance);
Serial.print("cm");
_delay_ms(50);
}
}
ISR(TIMER1_CAPT_vect)
{
pulse_width = ((ICR1 - 12)*10)/625;
}
OUTPUT:
Here I've attached the circuit diagram ,the AVR P2 is the working condition of the sensor at 0 distance and AVR P2 output is shows that sensor measuring the object at distance .