4
// Testing reading from the receiver. We're expecting a PWM signal, on
5
// interrupt 0 (which is pin 2 on an Arduino Uno).
7
// This program tries to measure the width of the signal pulses in
8
// microseconds. It takes several measurements and prints it the average over
13
// number of signal pulses to average
14
#define SIGNAL_SAMPLES 10
17
// set to the time that the last signal pulse was at
18
static unsigned long _new_pulse_on = 0;
19
static unsigned long _new_pulse_off = 0;
22
// ISR to handle the PWM signal
26
if( digitalRead( 2 ) )
27
_new_pulse_on = micros();
29
_new_pulse_off = micros();
35
// set up an interrupt handler on pin 2
36
attachInterrupt( 0, signal_handler, CHANGE );
37
digitalWrite( 2, LOW );
44
unsigned long last_pulse = 0;
45
unsigned long intervals[ SIGNAL_SAMPLES ] = {0};
50
// detect pulse falling-edge
51
unsigned long new_pulse_on = _new_pulse_on;
52
unsigned long new_pulse_off = _new_pulse_off;
53
bool got_pulse = false;
54
if( new_pulse_off > last_pulse )
56
// update interval buffer
57
intervals[ interval_idx ] = new_pulse_off - new_pulse_on;
58
if( ++interval_idx >= SIGNAL_SAMPLES )
61
last_pulse = new_pulse_off;
66
if( interval_idx == 0 && got_pulse )
70
for( int a = 0; a < SIGNAL_SAMPLES; a++ )
71
ave += intervals[ a ];
72
ave /= SIGNAL_SAMPLES;
75
Serial.println( round( ave ) );