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 width of the signal pulses in |
|
8 |
// microseconds. It takes several measurements and prints it the average over |
|
9 |
// serial. |
|
10 |
// |
|
11 |
||
12 |
||
13 |
// number of signal pulses to average |
|
14 |
#define SIGNAL_SAMPLES 10 |
|
15 |
||
16 |
||
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; |
|
20 |
||
21 |
||
22 |
// ISR to handle the PWM signal |
|
23 |
void signal_handler() |
|
24 |
{ |
|
25 |
// record time |
|
26 |
if( digitalRead( 2 ) ) |
|
27 |
_new_pulse_on = micros(); |
|
28 |
else |
|
29 |
_new_pulse_off = micros(); |
|
30 |
} |
|
31 |
||
32 |
||
33 |
void setup() |
|
34 |
{ |
|
35 |
// set up an interrupt handler on pin 2 |
|
36 |
attachInterrupt( 0, signal_handler, CHANGE ); |
|
37 |
digitalWrite( 2, LOW ); |
|
38 |
||
39 |
Serial.begin( 9600 ); |
|
40 |
} |
|
41 |
||
42 |
void loop() |
|
43 |
{ |
|
44 |
unsigned long last_pulse = 0; |
|
45 |
unsigned long intervals[ SIGNAL_SAMPLES ] = {0}; |
|
46 |
int interval_idx = 0; |
|
47 |
||
48 |
while( true ) |
|
49 |
{ |
|
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 ) |
|
55 |
{ |
|
56 |
// update interval buffer |
|
57 |
intervals[ interval_idx ] = new_pulse_off - new_pulse_on; |
|
58 |
if( ++interval_idx >= SIGNAL_SAMPLES ) |
|
59 |
interval_idx = 0; |
|
60 |
||
61 |
last_pulse = new_pulse_off; |
|
62 |
got_pulse = true; |
|
63 |
} |
|
64 |
||
65 |
// display average? |
|
66 |
if( interval_idx == 0 && got_pulse ) |
|
67 |
{ |
|
68 |
// calculate average |
|
69 |
double ave = 0; |
|
70 |
for( int a = 0; a < SIGNAL_SAMPLES; a++ ) |
|
71 |
ave += intervals[ a ]; |
|
72 |
ave /= SIGNAL_SAMPLES; |
|
73 |
||
74 |
// tell it like it is |
|
75 |
Serial.println( round( ave ) ); |
|
76 |
} |
|
77 |
} |
|
78 |
} |