/elec/quadcopter

To get this branch, use:
bzr branch http://bzr.ed.am/elec/quadcopter
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
//
// 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 (for damping)
#define DAMPING_SAMPLES 1


// 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_off = 0;
	unsigned long intervals[ DAMPING_SAMPLES ] = {0};
	int interval_idx = 0;

	while( true )
	{
		// detect pulse falling-edge
		unsigned long pulse_on = _new_pulse_on;
		unsigned long pulse_off = _new_pulse_off;
		bool got_pulse = false;
		if( pulse_off > last_pulse_off )
		{
			// sanity check
			unsigned long interval = pulse_off - pulse_on;
			if( interval > 800 && interval < 3000 )
			{
				// update interval buffer
				intervals[ interval_idx ] = pulse_off - pulse_on;
				if( ++interval_idx >= DAMPING_SAMPLES )
					interval_idx = 0;

				got_pulse = true;
			}

			last_pulse_off = pulse_off;
		}

		// display average?
		if( got_pulse )
		{
			// calculate average
			unsigned long ave = 0;
			for( int a = 0; a < DAMPING_SAMPLES; a++ )
				ave += intervals[ a ];
			ave /= DAMPING_SAMPLES;

			// tell it like it is
			Serial.print( ave );
			Serial.print( "\r\n" );
		}		
	}
}