interrupt.ino 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. // This function does low-lovel setups to achieve a call to an interrupts function every 20uS
  2. void setup_timer_interrupt()
  3. {
  4. //set timer1 interrupt at 10Hz
  5. TCCR1A = 0;// set entire TCCR1A register to 0
  6. TCCR1B = 0;// same for TCCR1B
  7. TCNT1 = 0;//initialize counter value to 0
  8. // set compare match register for 1hz increments
  9. // OCR1A = 40. This results is 16MHz / 8 / 40 = 20 uS between interrupts
  10. OCR1A = 40;
  11. // turn on CTC mode
  12. TCCR1B |= (1 << WGM12);
  13. // Set CS12:CS10 to 010 = /8 prescaler
  14. TCCR1B |= (1 << CS11);
  15. // enable timer compare interrupt
  16. TIMSK1 |= (1 << OCIE1A);
  17. }
  18. // 20uS timer interrupt function
  19. // 48810 int/sec = 20.487605 uS
  20. ISR(TIMER1_COMPA_vect, ISR_NOBLOCK) {
  21. static unsigned char currValue = 0;
  22. static unsigned short samples = 0;
  23. static unsigned short newSamples = 0;
  24. // Sample the pin value
  25. unsigned char value = digitalRead(rxPinA);
  26. if ( value == currValue ) {
  27. samples++;
  28. samples += newSamples;
  29. newSamples = 0;
  30. }
  31. else {
  32. newSamples++;
  33. }
  34. // We wait until we have sampled 3 equal states before actually accepting that we have received a new pulse
  35. if ( newSamples == 3 ) {
  36. uint16_t queSamples = (uint16_t)((samples * 20 > 60000) ? 60000 : samples * 20); // Calc the time in uS
  37. rcvEnQueue(queSamples); // Send the received pulse to the queue. Max 46000
  38. samples = newSamples;
  39. newSamples = 0;
  40. currValue = value;
  41. }
  42. }