Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include "Arduino.h"
- #define RING_BUFFER_SIZE 16
- volatile bool SampleTime;
- volatile bool SampleComplete;
- volatile uint16_t EchoLength;
- volatile bool EchoRX;
- uint16_t ringBuffer[RING_BUFFER_SIZE];
- uint32_t ringBufferTally;
- uint8_t ringBufferIndex;
- ISR(INT0_vect)
- {
- if (EchoRX)
- {
- EchoLength = TCNT1;
- SampleComplete = true;
- TCCR1B = 0x00;
- EICRA = (1 << ISC00) | (1 << ISC01); // Rising edge
- EchoRX = false;
- }
- else
- {
- EICRA = (1 << ISC01); // Falling edge
- TCNT1 = 0;
- TCCR1B = 0x02;
- EchoRX = true;
- }
- }
- void Trigger()
- {
- PORTB |= (1 << PORTB2);
- _delay_us(10);
- PORTB &= ~(1 << PORTB2);
- }
- void SampleCompleteHandler()
- {
- uint16_t Distance;
- uint16_t tmp;
- SampleComplete = false;
- ringBufferTally -= ringBuffer[ringBufferIndex];
- ringBufferTally += EchoLength;
- ringBuffer[ringBufferIndex] = EchoLength;
- ringBufferIndex++;
- ringBufferIndex &= (RING_BUFFER_SIZE - 1);
- tmp = ringBufferTally / RING_BUFFER_SIZE;
- // 331.6 + (0.606 * n°) = 346.75 m/s @ 25°C
- Distance = (uint16_t)(tmp * ((((1.0 / (F_CPU / 8))) * 347L) * 500.0));
- Serial.println(Distance);
- SampleTime = true;
- }
- void SampleTimeHandler()
- {
- SampleTime = false;
- Trigger();
- }
- void setup()
- {
- // Trigger
- DDRB |= (1 << DDB2);
- PORTB &= ~(1 << PORTB2);
- // Echo
- DDRD &= ~(1 << DDD2); // INT0
- PORTD &= ~(1 << PORTD2);
- EICRA = (1 << ISC00) | (1 << ISC01); // Rising edge
- EIMSK = (1 << INT0);
- TCCR1A = 0x00;
- TCCR1B = 0x00; // 0x02 = 1:8, 0x03 = 1:64, 0x04 = 1:256, 0x05 = 1:1024
- EchoRX = false;
- SampleTime = true;
- Serial.begin(115200);
- sei();
- }
- void loop()
- {
- if (SampleTime)
- SampleTimeHandler();
- if (SampleComplete)
- SampleCompleteHandler();
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement