bzr branch
http://bzr.ed.am/elec/quadcopter
1
by Tim Marston
initial commit, and a couple of receiver test programs |
1 |
// |
2 |
// main.ino |
|
3 |
// |
|
4 |
// Testing reading from the receiver. We're expecting a PWM signal, on |
|
5 |
// interrupt 0 (which is pin 2 on an Arduino Uno). |
|
6 |
// |
|
7 |
// This program tries to measure the frequency of the signal pulses in |
|
8 |
// microseconds. It takes several measurements and prints out the average over |
|
9 |
// serial. |
|
10 |
// |
|
11 |
||
12 |
// number of signal pulses to average |
|
13 |
#define SIGNAL_SAMPLES 10 |
|
14 |
||
15 |
||
16 |
// set to the time that the last signal pulse was at |
|
17 |
static volatile unsigned long _new_pulse_at = 0; |
|
18 |
||
19 |
||
20 |
// ISR to handle the PWM signal |
|
21 |
void signal_handler() |
|
22 |
{ |
|
23 |
// record time |
|
24 |
_new_pulse_at = micros(); |
|
25 |
} |
|
26 |
||
27 |
||
28 |
void setup() |
|
29 |
{ |
|
30 |
Serial.begin( 9600 ); |
|
31 |
||
32 |
// set up an interrupt handler on pin 2 |
|
33 |
attachInterrupt( 0, signal_handler, RISING ); |
|
34 |
} |
|
35 |
||
36 |
void loop() |
|
37 |
{ |
|
38 |
unsigned long last_pulse = 0; |
|
39 |
unsigned long intervals[ SIGNAL_SAMPLES ] = {0}; |
|
40 |
int interval_idx = 0; |
|
41 |
||
42 |
while( true ) |
|
43 |
{ |
|
44 |
// detect pulse |
|
45 |
unsigned long new_pulse = _new_pulse_at; |
|
46 |
bool got_pulse = false; |
|
47 |
if( new_pulse < last_pulse ) |
|
48 |
last_pulse = new_pulse; |
|
49 |
if( new_pulse > last_pulse ) |
|
50 |
{ |
|
51 |
// check interval |
|
52 |
unsigned long interval = new_pulse - last_pulse; |
|
53 |
if( interval < 300 ) |
|
54 |
{ |
|
55 |
Serial.print( "[" ); |
|
56 |
Serial.print( last_pulse ); |
|
57 |
Serial.print( "," ); |
|
58 |
Serial.print( new_pulse ); |
|
59 |
Serial.print( "]" ); |
|
60 |
} |
|
61 |
// if( interval > 19000 && interval < 20500 ) |
|
62 |
// { |
|
63 |
// update interval buffer |
|
64 |
intervals[ interval_idx ] = interval; |
|
65 |
if( ++interval_idx >= SIGNAL_SAMPLES ) |
|
66 |
interval_idx = 0; |
|
67 |
||
68 |
got_pulse = true; |
|
69 |
// } |
|
70 |
||
71 |
last_pulse = new_pulse; |
|
72 |
} |
|
73 |
||
74 |
// display average? |
|
75 |
if( interval_idx == 0 && got_pulse ) |
|
76 |
{ |
|
77 |
// calculate average |
|
78 |
for( int a = 0; a < SIGNAL_SAMPLES; a++ ) { |
|
79 |
Serial.print( intervals[ a ] ); |
|
80 |
if( a == SIGNAL_SAMPLES - 1 ) |
|
81 |
Serial.println(); |
|
82 |
else |
|
83 |
Serial.print( " " ); |
|
84 |
} |
|
85 |
} |
|
86 |
} |
|
87 |
} |