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
79
80
81
82
83
84
85
86
|
//
// 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 frequency of the signal pulses in
// microseconds. It takes several measurements and prints out 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 volatile unsigned long _new_pulse_at = 0;
// ISR to handle the PWM signal
void signal_handler()
{
// record time
_new_pulse_at = micros();
}
void setup()
{
Serial.begin( 9600 );
// set up an interrupt handler on pin 2
attachInterrupt( 0, signal_handler, RISING );
}
void loop()
{
unsigned long last_pulse = 0;
unsigned long intervals[ SIGNAL_SAMPLES ] = {0};
int interval_idx = 0;
while( true )
{
// detect pulse
unsigned long new_pulse = _new_pulse_at;
bool got_pulse = false;
if( new_pulse < last_pulse )
last_pulse = new_pulse;
if( new_pulse > last_pulse )
{
// check interval
unsigned long interval = new_pulse - last_pulse;
if( false && interval < 300 )
{
Serial.print( "[" );
Serial.print( last_pulse );
Serial.print( "," );
Serial.print( new_pulse );
Serial.print( "]" );
}
// if( interval > 19000 && interval < 20500 )
// {
// update interval buffer
intervals[ interval_idx ] = interval;
if( ++interval_idx >= SIGNAL_SAMPLES )
interval_idx = 0;
got_pulse = true;
// }
last_pulse = new_pulse;
}
// display average?
if( interval_idx == 0 && got_pulse )
{
// calculate average
long interval = 0;
for( int a = 0; a < SIGNAL_SAMPLES; a++ )
interval += intervals[ a ];
Serial.print( intervals[ 0 ] );
Serial.println();
}
}
}
|