float pulsewidth = 0; //Declard Global Variable PulseWidth
void trigger()
{
Serial.begin(9600); //Set the Baud Rate
PORTB |= (1<<PORTB1); //Set the PORTB
_delay_us(15); //delay for 15us
PORTB &=~ (1<<PORTB1); //Clear the PORTB
}
void init_timer() //Select Various Registers Regards to the Timer
{
ACSR |= (0<<ACIC); //0x00...no Connection between the Analog comparator and input capture function exists.
TIFR1 = (1<<ICF1); //0X20...Clearing Input Capture Flag
TCNT1 = 0; //Timer/Counter 1 Register blocks(removes)
TCCR1A |= (0<<WGM11) | (0<<WGM10); //0X00, 0X00...Waveform Generation Normal mode The input Capture is easy to use normal mode, new counter value can be written any time
TCCR1B |= (0<<ICES1) | (0<<WGM13) | (0<<WGM12) | (1<<CS12); //0X44...Setting Rising Edge will trigger the capture, Prescalar as 256,
TIMSK1 |= (1<<ICIE1); //0X20..ICIE1 bit in the timer mask Register(TIMSK1)must be set.
sei();
}
ISR(TIMER1_CAPT_vect) //Input Status Register
{
pulsewidth = (((ICR1 - 12)*10)/625); //ICR1 is Definig the Counter TOP value, usecond
} //The pulsewidth High pulse at Echo pin is the time taken by the travel to the Object and gets bounced back from the object to the sensor.
int main(void)
{
float distance = 0;
DDRB |= (1<<DDB1); //Configure the trig pin as output
while (1)
{
trigger(); //Trigeer Ultrasonic Sensor
init_timer();
distance = ((34*pulsewidth)/2); //Find The distance with respect to the Pulsewidth
Serial.println("distance ="); //Using To Print in Serial monitor
Serial.print(distance);
Serial.println("cm");
_delay_ms(40);
}
}