Hi,
I want to interface a ultrasonic sensor to attiny2313. The code I developed using avrgcc. I used capture interrupt of the avr to capture the rising and falling edge of the pulse and calculate the time elapsed in doing so. In this process, after capturing the falling edge of the pulse, the timer is switched of and again it is switched on only after triggering the sensor. The code below works fine but when the distance is low (say 10cm), timer overflows and everything stops. But by seeing the speed of the avr core and timer, it has no chance to overflow. I cannot sort it out.
What is the problem in this code which makes the timer overflow?
Thanks.
I want to interface a ultrasonic sensor to attiny2313. The code I developed using avrgcc. I used capture interrupt of the avr to capture the rising and falling edge of the pulse and calculate the time elapsed in doing so. In this process, after capturing the falling edge of the pulse, the timer is switched of and again it is switched on only after triggering the sensor. The code below works fine but when the distance is low (say 10cm), timer overflows and everything stops. But by seeing the speed of the avr core and timer, it has no chance to overflow. I cannot sort it out.
Rich (BB code):
#include "avr/io.h"
#include "avr/interrupt.h"
#define F_CPU 8000000
#include "util/delay.h"
volatile unsigned int pulseStart;
volatile unsigned int pulseEnd;
volatile unsigned int pulseInUs = 2013;
volatile unsigned char edge =0;
volatile unsigned int success = 0;
volatile unsigned int failure = 0;
#define START_TIMER TCCR1B |= ((1 << CS11) | (1 << CS10))
#define STOP_TIMER TCCR1B &= ~((1 << CS11) | (1 << CS10))
void pulseSensor(void){
PORTB |= (1 << 0);
_delay_us(10);
PORTB &= ~(1 << 0);
}
void initialisePorts(void){
DDRD &= ~(1 << 6); //PORTD.6 = INPUT
DDRB |= (1 << 0) | (1 << 1) | (1 << 2); //PORTB.0 = PORTB.1 = OUTPUT
}
void blinkLED(unsigned int port){
DDRB |= (1 << port);
PORTB ^= (1 << port);
_delay_ms(200);
}
int main(void){
initialisePorts();
TIMSK |= ((1 << ICIE1)| (1 << TOIE1)); //Set capture interrupt
sei(); //Set global interrupt
TCCR1B |= (1 << ICES1); //Set capture rising edge
pulseSensor();
START_TIMER;
for(;;){
if(success){
success = 0;
if(pulseInUs <= 200) //Obstacle in range
PORTB |= (1 << 1);
else
PORTB &= ~(1 << 1); //Obstacle not in range
pulseSensor();
START_TIMER;
}
if(failure){
failure = 0;
PORTB |= (1 << 2);
}
}
return 0;
}
ISR(TIMER1_CAPT_vect){
if(edge == 0){
pulseStart = ICR1; //copy capture value
TCCR1B &= ~(1 << ICES1); //toggle capture edge
edge = 1;
}
else{
pulseEnd = ICR1; //copy capture value
TCCR1B |= (1 << ICES1); //toggle capture edge
edge = 0;
STOP_TIMER;
TCNT1 = 0;
pulseInUs = pulseEnd - pulseStart;
success = 1;
}
}
ISR(TIMER1_OVF_vect){
failure = 1;
TCCR1B |= (1 << ICES1);
STOP_TIMER;
TCNT1 = 0;
edge = 0;
}
Thanks.