]> git.defcon.no Git - rctxduino/blob - source/RCTXDuino/RCTXDuino.pde
a6769d68098f31912370690d83dc3bda6ce671af
[rctxduino] / source / RCTXDuino / RCTXDuino.pde
1 #include <LiquidCrystal.h>
2 #include <TimerOne.h>
3 #include <EEPROM.h>
4
5 // Undefine this whenever a "release" or "flight-test" build is made.
6 // Defining DEBUG sets some crazy values for things like battery warning,
7 // and includes a whole bunch of debugging-related code ...
8 #define DEBUG 1
9
10 #define MAX_INPUTS 8
11
12 // Update this _every_ time a change in datastructures that
13 // can/will ber written to EEPROM is done. EEPROM data is
14 // read/written torectly into/from the data structures using
15 // pointers, so every time a data-set change occurs, the EEPROM
16 // format changes as well..
17 #define EEPROM_VERSION 7
18
19 // Some data is stored in fixed locations, e.g.:
20 // * The EEPROM version number for the stored data (loc 0)
21 // * The selected model configuration number (loc 1)
22 // * (add any other fixed-loc's here for doc-purpose)
23 // This means that any pointer-math-operations need a BASE
24 // adress to start calc'ing from. This is defined as:
25 #define EE_BASE_ADDR 10
26
27 // Having to repeat tedious base-address-calculations for the
28 // start of model data should be unnessecary. Plus, updating
29 // what data is stored before the models will mean that each
30 // of those calculations must be updated. A better approach is
31 // to define the calculation in a define!
32 // NOTE: If new data is added in front of the model data,
33 // this define must be updated!
34 #define EE_MDL_BASE_ADDR (EE_BASE_ADDR+(sizeof(input_cal_t)+ 10))
35
36 // Just as a safety-precaution, update/change this if a chip with
37 // a different internal EEPROM size is used. Atmega328p has 1024 bytes.
38 #define INT_EEPROM_SIZE 1024
39
40 #define MAX_MODELS 4 // Nice and random number..
41
42
43 // --------------- ADC related stuffs.... --------------------
44
45 struct input_cal_t // Struct type for input calibration values
46 {
47 int min[MAX_INPUTS];
48 int max[MAX_INPUTS];
49 int center[MAX_INPUTS];
50 } ;
51 input_cal_t input_cal;
52
53 struct model_t
54 {
55 int channels; // How many channels should PPM generate for this model ...
56 float stick[8]; // The (potentially recalc'ed) value of stick/input channel.
57 int raw[8];
58 boolean rev[8];
59 int dr[8]; // The Dual-rate array uses magic numbers :P
60 /* dr[0] = Input channel #1 of 2 for D/R switch #1. 0 means off, 1-4 valid values.
61 dr[1] = Input channel #2 of 2 for D/R switch #1. 0 means off, 1-4 valid values.
62 dr[2] = Input channel #1 of 2 for D/R switch #2. 0 means off, 1-4 valid values.
63 dr[3] = Input channel #2 of 2 for D/R switch #2. 0 means off, 1-4 valid values.
64 dr[4] = D/R value for switch # 1 LOW(off). Value -100 to 100 in steps of 5.
65 dr[5] = D/R value for switch # 1 HIGH(on). Value -100 to 100 in steps of 5.
66 dr[6] = D/R value for switch # 1 LOW(off). Value -100 to 100 in steps of 5.
67 dr[7] = D/R value for switch # 1 HIGH(on). Value -100 to 100 in steps of 5.
68 */
69 };
70 volatile model_t model;
71 unsigned char current_model; // Using uchar to spend a single byte of mem..
72
73 // ----------------- Display related stuffs --------------------
74 LiquidCrystal lcd( 12, 11, 10, 6, 7, 8, 9);
75 // Parameters are: rs, rw, enable, d4, d5, d6, d7 pin numbers.
76
77 // ----------------- PPM related stuffs ------------------------
78 // The PPM generation is handled by Timer0 interrupts, and needs
79 // all modifiable variables to be global and volatile...
80
81 volatile long sum = 0; // Frame-time spent so far
82 volatile int cchannel = 0; // Current channnel
83 volatile bool do_channel = true; // Is next operation a channel or a separator
84
85
86 // All time values in usecs
87 // TODO:
88 // The timing here (and/or in the ISR) needs to be tweaked to provide valid
89 // RC PPM signals accepted by standard RC RX'es and the Microcopter...
90
91 #define framelength 21000 // Max length of frame
92 #define seplength 300 // Lenght of a channel separator
93 #define chmax 1600 // Max lenght of channel pulse
94 #define chmin 495 // Min length of channel
95 #define chwidht (chmax - chmin)// Useable time of channel pulse
96
97 // ----------------- Menu/IU related stuffs --------------------
98
99 // Keys/buttons/switches for UI use, including dual-rate/expo
100 // are digital inputs connected to a 4051 multiplexer, giving
101 // 8 inputs on a single input pin.
102 #define KEY_UP 0
103 #define KEY_DOWN 1
104 #define KEY_RIGHT 2
105 #define KEY_LEFT 3
106 #define KEY_INC 4
107 #define KEY_DEC 5
108 #define KEY_DR1 6
109 #define KEY_DR2 7
110
111 // Voltage sense pin is connected to a 1/3'd voltage divider.
112 #define BATTERY_CONV (10 * 3 * (5.0f/1024.0f))
113
114 #ifdef DEBUG
115 // The following values are for DEBUGGING ONLY!!
116 #define BATTERY_LOW 92
117 #define BATTERY_CRITICAL 0
118 #else
119 #define BATTERY_LOW 92
120 #define BATTERY_CRITICAL 92
121 #endif
122
123 enum {
124 VALUES,
125 BATTERY,
126 TIMER,
127 CURMODEL,
128 MENU
129 }
130 displaystate;
131
132 enum {
133 TOP,
134 INVERTS,
135 DUALRATES,
136 EXPOS, // Some radios have "drawn curves", i.e. loopup tables stored in external EEPROM ...
137 DEBUG_DUMP,
138 SAVE
139 }
140 menu_mainstate;
141 int menu_substate;
142
143 boolean keys[8];
144 boolean prev_keys[8];
145
146 int battery_val;
147
148 // The display/UI is handled only when more
149 // than UI_INTERVAL milliecs has passed since last...
150 #define UI_INTERVAL 250
151 unsigned long last = 0;
152
153 struct clock_timer_t
154 {
155 unsigned long start;
156 unsigned long init;
157 unsigned long value;
158 boolean running;
159 } clock_timer;
160
161 #ifdef DEBUG
162 // ----------------- DEBUG-STUFF --------------------
163 unsigned long prev_loop_time;
164 unsigned long avg_loop_time;
165 unsigned long t;
166 #endif
167 // -----------------------LCD--------------------------
168
169
170 #define PIN_SCE 7 //Pin 3 on LCD
171 #define PIN_RESET 6 //Pin 4 on LCD
172 #define PIN_DC 5 //Pin 5 on LCD
173 #define PIN_SDIN 4 //Pin 6 on LCD
174 #define PIN_SCLK 3 //Pin 7 on LCD
175
176 //The DC pin tells the LCD if we are sending a command or data
177 #define LCD_COMMAND 0
178 #define LCD_DATA 1
179
180 //You may find a different size screen, but this one is 84 by 48 pixels
181 #define LCD_X 84
182 #define LCD_Y 48
183
184 //This table contains the hex values that represent pixels
185 //for a font that is 5 pixels wide and 8 pixels high
186 static const byte ASCII[][5] = {
187 {0x00, 0x00, 0x00, 0x00, 0x00} // 20
188 ,{0x00, 0x00, 0x5f, 0x00, 0x00} // 21 !
189 ,{0x00, 0x07, 0x00, 0x07, 0x00} // 22 "
190 ,{0x14, 0x7f, 0x14, 0x7f, 0x14} // 23 #
191 ,{0x24, 0x2a, 0x7f, 0x2a, 0x12} // 24 $
192 ,{0x23, 0x13, 0x08, 0x64, 0x62} // 25 %
193 ,{0x36, 0x49, 0x55, 0x22, 0x50} // 26 &
194 ,{0x00, 0x05, 0x03, 0x00, 0x00} // 27 '
195 ,{0x00, 0x1c, 0x22, 0x41, 0x00} // 28 (
196 ,{0x00, 0x41, 0x22, 0x1c, 0x00} // 29 )
197 ,{0x14, 0x08, 0x3e, 0x08, 0x14} // 2a *
198 ,{0x08, 0x08, 0x3e, 0x08, 0x08} // 2b +
199 ,{0x00, 0x50, 0x30, 0x00, 0x00} // 2c ,
200 ,{0x08, 0x08, 0x08, 0x08, 0x08} // 2d -
201 ,{0x00, 0x60, 0x60, 0x00, 0x00} // 2e .
202 ,{0x20, 0x10, 0x08, 0x04, 0x02} // 2f /
203 ,{0x3e, 0x51, 0x49, 0x45, 0x3e} // 30 0
204 ,{0x00, 0x42, 0x7f, 0x40, 0x00} // 31 1
205 ,{0x42, 0x61, 0x51, 0x49, 0x46} // 32 2
206 ,{0x21, 0x41, 0x45, 0x4b, 0x31} // 33 3
207 ,{0x18, 0x14, 0x12, 0x7f, 0x10} // 34 4
208 ,{0x27, 0x45, 0x45, 0x45, 0x39} // 35 5
209 ,{0x3c, 0x4a, 0x49, 0x49, 0x30} // 36 6
210 ,{0x01, 0x71, 0x09, 0x05, 0x03} // 37 7
211 ,{0x36, 0x49, 0x49, 0x49, 0x36} // 38 8
212 ,{0x06, 0x49, 0x49, 0x29, 0x1e} // 39 9
213 ,{0x00, 0x36, 0x36, 0x00, 0x00} // 3a :
214 ,{0x00, 0x56, 0x36, 0x00, 0x00} // 3b ;
215 ,{0x08, 0x14, 0x22, 0x41, 0x00} // 3c <
216 ,{0x14, 0x14, 0x14, 0x14, 0x14} // 3d =
217 ,{0x00, 0x41, 0x22, 0x14, 0x08} // 3e >
218 ,{0x02, 0x01, 0x51, 0x09, 0x06} // 3f ?
219 ,{0x32, 0x49, 0x79, 0x41, 0x3e} // 40 @
220 ,{0x7e, 0x11, 0x11, 0x11, 0x7e} // 41 A
221 ,{0x7f, 0x49, 0x49, 0x49, 0x36} // 42 B
222 ,{0x3e, 0x41, 0x41, 0x41, 0x22} // 43 C
223 ,{0x7f, 0x41, 0x41, 0x22, 0x1c} // 44 D
224 ,{0x7f, 0x49, 0x49, 0x49, 0x41} // 45 E
225 ,{0x7f, 0x09, 0x09, 0x09, 0x01} // 46 F
226 ,{0x3e, 0x41, 0x49, 0x49, 0x7a} // 47 G
227 ,{0x7f, 0x08, 0x08, 0x08, 0x7f} // 48 H
228 ,{0x00, 0x41, 0x7f, 0x41, 0x00} // 49 I
229 ,{0x20, 0x40, 0x41, 0x3f, 0x01} // 4a J
230 ,{0x7f, 0x08, 0x14, 0x22, 0x41} // 4b K
231 ,{0x7f, 0x40, 0x40, 0x40, 0x40} // 4c L
232 ,{0x7f, 0x02, 0x0c, 0x02, 0x7f} // 4d M
233 ,{0x7f, 0x04, 0x08, 0x10, 0x7f} // 4e N
234 ,{0x3e, 0x41, 0x41, 0x41, 0x3e} // 4f O
235 ,{0x7f, 0x09, 0x09, 0x09, 0x06} // 50 P
236 ,{0x3e, 0x41, 0x51, 0x21, 0x5e} // 51 Q
237 ,{0x7f, 0x09, 0x19, 0x29, 0x46} // 52 R
238 ,{0x46, 0x49, 0x49, 0x49, 0x31} // 53 S
239 ,{0x01, 0x01, 0x7f, 0x01, 0x01} // 54 T
240 ,{0x3f, 0x40, 0x40, 0x40, 0x3f} // 55 U
241 ,{0x1f, 0x20, 0x40, 0x20, 0x1f} // 56 V
242 ,{0x3f, 0x40, 0x38, 0x40, 0x3f} // 57 W
243 ,{0x63, 0x14, 0x08, 0x14, 0x63} // 58 X
244 ,{0x07, 0x08, 0x70, 0x08, 0x07} // 59 Y
245 ,{0x61, 0x51, 0x49, 0x45, 0x43} // 5a Z
246 ,{0x00, 0x7f, 0x41, 0x41, 0x00} // 5b [
247 ,{0x02, 0x04, 0x08, 0x10, 0x20} // 5c \
248 ,{0x00, 0x41, 0x41, 0x7f, 0x00} // 5d ]
249 ,{0x04, 0x02, 0x01, 0x02, 0x04} // 5e ^
250 ,{0x40, 0x40, 0x40, 0x40, 0x40} // 5f _
251 ,{0x00, 0x01, 0x02, 0x04, 0x00} // 60 `
252 ,{0x20, 0x54, 0x54, 0x54, 0x78} // 61 a
253 ,{0x7f, 0x48, 0x44, 0x44, 0x38} // 62 b
254 ,{0x38, 0x44, 0x44, 0x44, 0x20} // 63 c
255 ,{0x38, 0x44, 0x44, 0x48, 0x7f} // 64 d
256 ,{0x38, 0x54, 0x54, 0x54, 0x18} // 65 e
257 ,{0x08, 0x7e, 0x09, 0x01, 0x02} // 66 f
258 ,{0x0c, 0x52, 0x52, 0x52, 0x3e} // 67 g
259 ,{0x7f, 0x08, 0x04, 0x04, 0x78} // 68 h
260 ,{0x00, 0x44, 0x7d, 0x40, 0x00} // 69 i
261 ,{0x20, 0x40, 0x44, 0x3d, 0x00} // 6a j
262 ,{0x7f, 0x10, 0x28, 0x44, 0x00} // 6b k
263 ,{0x00, 0x41, 0x7f, 0x40, 0x00} // 6c l
264 ,{0x7c, 0x04, 0x18, 0x04, 0x78} // 6d m
265 ,{0x7c, 0x08, 0x04, 0x04, 0x78} // 6e n
266 ,{0x38, 0x44, 0x44, 0x44, 0x38} // 6f o
267 ,{0x7c, 0x14, 0x14, 0x14, 0x08} // 70 p
268 ,{0x08, 0x14, 0x14, 0x18, 0x7c} // 71 q
269 ,{0x7c, 0x08, 0x04, 0x04, 0x08} // 72 r
270 ,{0x48, 0x54, 0x54, 0x54, 0x20} // 73 s
271 ,{0x04, 0x3f, 0x44, 0x40, 0x20} // 74 t
272 ,{0x3c, 0x40, 0x40, 0x20, 0x7c} // 75 u
273 ,{0x1c, 0x20, 0x40, 0x20, 0x1c} // 76 v
274 ,{0x3c, 0x40, 0x30, 0x40, 0x3c} // 77 w
275 ,{0x44, 0x28, 0x10, 0x28, 0x44} // 78 x
276 ,{0x0c, 0x50, 0x50, 0x50, 0x3c} // 79 y
277 ,{0x44, 0x64, 0x54, 0x4c, 0x44} // 7a z
278 ,{0x00, 0x08, 0x36, 0x41, 0x00} // 7b {
279 ,{0x00, 0x00, 0x7f, 0x00, 0x00} // 7c |
280 ,{0x00, 0x41, 0x36, 0x08, 0x00} // 7d }
281 ,{0x10, 0x08, 0x08, 0x10, 0x08} // 7e ~
282 ,{0x78, 0x46, 0x41, 0x46, 0x78} // 7f DEL
283 };
284
285
286
287
288
289
290
291
292 // ---------- CODE! -----------------------------------
293
294 // ---------- Arduino SETUP code ----------------------
295 void setup(){
296 pinMode(13, OUTPUT); // led
297
298 pinMode(2, OUTPUT); // s0
299 pinMode(3, OUTPUT); // s1
300 pinMode(4, OUTPUT); // s2
301 pinMode(5, OUTPUT); // e
302
303 lcd.begin(16,2);
304 lcd.print("Starting....");
305
306 Serial.begin(9600);
307 Serial.println("Starting....");
308 delay(500);
309
310 model_defaults();
311 read_settings();
312
313 displaystate = VALUES;
314
315 // Arduino believes all pins on Port C are Analog.
316 // In reality they are tri-purpose; ADC, Digital, Digital Interrupts
317 // Unfortunately the interrupt mode is unusable in this scenario, but digital I/O works :P
318 pinMode(A2, INPUT);
319 digitalWrite(A2, HIGH);
320 scan_keys();
321 if ( !keys[KEY_UP])
322 calibrate();
323
324 #ifdef DEBUG
325 // Debugging: how long does the main loop take on avg...
326 t = micros();
327 avg_loop_time = t;
328 prev_loop_time = t;
329 #endif
330
331 // Initializing the stopwatch timer/clock values...
332 clock_timer = (clock_timer_t){0, 0, 0, false};
333
334 pinMode(A5, OUTPUT); // PPM output pin
335 do_channel = false;
336 set_timer( seplength );
337 Timer1.initialize(framelength);
338 Timer1.attachInterrupt(ISR_timer);
339
340 }
341
342 void model_defaults( void )
343 {
344 // This function provides default values for model data
345 // that is not a result of stick input, or in other words:
346 // provides defautls for all user-configurable model options.
347
348 // Remember to update this when a new option/element is added
349 // to the model_t struct (preferably before implementing the
350 // menu code that sets those options ...)
351
352 // This is used when a user wants a new, blank model, a reset
353 // of a configured model, and (most important) when EEPROM
354 // data format changes.
355 // NOTE: This means that stored model conficuration is reset
356 // to defaults when the EEPROM version/format changes.
357 model.channels = 8;
358 model.rev[0] = model.rev[1] = model.rev[2] = model.rev[3] =
359 model.rev[4] = model.rev[5] = model.rev[6] = model.rev[7] = false;
360 model.dr[0] = model.dr[1] = model.dr[2] = model.dr[3] = 0;
361 model.dr[4] = model.dr[5] = model.dr[6] = model.dr[7] = 100;
362
363 }
364
365 // ---------- Arduino main loop -----------------------
366 void loop ()
367 {
368
369 process_inputs();
370
371 // Wasting a full I/O pin on battery status monitoring!
372 battery_val = analogRead(1) * BATTERY_CONV;
373 if ( battery_val < BATTERY_LOW ) {
374 digitalWrite(13, 1); // Simulate alarm :P
375 }
376 if ( battery_val < BATTERY_CRITICAL ) {
377 displaystate = BATTERY;
378 }
379
380 if ( millis() - last > UI_INTERVAL )
381 {
382 last = millis();
383 ui_handler();
384 }
385
386 #ifdef DEBUG
387 if ( displaystate != MENU )
388 {
389 // Debugging: how long does the main loop take on avg,
390 // when not handling the UI...
391 t = micros();
392 avg_loop_time = ( t - prev_loop_time + avg_loop_time ) / 2;
393 prev_loop_time = t;
394 }
395 #endif
396
397 // Whoa! Slow down partner! Let everything settle down before proceeding.
398 delay(5);
399 }
400
401 // ----- Simple support functions used by more complex functions ----
402
403 void set_ppm_output( bool state )
404 {
405 digitalWrite(A5, state); // Hard coded PPM output
406 }
407
408 void set_timer(long time)
409 {
410 Timer1.detachInterrupt();
411 Timer1.attachInterrupt(ISR_timer, time);
412 }
413
414 boolean check_key( int key)
415 {
416 return ( !keys[key] && prev_keys[key] );
417 }
418
419 void mplx_select(int pin)
420 {
421 digitalWrite(5, 1);
422 delayMicroseconds(24);
423
424 digitalWrite(2, bitRead(pin,0)); // Arduino alias for non-modifying bitshift operation
425 digitalWrite(3, bitRead(pin,1)); // us used to extract individual bits from the int (0..7)
426 digitalWrite(4, bitRead(pin,2)); // Select the appropriate input by setting s1,s2,s3 and e
427 digitalWrite(5, 0); // on the 4051 multiplexer.
428
429 // May need to slow the following read down to be able to
430 // get fully reliable values from the 4051 multiplex.
431 delayMicroseconds(24);
432
433 }
434
435 // ----- "Complex" functions follow ---------------------------------
436
437 void calibrate()
438 {
439 int i, adc_in;
440 int num_calibrations = 200;
441
442 lcd.clear();
443 lcd.print("Move controls to");
444 lcd.setCursor(0,1);
445 lcd.print("their extremes..");
446 Serial.print("Calibration. Move all controls to their extremes.");
447
448 for (i=0; i<MAX_INPUTS; i++) {
449 input_cal.min[i] = 1024;
450 input_cal.center[i] = 512;
451 input_cal.max[i] = 0;
452 }
453
454 while ( num_calibrations-- )
455 {
456 for (i=0; i<MAX_INPUTS; i++) {
457 mplx_select(i);
458 adc_in = analogRead(0);
459
460 // Naive min/max calibration
461 if ( adc_in < input_cal.min[i] ) {
462 input_cal.min[i] = adc_in;
463 }
464 if ( adc_in > input_cal.max[i] ) {
465 input_cal.max[i] = adc_in;
466 }
467 delay(10);
468 }
469 }
470
471 // TODO: WILL need to do center-point calibration after min-max...
472
473 lcd.clear();
474 lcd.print("Saving to EEPROM");
475 write_calibration();
476 lcd.setCursor(0 , 1);
477 lcd.print("Done calibrating");
478
479 Serial.print("Done calibrating");
480 delay(2000);
481 }
482
483 void write_calibration(void)
484 {
485 int i;
486 unsigned char v;
487 const byte *p;
488
489 // Set p to be a pointer to the start of the input calibration struct.
490 p = (const byte*)(const void*)&input_cal;
491
492 // Iterate through the bytes of the struct...
493 for (i = 0; i < sizeof(input_cal_t); i++)
494 {
495 // Get a byte of data from the struct...
496 v = (unsigned char) *p;
497 // write it to EEPROM
498 EEPROM.write( EE_BASE_ADDR + i, v);
499 // and move the pointer to the next byte in the struct.
500 *p++;
501 }
502 }
503
504 void read_settings(void)
505 {
506 int i;
507 unsigned char v;
508 byte *p;
509
510 v = EEPROM.read(0);
511 if ( v != EEPROM_VERSION )
512 {
513 // All models have been reset. Set the current model to 0
514 current_model = 0;
515 EEPROM.write(1, current_model);
516
517 calibrate();
518 model_defaults();
519 // The following does not yet work...
520 for ( i = 0; i < MAX_MODELS; i++)
521 write_model_settings(i);
522
523
524 // After saving calibration data and model defaults,
525 // update the saved version-identifier to the current ver.
526 EEPROM.write(0, EEPROM_VERSION);
527 }
528
529 // Read calibration values from EEPROM.
530 // This uses simple pointer-arithmetic and byte-by-byte
531 // to put bytes read from EEPROM to the data-struct.
532 p = (byte*)(void*)&input_cal;
533 for (i = 0; i < sizeof(input_cal_t); i++)
534 *p++ = EEPROM.read( EE_BASE_ADDR + i);
535
536 // Get the previously selected model from EEPROM.
537 current_model = EEPROM.read(1);
538 read_model_settings( current_model );
539 }
540
541 void read_model_settings(unsigned char mod_no)
542 {
543 int model_address;
544 int i;
545 unsigned char v;
546 byte *p;
547
548 // Calculate the EEPROM start adress for the given model (mod_no)
549 model_address = EE_MDL_BASE_ADDR + (mod_no * sizeof(model_t));
550
551 // Do not try to write the model to EEPROM if it won't fit.
552 if ( INT_EEPROM_SIZE < (model_address + sizeof(model_t)) )
553 {
554 lcd.clear();
555 lcd.print("Aborting READ");
556 lcd.setCursor(0 , 1);
557 lcd.print("Invalid location");
558 delay(2000);
559 return;
560 }
561
562 lcd.clear();
563 lcd.print("Reading model ");
564 lcd.print( (int)mod_no );
565
566 // Pointer to the start of the model_t data struct,
567 // used for byte-by-byte reading of data...
568 p = (byte*)(void*)&model;
569 for (i = 0; i < sizeof(model_t); i++)
570 *p++ = EEPROM.read( model_address++ );
571
572 #ifdef DEBUG
573 serial_dump_model();
574 #endif
575
576 lcd.setCursor(0 , 1);
577 lcd.print("... Loaded.");
578 delay(1000);
579 }
580
581 void write_model_settings(unsigned char mod_no)
582 {
583 int model_address;
584 int i;
585 unsigned char v;
586 byte *p;
587
588 // Calculate the EEPROM start adress for the given model (mod_no)
589 model_address = EE_MDL_BASE_ADDR + (mod_no * sizeof(model_t));
590
591 // Do not try to write the model to EEPROM if it won't fit.
592 if ( INT_EEPROM_SIZE < (model_address + sizeof(model_t)) )
593 {
594 lcd.clear();
595 lcd.print("Aborting SAVE");
596 lcd.setCursor(0 , 1);
597 lcd.print("No room for data");
598 delay(2000);
599 return;
600 }
601
602 lcd.clear();
603 lcd.print("Saving model ");
604 lcd.print( (int)mod_no);
605
606 // Pointer to the start of the model_t data struct,
607 // used for byte-by-byte reading of data...
608 p = (byte*)(void*)&model;
609
610 // Write/serialize the model data struct to EEPROM...
611 for (i = 0; i < sizeof(model_t); i++)
612 EEPROM.write( model_address++, *p++);
613
614 lcd.setCursor(0 , 1);
615 lcd.print(".. done saving.");
616 delay(200);
617 }
618
619 #ifdef DEBUG
620 void serial_dump_model ( void )
621 {
622 int i;
623 int model_address;
624 // Calculate the EEPROM start adress for the given model (mod_no)
625 model_address = EE_MDL_BASE_ADDR + (current_model * sizeof(model_t));
626 Serial.print("Current model: ");
627 Serial.println( (int)current_model );
628 Serial.print("Models base addr: ");
629 Serial.println( EE_MDL_BASE_ADDR );
630 Serial.print("Model no: ");
631 Serial.println( current_model, 10 );
632 Serial.print("Size of struct: ");
633 Serial.println( sizeof( model_t) );
634 Serial.print("Model address: ");
635 Serial.println( model_address );
636 Serial.print("End of model: ");
637 Serial.println( model_address + sizeof(model_t) );
638
639 Serial.println();
640
641 Serial.print("Channel reversions: ");
642 for ( i = 0; i<8; i++)
643 {
644 Serial.print(i);
645 Serial.print("=");
646 Serial.print(model.rev[i], 10);
647 Serial.print(" ");
648 }
649 Serial.println();
650
651 Serial.print("DR1 inp 0: ");
652 Serial.println(model.dr[0]);
653 Serial.print("DR1 inp 1: ");
654 Serial.println(model.dr[1]);
655 Serial.print("DR1 LO val: ");
656 Serial.println(model.dr[4]);
657 Serial.print("DR1 HI val: ");
658 Serial.println(model.dr[5]);
659 Serial.print("DR2 inp 0: ");
660 Serial.println(model.dr[2]);
661 Serial.print("DR2 inp 1: ");
662 Serial.println(model.dr[3]);
663 Serial.print("DR2 LO val: ");
664 Serial.println(model.dr[6]);
665 Serial.print("DR2 HI val: ");
666 Serial.println(model.dr[7]);
667
668 for (i=0; i<MAX_INPUTS; i++) {
669 Serial.print("Input #");
670 Serial.print(i);
671 Serial.print(" pct: ");
672 Serial.print(model.stick[i]);
673 Serial.print(" min: ");
674 Serial.print(input_cal.min[i]);
675 Serial.print(" max: ");
676 Serial.print(input_cal.max[i]);
677 Serial.println();
678 }
679 }
680 #endif
681
682 void scan_keys ( void )
683 {
684 boolean key_in;
685
686 // To get more inputs, another 4051 analog multiplexer is used,
687 // but this time it is used for digital inputs. 8 digital inputs
688 // on one input line, as long as proper debouncing and filtering
689 // is done in hardware :P
690 for (int i=0; i<=7; i++) {
691 // To be able to detect that a key has changed state, preserve the previous..
692 prev_keys[i] = keys[i];
693
694 // Select and read input.
695 mplx_select(i);
696 keys[i] = digitalRead(A2);
697 delay(2);
698 }
699 }
700
701
702 void process_inputs(void )
703 {
704 int current_input, adc_in, fact;
705 float min, max;
706
707 for (current_input=0; current_input<MAX_INPUTS; current_input++) {
708
709 mplx_select(current_input);
710 adc_in = analogRead(0);
711
712 model.raw[current_input] = adc_in;
713 // New format on stick values
714 // The calculations happen around the center point, the values
715 // need to arrive at 0...100 of the range "center-to-edge",
716 // and must end up as negative on the ... negative side of center.
717
718 if ( adc_in < input_cal.center[current_input] )
719 {
720 // The stick is on the negative side, so the range is
721 // from the lowest possible value to center, and we must
722 // make this a negative percentage value.
723 max = input_cal.min[current_input];
724 min = input_cal.center[current_input];
725 fact = -100;
726 }
727 else
728 {
729 // The stick is at center, or on the positive side.
730 // Thus, the range is from center to max, and
731 // we need positive percentages.
732 min = input_cal.center[current_input];
733 max = input_cal.max[current_input];
734 fact = 100;
735 }
736 // Calculate the percentage that the current stick position is at
737 // in the given range, referenced to or from center, depending :P
738 model.stick[current_input] = fact * ((float)adc_in - min ) / (max - min);
739
740 // If this input is configured to be reversed, simply do a sign-flip :D
741 if ( model.rev[current_input] ) model.stick[current_input] *= -1;
742
743 // Dual-rate calculation :D
744 // This is very repetitive code. It should be fast, but it may waste code-space.
745 float dr_val;
746 // Test to see if dualrate-switch #1 applies to channel...
747 if ( ( current_input == ( model.dr[0]-1) ) || ( current_input == ( model.dr[1]-1) ) )
748 {
749 if ( !keys[KEY_DR1] )
750 dr_val = ((float)model.dr[4])/100.0;
751 else
752 dr_val = ((float)model.dr[5])/100.0;
753
754 model.stick[current_input] *= dr_val;
755 }
756 else
757 // Test to see if dualrate-switch #1 applies to channel...
758 if ( ( current_input == ( model.dr[2]-1) ) || ( current_input == ( model.dr[3]-1) ) )
759 {
760 if ( !keys[KEY_DR1] )
761 dr_val = ((float)model.dr[6])/100.0;
762 else
763 dr_val = ((float)model.dr[7])/100.0;
764
765 model.stick[current_input] *= dr_val;
766 }
767 }
768 }
769
770
771 void ISR_timer(void)
772 {
773 Timer1.stop(); // Make sure we do not run twice while working :P
774
775 if ( !do_channel )
776 {
777 set_ppm_output( LOW );
778 sum += seplength;
779 do_channel = true;
780 set_timer(seplength);
781 return;
782 }
783
784 if ( cchannel >= model.channels )
785 {
786 set_ppm_output( HIGH );
787 long framesep = framelength - sum;
788
789 sum = 0;
790 do_channel = false;
791 cchannel = 0;
792 set_timer ( framesep );
793 return;
794 }
795
796 if ( do_channel )
797 {
798 set_ppm_output( HIGH );
799
800 // New format on stick values
801 // model.stick contains percentages, -100% to 100% in float. To make the timer-handling
802 // here as simple as possible. We want to calc the channel value as a "ratio-value",
803 // a float in the range 0..1.0. So, by moving the lower bound to 0, then cutting the
804 // range in half, and finally dividing by 100, we should get the ratio value.
805 // Some loss of presicion occurs, perhaps the algo' should be reconsidered :P
806 long next_timer = (( chwidht * ((model.stick[cchannel]+100)/200) ) + chmin);
807 // Do sanity-check of next_timer compared to chmax and chmin...
808 while ( chmax < next_timer ) next_timer--;
809 while ( next_timer < chmin ) next_timer++;
810
811 // Update the sum of elapsed time
812 sum += next_timer;
813
814 // Done with channel separator and value,
815 // prepare for next channel...
816 cchannel++;
817 do_channel = false;
818 set_timer ( next_timer );
819 return;
820 }
821 }
822
823
824 #ifdef DEBUG
825 void serial_debug()
826 {
827 int current_input;
828 for (current_input=0; current_input<MAX_INPUTS; current_input++) {
829
830 Serial.print("Input #");
831 Serial.print(current_input);
832 Serial.print(" pct: ");
833 Serial.print(model.stick[current_input]);
834 Serial.print(" raw value: ");
835 Serial.print(model.raw[current_input]);
836 Serial.print(" min: ");
837 Serial.print(input_cal.min[current_input]);
838 Serial.print(" max: ");
839 Serial.print(input_cal.max[current_input]);
840 Serial.println();
841 }
842 Serial.print("Battery level is: ");
843 Serial.println(battery_val);
844
845 Serial.print("Average loop time:");
846 Serial.println(avg_loop_time);
847
848 Serial.print("Free RAM:");
849 Serial.print( FreeRam() );
850 Serial.println();
851 }
852 #endif
853
854 void dr_inputselect( int no, int in )
855 {
856 if ( model.dr[menu_substate] < 0 ) model.dr[menu_substate] = 4;
857 if ( model.dr[menu_substate] > 4 ) model.dr[menu_substate] = 0;
858
859 lcd.setCursor(0 , 0);
860 lcd.print("D/R switch ");
861 lcd.print( no + 1 );
862 lcd.print(" ");
863 lcd.setCursor(0 , 1);
864 lcd.print("Input ");
865 lcd.print(in+1);
866
867 lcd.print(": ");
868 if ( ! model.dr[menu_substate] ) lcd.print("Off");
869 else lcd.print(model.dr[menu_substate]);
870
871 if ( check_key(KEY_INC) ) {
872 model.dr[menu_substate]++;
873 return;
874 }
875 else if ( check_key(KEY_DEC) ) {
876 model.dr[menu_substate]--;
877 return;
878 }
879 // Wrap around.
880 return;
881
882 }
883
884 void dr_value()
885 {
886 int pos;
887 int state;
888
889 if ( menu_substate == 4) state = keys[KEY_DR1];
890 else state = keys[KEY_DR2];
891
892 pos = 4 + (menu_substate - 4) * 2;
893 if (state) pos++;
894
895 lcd.setCursor(0 , 0);
896 lcd.print("D/R switch ");
897 lcd.print( menu_substate - 3 );
898 lcd.print(" ");
899 lcd.setCursor(0 , 1);
900 lcd.print( state ? "HI" : "LO" );
901 lcd.print(" Value :");
902
903 lcd.print( model.dr[pos] );
904
905 if ( !keys[KEY_INC] ) {
906 if ( model.dr[pos] < 100) model.dr[pos] += 5;
907 return;
908 }
909 else if ( !keys[KEY_DEC] ) {
910 if ( model.dr[pos] > -100) model.dr[pos] -= 5;
911 return;
912 }
913
914 return;
915 }
916 void ui_handler()
917 {
918 int row;
919 int col;
920 scan_keys();
921
922 if ( displaystate != MENU )
923 {
924 menu_substate = 0;
925 if ( check_key(KEY_UP) && displaystate == VALUES ) {
926 displaystate = BATTERY;
927 return;
928 }
929 else if ( check_key(KEY_UP) && displaystate == BATTERY ) {
930 displaystate = TIMER;
931 return;
932 }
933 else if ( check_key(KEY_UP) && displaystate == TIMER ) {
934 displaystate = CURMODEL;
935 return;
936 }
937 else if ( check_key(KEY_UP) && displaystate == CURMODEL ) {
938 displaystate = VALUES;
939 return;
940 }
941
942 else if ( check_key(KEY_DOWN) ) {
943 displaystate = MENU;
944 return;
945 }
946 }
947
948 digitalWrite(13, digitalRead(13) ^ 1 );
949
950 switch ( displaystate )
951 {
952 case VALUES:
953 int current_input;
954 for (current_input=0; current_input<MAX_INPUTS; current_input++) {
955 // In channel value display, do a simple calc
956 // of the LCD row & column location. With 8 channels
957 // we can fit eight channels as percentage values on
958 // a simple 16x2 display...
959 if ( current_input < 4 )
960 {
961 col = current_input * 4;
962 row = 0;
963 }
964 else
965 {
966 col = (current_input-4) * 4;
967 row = 1;
968 }
969 // Overwriting the needed positions with
970 // blanks cause less display-flicker than
971 // actually clearing the display...
972 lcd.setCursor(col, row);
973 lcd.print(" ");
974 lcd.setCursor(col, row);
975 // Display uses percents, while PPM uses ratio....
976 // New format on stick values
977 lcd.print( (int)model.stick[current_input] );
978 }
979 break;
980
981
982 case BATTERY:
983 lcd.clear();
984 lcd.print("Battery level: ");
985 lcd.setCursor(0 , 1);
986 lcd.print( (float)battery_val/10);
987 lcd.print("V");
988 if ( battery_val < BATTERY_LOW ) lcd.print(" - WARNING");
989 else lcd.print(" - OK");
990 break;
991
992
993
994 case TIMER:
995 unsigned long delta;
996 int hours;
997 int minutes;
998 int seconds;
999
1000 lcd.clear();
1001 lcd.print("Timer: ");
1002 lcd.print( clock_timer.running ? "Running" : "Stopped" );
1003 lcd.setCursor(5 , 1);
1004 if ( clock_timer.running )
1005 {
1006 clock_timer.value = millis() - (clock_timer.start + clock_timer.init);
1007 }
1008 hours = ( clock_timer.value / 1000 ) / 3600;
1009 clock_timer.value = clock_timer.value % 3600000;
1010 minutes = ( clock_timer.value / 1000 ) / 60;
1011 seconds = ( clock_timer.value / 1000 ) % 60;
1012 if ( hours ) {
1013 lcd.print(hours);
1014 lcd.print(":");
1015 }
1016 if ( minutes < 10 ) lcd.print("0");
1017 lcd.print( minutes );
1018 lcd.print(":");
1019 if ( seconds < 10 ) lcd.print("0");
1020 lcd.print( seconds );
1021
1022 if ( check_key(KEY_INC) ) {
1023 if ( !clock_timer.running && !clock_timer.start )
1024 {
1025 clock_timer.start = millis();
1026 clock_timer.value = 0;
1027 clock_timer.running = true;
1028 } else if ( !clock_timer.running && clock_timer.start ) {
1029 clock_timer.start = millis() - clock_timer.value;
1030 clock_timer.running = true;
1031 } else if ( clock_timer.running ) {
1032 clock_timer.running = false;
1033 }
1034 return;
1035 } else if ( check_key(KEY_DEC) ) {
1036 if ( !clock_timer.running && clock_timer.start ) {
1037 clock_timer.value = 0;
1038 clock_timer.start = 0;
1039 clock_timer.init = 0;
1040 }
1041 return;
1042 }
1043 break;
1044
1045
1046
1047 case CURMODEL:
1048 lcd.clear();
1049 lcd.print("Model #: ");
1050 lcd.print( (int)current_model );
1051 lcd.setCursor(0 , 1);
1052 lcd.print("NAME (not impl)");
1053 break;
1054
1055
1056
1057 case MENU:
1058 lcd.clear();
1059 switch ( menu_mainstate )
1060 {
1061 case TOP:
1062 lcd.print("In MENU mode!");
1063 lcd.setCursor(0 , 1);
1064 lcd.print("Esc UP. Scrl DN.");
1065 menu_substate = 0;
1066 if ( check_key(KEY_UP) ) {
1067 displaystate = VALUES;
1068 return;
1069 }
1070 else if ( check_key(KEY_DOWN) ) {
1071 menu_mainstate = INVERTS;
1072 return;
1073 }
1074 break;
1075
1076
1077 case INVERTS:
1078 if ( menu_substate >= model.channels ) menu_substate = 0;
1079 if ( menu_substate < 0) menu_substate = (model.channels - 1);
1080 lcd.print("Channel invert");
1081 lcd.setCursor(0 , 1);
1082 lcd.print("Ch ");
1083 lcd.print(menu_substate+1);
1084 lcd.print( (model.rev[menu_substate] ? ": Invert" : ": Normal"));
1085
1086 if ( check_key(KEY_UP) ) {
1087 menu_mainstate = TOP;
1088 return;
1089 }
1090 else if ( check_key(KEY_DOWN) ) {
1091 menu_mainstate = DUALRATES;
1092 return;
1093 }
1094
1095 if ( check_key(KEY_RIGHT) ) {
1096 menu_substate++;
1097 return;
1098 }
1099 else if ( check_key(KEY_LEFT) ) {
1100 menu_substate--;
1101 return;
1102 }
1103 else if ( check_key(KEY_INC) || check_key(KEY_DEC) ) {
1104 model.rev[menu_substate] ^= 1;
1105 return;
1106 }
1107 break;
1108
1109 case DUALRATES:
1110 if ( menu_substate > 5 ) menu_substate = 0;
1111 if ( menu_substate < 0) menu_substate = 5;
1112
1113 if ( check_key(KEY_UP) ) {
1114 menu_mainstate = INVERTS;
1115 return;
1116 }
1117 if ( check_key(KEY_DOWN) ) {
1118 menu_mainstate = EXPOS;
1119 return;
1120 }
1121 if ( check_key(KEY_RIGHT) ) {
1122 menu_substate++;
1123 return;
1124 }
1125 else if ( check_key(KEY_LEFT) ) {
1126 menu_substate--;
1127 return;
1128 }
1129 switch (menu_substate)
1130 {
1131 case 0:
1132 dr_inputselect(0, 0);
1133 return;
1134 case 1:
1135 dr_inputselect(0, 1);
1136 return;
1137 case 2:
1138 dr_inputselect(1, 0);
1139 return;
1140 case 3:
1141 dr_inputselect(1, 1);
1142 return;
1143 case 4:
1144 case 5:
1145 dr_value();
1146 return;
1147 default:
1148 menu_substate = 0;
1149 break;
1150 }
1151 break;
1152
1153 case EXPOS:
1154 //________________
1155 lcd.print("Input expo curve");
1156 lcd.setCursor(0 , 1);
1157 lcd.print("Not implemented");
1158 // Possible, if input values are mapped to +/- 100 rather than 0..1 ..
1159 // plot ( x*(1 - 1.0*cos (x/(20*PI)) )) 0 to 100
1160 // Run in wolfram to see result, adjust the 1.0 factor to inc/red effect.
1161 // Problem: -100 to 100 is terribly bad presicion, esp. considering that
1162 // the values started as 0...1024, and we have 1000usec to "spend" on channels.
1163
1164 // NEW IDEA provided my ivarf @ hig: use bezier curves og hermite curves!
1165 // Looks like a promising idea, but the implementation is still a bitt off
1166 // on the time-horizon :P
1167 if ( check_key(KEY_UP ) ) {
1168 menu_mainstate = DUALRATES;
1169 return;
1170 }
1171 #ifdef DEBUG
1172 if ( check_key(KEY_DOWN ) ) {
1173 menu_mainstate = DEBUG_DUMP;
1174 return;
1175 }
1176 #else
1177 if ( check_key(KEY_DOWN ) ) {
1178 menu_mainstate = TOP;
1179 return;
1180 }
1181
1182 #endif
1183 break;
1184
1185 #ifdef DEBUG
1186 case DEBUG_DUMP:
1187 lcd.setCursor(0 , 0);
1188 lcd.print("Dumping debug to");
1189 lcd.setCursor(0 , 1);
1190 lcd.print("serial port 0");
1191 serial_debug();
1192 if ( check_key(KEY_UP ) ) {
1193 // FIXME: Remember to update the "Scroll up" state!
1194 menu_mainstate = EXPOS;
1195 return;
1196 } else if ( check_key(KEY_DOWN ) ) {
1197 menu_mainstate = SAVE;
1198 return;
1199 }
1200 break;
1201 #endif
1202 default:
1203 lcd.print("Not implemented");
1204 lcd.setCursor(0 , 1);
1205 lcd.print("Press DOWN...");
1206 if ( check_key(KEY_DOWN ) ) menu_mainstate = TOP;
1207 }
1208 break;
1209
1210
1211 default:
1212 // Invalid
1213 return;
1214 }
1215
1216 return;
1217 }
1218
1219 // ----------- LCD related functions ---------------
1220
1221 void LCDgotoXY(int x, int y) {
1222 LCDWrite(0, 0x80 | x); // Column.
1223 LCDWrite(0, 0x40 | y); // Row. ?
1224 }
1225
1226 //This takes a large array of bits and sends them to the LCD
1227 void LCDBitmap(char my_array[]){
1228 for (int index = 0 ; index < (LCD_X * LCD_Y / 8) ; index++)
1229 LCDWrite(LCD_DATA, my_array[index]);
1230 }
1231
1232 //This function takes in a character, looks it up in the font table/array
1233 //And writes it to the screen
1234 //Each character is 8 bits tall and 5 bits wide. We pad one blank column of
1235 //pixels on each side of the character for readability.
1236 void LCDCharacter(char character) {
1237 LCDWrite(LCD_DATA, 0x00); //Blank vertical line padding
1238
1239 for (int index = 0 ; index < 5 ; index++)
1240 LCDWrite(LCD_DATA, ASCII[character - 0x20][index]);
1241 //0x20 is the ASCII character for Space (' '). The font table starts with this character
1242
1243 LCDWrite(LCD_DATA, 0x00); //Blank vertical line padding
1244 }
1245
1246 //Given a string of characters, one by one is passed to the LCD
1247 void LCDString(char *characters) {
1248 while (*characters)
1249 LCDCharacter(*characters++);
1250 }
1251
1252 //Clears the LCD by writing zeros to the entire screen
1253 void LCDClear(void) {
1254 for (int index = 0 ; index < (LCD_X * LCD_Y / 8) ; index++)
1255 LCDWrite(LCD_DATA, 0x00);
1256
1257 LCDgotoXY(0, 0); //After we clear the display, return to the home position
1258 }
1259
1260 //This sends the magical commands to the PCD8544
1261 void LCDInit(void) {
1262
1263 //Configure control pins
1264 pinMode(PIN_SCE, OUTPUT);
1265 pinMode(PIN_RESET, OUTPUT);
1266 pinMode(PIN_DC, OUTPUT);
1267 pinMode(PIN_SDIN, OUTPUT);
1268 pinMode(PIN_SCLK, OUTPUT);
1269
1270 //Reset the LCD to a known state
1271 digitalWrite(PIN_RESET, LOW);
1272 digitalWrite(PIN_RESET, HIGH);
1273
1274 LCDWrite(LCD_COMMAND, 0x21); //Tell LCD that extended commands follow
1275 LCDWrite(LCD_COMMAND, 0xB0); //Set LCD Vop (Contrast): Try 0xB1(good @ 3.3V) or 0xBF if your display is too dark
1276 LCDWrite(LCD_COMMAND, 0x04); //Set Temp coefficent
1277 LCDWrite(LCD_COMMAND, 0x14); //LCD bias mode 1:48: Try 0x13 or 0x14
1278
1279 LCDWrite(LCD_COMMAND, 0x20); //We must send 0x20 before modifying the display control mode
1280 LCDWrite(LCD_COMMAND, 0x0C); //Set display control, normal mode. 0x0D for inverse
1281 }
1282
1283 //There are two memory banks in the LCD, data/RAM and commands. This
1284 //function sets the DC pin high or low depending, and then sends
1285 //the data byte
1286 void LCDWrite(byte data_or_command, byte data) {
1287 digitalWrite(PIN_DC, data_or_command); //Tell the LCD that we are writing either to data or a command
1288
1289 //Send the data
1290 digitalWrite(PIN_SCE, LOW);
1291 shiftOut(PIN_SDIN, PIN_SCLK, MSBFIRST, data);
1292 digitalWrite(PIN_SCE, HIGH);
1293 }
1294
1295
1296
1297 #ifdef DEBUG
1298 /* The following code is taken from the
1299 Arduino FAT16 Library by William Greiman
1300 The code may or may-not survive in the long run,
1301 depending on what licensing-terms we decide on.
1302 The license will be open source, but the FAT16lib
1303 is GPL v3, and I (fishy) am personally not so sure about that...
1304
1305 On the other hand... This code is a very "intuitive approach",
1306 so contacting the author may give us the option of relicencing just this bit...
1307 */
1308 static int FreeRam(void) {
1309 extern int __bss_end;
1310 extern int* __brkval;
1311 int free_memory;
1312 if (reinterpret_cast<int>(__brkval) == 0) {
1313 // if no heap use from end of bss section
1314 free_memory = reinterpret_cast<int>(&free_memory)
1315 - reinterpret_cast<int>(&__bss_end);
1316 } else {
1317 // use from top of stack to heap
1318 free_memory = reinterpret_cast<int>(&free_memory)
1319 - reinterpret_cast<int>(__brkval);
1320 }
1321 return free_memory;
1322 }
1323 #endif
1324
1325
1326
1327