Use TIMER2 for sonar interrupts

This commit is contained in:
Rihards Skuja 2018-01-23 23:23:18 +02:00
parent 1633d3e78d
commit 9f6e90f27f
No known key found for this signature in database
GPG Key ID: 53FA13A3F7F8571B
2 changed files with 9 additions and 10 deletions

View File

@ -17,9 +17,9 @@
#define SPEED_OF_SOUND 343 // 20°C dry air (m/s) #define SPEED_OF_SOUND 343 // 20°C dry air (m/s)
#define MAX_SONAR_RANGE 8 // Trigger + echo (m) #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 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 CYCLES_PER_US (F_CPU / 1000000)
#define SONAR_TIMEOUT (F_CPU * MAX_SONAR_RANGE) / SPEED_OF_SOUND #define SONAR_TIMEOUT (F_CPU * MAX_SONAR_RANGE) / SPEED_OF_SOUND

View File

@ -1,7 +1,6 @@
#include <avr/interrupt.h> #include <avr/interrupt.h>
#include <util/delay.h> #include <util/delay.h>
#include "sonar.h" #include "sonar.h"
#include "led.h"
volatile uint32_t trig_counter; volatile uint32_t trig_counter;
volatile uint32_t no_of_ticks; volatile uint32_t no_of_ticks;
@ -27,27 +26,27 @@ int32_t read_sonar(void)
} }
} }
TCNT1 = 0; TCNT2 = 0;
SET(TCCR1B, CS10); // Prescaler = 1 SET(TCCR2B, CS20); // Prescaler = 1
SET(TIMSK1, TOIE1); // Enable overflow interrupts SET(TIMSK2, TOIE2); // Enable overflow interrupts
no_of_ticks = 0; // Reset overflow counter no_of_ticks = 0; // Reset overflow counter
sei(); sei();
// Count cycles until ECHO goes low // Count cycles until ECHO goes low
while (CHK(ECHO_PIN, ECHO_BIT)) { while (CHK(ECHO_PIN, ECHO_BIT)) {
if (no_of_ticks + TCNT1 > SONAR_TIMEOUT) { if (no_of_ticks + TCNT2 > SONAR_TIMEOUT) {
return ECHO_TIMEOUT; return ECHO_TIMEOUT;
} }
} }
TCCR1B = 0x00; TCCR2B = 0x00; // Stop TIMER2
cli(); cli();
no_of_ticks += TCNT1; no_of_ticks += TCNT2;
return (uint16_t)(no_of_ticks / (CYCLES_PER_US * 58)); return (uint16_t)(no_of_ticks / (CYCLES_PER_US * 58));
} }
ISR(TIMER1_OVF_vect) ISR(TIMER2_OVF_vect)
{ {
no_of_ticks += TIMER_MAX; no_of_ticks += TIMER_MAX;
} }