Challenge

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

#include <avr/io.h>
#define F_CPU 16000000
#include <util/delay.h>
#define TRIG PB1
#define ECHO PB0
unsigned int pulse_width,TimerOverflow;
int main(void)
{
float distance = 0;
DDRB |= (1<<DDB1); //Configure the trig pin as output
while(1) //Infinite loop
{
trigger();
init_timer();
distance = (34*pulse_width)/2;
Serial.print(distance);
Serial.println("cm");
_delay_ms(40);
}
}
void trigger()
{
Serial.begin(9600);
PORTB|= (1<<PORTB1);//Outputs 1
_delay_us(15);//wait for 15us
PORTB &= ~(1<<PORTB1);//outputs 0
}
void init_timer()
{
ACSR |= (0<<ACIC);//Selecting ICPl 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,prescalar as 256
TIMSK1 |= (1<<ICIE1);
sei();
}
ISR(TIMER1_CAPT_vect)
{
pulse_width = ((ICR1 - 12)*10)/625; //usecondition
}

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.

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.