1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
|
//
// main.ino
//
// Testing reading from the receiver. We're expecting a PWM signal, on
// interrupt 0 (which is pin 2 on an Arduino Uno).
//
// This program tries to measure the width of the signal pulses in
// microseconds. It takes several measurements and prints it the average over
// serial.
//
// number of signal pulses to average
#define SIGNAL_SAMPLES 10
// set to the time that the last signal pulse was at
static unsigned long _new_pulse_on = 0;
static unsigned long _new_pulse_off = 0;
// ISR to handle the PWM signal
void signal_handler()
{
// record time
if( digitalRead( 2 ) )
_new_pulse_on = micros();
else
_new_pulse_off = micros();
}
void setup()
{
// set up an interrupt handler on pin 2
attachInterrupt( 0, signal_handler, CHANGE );
digitalWrite( 2, LOW );
Serial.begin( 9600 );
}
void loop()
{
unsigned long last_pulse = 0;
unsigned long intervals[ SIGNAL_SAMPLES ] = {0};
int interval_idx = 0;
while( true )
{
// detect pulse falling-edge
unsigned long new_pulse_on = _new_pulse_on;
unsigned long new_pulse_off = _new_pulse_off;
bool got_pulse = false;
if( new_pulse_off > last_pulse )
{
// update interval buffer
intervals[ interval_idx ] = new_pulse_off - new_pulse_on;
if( ++interval_idx >= SIGNAL_SAMPLES )
interval_idx = 0;
last_pulse = new_pulse_off;
got_pulse = true;
}
// display average?
if( interval_idx == 0 && got_pulse )
{
// calculate average
double ave = 0;
for( int a = 0; a < SIGNAL_SAMPLES; a++ )
ave += intervals[ a ];
ave /= SIGNAL_SAMPLES;
// tell it like it is
Serial.println( round( ave ) );
}
}
}
|