diff --git a/robot/include/sonar.h b/robot/include/sonar.h index b8ad087..ef4227f 100644 --- a/robot/include/sonar.h +++ b/robot/include/sonar.h @@ -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 diff --git a/robot/src/sonar.c b/robot/src/sonar.c index 8db9d31..26c58fa 100644 --- a/robot/src/sonar.c +++ b/robot/src/sonar.c @@ -1,7 +1,6 @@ #include #include #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; }