Advertisement
JustinCase2020

Arduino Range Sensor

Jun 7th, 2020
197
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.98 KB | None | 0 0
  1.  
  2. #include "Arduino.h"
  3.  
  4. #define RING_BUFFER_SIZE        16
  5.  
  6. volatile bool       SampleTime;
  7. volatile bool       SampleComplete;
  8. volatile uint16_t   EchoLength;
  9. volatile bool       EchoRX;
  10.  
  11. uint16_t ringBuffer[RING_BUFFER_SIZE];
  12. uint32_t ringBufferTally;
  13. uint8_t ringBufferIndex;
  14.  
  15. ISR(INT0_vect)
  16. {
  17.     if (EchoRX)
  18.     {
  19.         EchoLength = TCNT1;
  20.         SampleComplete = true;
  21.         TCCR1B = 0x00;
  22.         EICRA = (1 << ISC00) | (1 << ISC01); // Rising edge
  23.         EchoRX = false;
  24.     }
  25.     else
  26.     {
  27.         EICRA = (1 << ISC01); // Falling edge
  28.         TCNT1 = 0;
  29.         TCCR1B = 0x02;
  30.         EchoRX = true;
  31.     }
  32. }
  33.  
  34. void Trigger()
  35. {
  36.     PORTB |= (1 << PORTB2);
  37.     _delay_us(10);
  38.     PORTB &= ~(1 << PORTB2);
  39. }
  40.  
  41. void SampleCompleteHandler()
  42. {
  43.     uint16_t Distance;
  44.     uint16_t tmp;
  45.  
  46.     SampleComplete = false;
  47.  
  48.     ringBufferTally -= ringBuffer[ringBufferIndex];
  49.     ringBufferTally += EchoLength;
  50.     ringBuffer[ringBufferIndex] = EchoLength;
  51.     ringBufferIndex++;
  52.     ringBufferIndex &= (RING_BUFFER_SIZE - 1);
  53.  
  54.     tmp = ringBufferTally / RING_BUFFER_SIZE;
  55.  
  56.     // 331.6 + (0.606 * n°) = 346.75 m/s @ 25°C
  57.     Distance = (uint16_t)(tmp * ((((1.0 / (F_CPU / 8))) * 347L) * 500.0));
  58.  
  59.     Serial.println(Distance);
  60.        
  61.     SampleTime = true;
  62. }
  63.  
  64. void SampleTimeHandler()
  65. {
  66.     SampleTime = false;
  67.     Trigger();
  68. }
  69.  
  70. void setup()
  71. {
  72.     // Trigger
  73.     DDRB |= (1 << DDB2);
  74.     PORTB &= ~(1 << PORTB2);
  75.  
  76.     // Echo
  77.     DDRD        &= ~(1 << DDD2);                // INT0
  78.     PORTD       &= ~(1 << PORTD2);
  79.     EICRA       = (1 << ISC00) | (1 << ISC01); // Rising edge
  80.     EIMSK       = (1 << INT0);
  81.  
  82.     TCCR1A = 0x00;
  83.     TCCR1B = 0x00;      // 0x02 = 1:8, 0x03 = 1:64, 0x04 = 1:256, 0x05 = 1:1024
  84.  
  85.     EchoRX = false;
  86.     SampleTime = true;
  87.  
  88.     Serial.begin(115200);
  89.  
  90.     sei();
  91. }
  92.  
  93. void loop()
  94. {
  95.     if (SampleTime)
  96.         SampleTimeHandler();
  97.  
  98.     if (SampleComplete)
  99.         SampleCompleteHandler();
  100. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement