Challenge

Project 2 - Measuring distance of an object using ultrasonic sensor (HC-SR04)

/*
* project2.c
*
* Created: 14-12-2022 20:53:18
* Author : 91948
*/

#include <avr/io.h>
#include <util/delay.h>
#define F_CPU 16000000L;
void trigger()
{
serial.begin(9600);
PORTB |=(1<<PORTB1); // set the bits

_delay_ms(20);
PORTB &=~(1<<PORTB1); // clear the bits

};
void init_timer()
{

ACSR |=(0<<ACIC); // selecting ICP1 as capture input //
TIFR1 = (1<<ICF1); // clearing input capture flag //
TCNT1=0;
TCCR1A |=(0<<WGM11)|(0<<WGM10);
TCCR1B |=(0<<ICES1)|(0<<WGM13)|(0<<WGM12)|(1<<CS12); // setting rising edge ,prescaler as256 //
TIMSK1 |=(1<<ICIE1);
sei();

}
ISR(TIMER1_CAPT_vect)
{
pluse_width=((ICR1-12)*10)/625;
}

int main(void)
{
float distance=0;
DDRB|=(1<<DDB1);
/* Replace with your application code */
while (1)
{
trigger();
init_timer();// configure the trig pin as output
distance =(34*pulse_width)/2;
serial.print(distance);
serial.println ("cm");
_delay_ms(30);
}
}

output

Your portfolio, next

Ship work like this
in your own course.

Talk to a career counsellor

Free 20-minute call. We'll map the right course to where you want to work.

By submitting you agree to our Terms and Privacy Policy.