Use TIMER2 for sonar interrupts
This commit is contained in:
parent
1633d3e78d
commit
9f6e90f27f
@ -17,9 +17,9 @@
|
||||
|
||||
#define SPEED_OF_SOUND 343 // 20°C dry air (m/s)
|
||||
#define MAX_SONAR_RANGE 8 // Trigger + echo (m)
|
||||
#define MIN_SONAR_RANGE 3 // Minimum distance that is still reliable
|
||||
#define MIN_SONAR_RANGE 4 // Minimum distance that is still reliable
|
||||
#define SONAR_DELAY 60 // Timeout for return signal
|
||||
#define TIMER_MAX 65535 // For 16-bit timer
|
||||
#define TIMER_MAX 255 // For 8-bit timer
|
||||
#define CYCLES_PER_US (F_CPU / 1000000)
|
||||
#define SONAR_TIMEOUT (F_CPU * MAX_SONAR_RANGE) / SPEED_OF_SOUND
|
||||
|
||||
|
@ -1,7 +1,6 @@
|
||||
#include <avr/interrupt.h>
|
||||
#include <util/delay.h>
|
||||
#include "sonar.h"
|
||||
#include "led.h"
|
||||
|
||||
volatile uint32_t trig_counter;
|
||||
volatile uint32_t no_of_ticks;
|
||||
@ -27,27 +26,27 @@ int32_t read_sonar(void)
|
||||
}
|
||||
}
|
||||
|
||||
TCNT1 = 0;
|
||||
SET(TCCR1B, CS10); // Prescaler = 1
|
||||
SET(TIMSK1, TOIE1); // Enable overflow interrupts
|
||||
TCNT2 = 0;
|
||||
SET(TCCR2B, CS20); // Prescaler = 1
|
||||
SET(TIMSK2, TOIE2); // Enable overflow interrupts
|
||||
no_of_ticks = 0; // Reset overflow counter
|
||||
|
||||
sei();
|
||||
// Count cycles until ECHO goes low
|
||||
while (CHK(ECHO_PIN, ECHO_BIT)) {
|
||||
if (no_of_ticks + TCNT1 > SONAR_TIMEOUT) {
|
||||
if (no_of_ticks + TCNT2 > SONAR_TIMEOUT) {
|
||||
return ECHO_TIMEOUT;
|
||||
}
|
||||
}
|
||||
TCCR1B = 0x00;
|
||||
TCCR2B = 0x00; // Stop TIMER2
|
||||
cli();
|
||||
|
||||
no_of_ticks += TCNT1;
|
||||
no_of_ticks += TCNT2;
|
||||
|
||||
return (uint16_t)(no_of_ticks / (CYCLES_PER_US * 58));
|
||||
}
|
||||
|
||||
ISR(TIMER1_OVF_vect)
|
||||
ISR(TIMER2_OVF_vect)
|
||||
{
|
||||
no_of_ticks += TIMER_MAX;
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user