Challenge

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

unsigned int pulse_width;
void trigger()
{
Serial.begin(9600); // baud rate
PORTB|= (1<<PORTB1);
Serial.print(" Distance ");
Serial.print(" Measurement ");
_delay_us(2000);//wait for 2 seconds
PORTB &= ~(1<<PORTB1);
}

void init_timer()
{
ACSR |= (0<<ACIC);//Selecting ICP1 bit as Capture Input
TIFR1 = (1<<ICF1);//Clearing Input Capture Flag register
TCNT1 = 0;
TCCR1A |= (0<<WGM11)|(0<<WGM10);
TCCR1B |= (0<<ICES1)|(0<<WGM13)|(0<<WGM12)|(1<<CS12); //SETTING RISING EDGE, selected PRESCALER AS 256
TIMSK1 |= (1<<ICIE1);
sei();
}
ISR(TIMER1_CAPT_vect)
{
pulse_width = ((ICR1 - 12)*10)/625;
}

int main(void)
{
float distance = 0;
DDRB |= (1<<DDB1);//Configure the trigger pin as output
while(1)
{
trigger();
init_timer();

distance = (40*pulse_width)/2;
Serial.print(distance);
Serial.println("cm");
_delay_ms(2000);
}
}

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.