Project 2 - Measuring distance of an object using ultrasonic sensor (HC-SR04)
/*
* project_2.c
*
* Created: 02-10-2022 14:35:53
* Author : SANDEEP
*/
#include <avr/io.h>
#define F_CPU 16000000ul
#include <util/delay.h>
#include <avr/interrupt.h>
#include <string.h>
#include <stdlib.h>
#define trigger PB1//defining trigger pin as PB1
#define echo PB0//defining echo pin as PB0
int pw;//global variable
void trigger_init(void);//prototypes of functions
void timer_init(void);
//function definition of trigger
void trigger_init()
{
PORTB|=(1<<trigger);
_delay_us(25);//delay to send pulses or signals
PORTB &= ~(1<<trigger);
}
void timer_init()
{
ACSR |=(1<<ACIC);//this bit enables the Input Capture function in Timer/Counter1 to be triggered by the Analog Comparator
TIFR1 |=(1<<ICF1);//The ICF1 bit is set (one) to flag an input capture event, indicating that the Timer/Counter1 value has been transferred to the input capture register - ICR1
TCNT1=0;//initilization of counter with 0
TCCR1A = 0b00000000;//Normal Timer mode operation
TCCR1B = 0b00000100;//prescaling with 256
TIMSK1 |= (1<<ICIE1);
sei();//Global interrupt enable
}
ISR(TIMER1_CAPT_vect)// Interrupt serive routine
{
pw=((ICR1-12)*10)/625;//pulse width calculation
}
int main(void)
{
Serial.begin(9600);//initialization of serial monitor
unsigned int distance=0;
DDRB |= (1<<1);//configuration of trigger pin as output
/* Replace with your application code */
while (1)
{
trigger_init();//calling function of trigger
timer_init();//calling timer initialization func
distance=(34*pw)/2;///calculating distance
Serial.println(distance);//printing serial monitor
_delay_ms(40);
Serial.println("cm");// printing unit
}
}