Project 2 - Measuring distance of an object using ultrasonic sensor (HC-SR04)
ANS:
#define Trigger PB1//define PB1 as Trigger Pin as macro
#define Echo PB0//define PB0 as Echo pin as macro
int pulse_width;//globally declare the vaiable in the ISR
void Trigger_pulse()//trigger function
{
PORTB|=(1<<1);//B1 is Digital Pin (PWM) high. counter or timer compare match A.
_delay_us(15);//delay of 15micro seconds. for counting
PORTB &= ~(1<<1);//make B1 pin low
}
void Timer_init()//Timer initilization
{
/*analog comparator control and status register (ACSR)-• Bit 2 – ACIC: Analog Comparator Input Capture Enable
When written logic one, this bit enables the input capture function in Timer/Counter1 to be triggered by the analog
comparator. When written logic zero, no connection between the analog comparator and the input capture function exists*/
ACSR=(0<<ACIC);
/*TIFR1 – Timer/Counter1 Interrupt Flag Register-• Bit 5 – ICF1: Timer/Counter1, Input Capture Flag
This flag is set when a capture event occurs on the ICP1 pin(ICP1, input capture pin)*/
TIFR1=(1<<ICF1);
TCNT1=0;//initilize timer counter register to 0
/*Timer/Counter control registers A and B (TCCR1A and TCCR1B)*/
TCCR1A=0x00;
TCCR1B=0x04;//c12-1(clk/256 (from prescaler)
TIMSK1=0x20;/*Timer/Counter1 Interrupt Mask Register-input capture interrupt is enabled. The corresponding interrupt vector is executed
when the ICF1 flag, located in TIFR1, is set.*/
sei();//Enable global interrupt
}
int main()
{
int distance = 0;//variable declareation for distance
DDRB|=(1<<1);//output pin
while(1)
{
Trigger_pulse();//trigger function
Timer_init();//timer initilization function
distance=(34*pulse_width)/2;//Speed of ultrasonic wave is 347 m/s(dis=speed/time)
Serial.print(distance);//for printing the distance
Serial.print("cm");//printing the string
Serial.println(" ");//printing the string
_delay_ms(50);//for calculating it takes some time
}
}
ISR(TIMER1_CAPT_vect)//Interrupt Service Routine
{
pulse_width = ((ICR1 - 12)*10)/625;
}