[ create a new paste ] login | about

Link: http://codepad.org/nNgQzcB0    [ raw code | fork ]

meigrafd - C, pasted on Sep 29:
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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
/*
    Interface between Python and an Arduino

    Version: 0.1
    Creator: meigrafd
    Copyright (C) 2016 by meiraspi@gmail.com published under the MIT License

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.
*/

const int TRUE=1, FALSE=0;

/* ************************************************************************
Support for custom functions
************************************************************************ */ 
// I2C Arduino Library for a compass
#include <Wire.h>

// needed for 24LC256 EEPROM
#include <EEPROM.h>

// CMPS10 Compass
#include <CMPS10.h>

// Include and initialize the library for the LCD (SPI)
#include <LiquidCrystal.h>
LiquidCrystal lcd(11, 12, 3, 4, 2, 5);
String lcdMessage = "";

// Stuff for the status line on our LCD
unsigned long lastMinute = 0;
int commandsLastMinute = 0;
int iterationCount = 0;
int commandsAverage = 0;

/* ************************************************************************
Support for standard functions
************************************************************************ */ 
// Setup for servo handling 
#include <Servo.h> 
Servo myservo1, myservo2, myservo3, myservo4;

CMPS10 compass;

// 0=Wait for Handshake, "1"=Get Command, "2"=Process Command
int loopState=0;

// Command and sub command with their arguments
char cmdMain, cmdSub;
int arg1, arg2;                 // Integer versions for most purposes
String arg1String, arg2String;  // String version of arg1 for special purposes

// Working variables
String cmdLine;
char cmdChar;
int commaPos;

// Compass sample size, counter, and three axis data
int sampleSize = 25;
int sample = 0;
int x,y,z; 
long int xSum = 0;

// Switch for debug and/or trace logging mode (both add overhead)
int debugOn = FALSE;            // Returns verbose status
int traceOn = FALSE;            // Logs commands and responses for retrieval

// Buffers and other stuff for trace logging
int traceBuffer = 0;            // Which buffer are we using
String traceBuffer0, traceBuffer1;  // Rolling buffers
int traceBufferSize = 100;      // Size of buffers in lines
int traceLine = 0;              // Current line in current buffer
String lastTime = "";           // Last timestamp from server
long int millisCurrent = 0;     // Current trace time
long int millisLast = 0;        // Last trace time
long int millisDuration = 0;    // Duration between traces


/* ************************************************************************
Needed functions
************************************************************************ */


// *****
// Serial print (with trace exit)
// *****
void serialPrint(String output) {
    if (traceOn == TRUE) {
        traceEntry(output);
    }
    Serial.print(output);
    Serial.print("\n");
    //Serial.flush();
}

// *****
// Enter trace output into one of the two rotating buffers.
// *****
void traceEntry(String output) {
    // Timestamp this entry
    millisCurrent = millis();
    millisDuration = millisCurrent - millisLast;
    millisLast = millisCurrent;
    output += " - " + String(millisCurrent);
    output += " (" + String(millisDuration) + ")\n";

    // Write to the appropriate buffer
    if (traceBuffer == 0) {
        traceBuffer0 += lastTime;
        traceBuffer0 += " - ";
        traceBuffer0 += output;
    }
    else {
        traceBuffer1 += lastTime;
        traceBuffer1 += " - ";
        traceBuffer1 += output;
    }

    // If we have filled the second buffer move it forward and whack it
    traceLine++;
    if (traceLine == traceBufferSize) {
        if (traceBuffer == 1) {
            traceBuffer0 = traceBuffer1;
            traceBuffer1 = "";
        }
        else {
            traceBuffer++;
        }
        traceLine = 0;
    }
}

// *****
// Debug blinker
// *****
void blink(int blinks, int duration) {
  while(blinks-- > 0) {
    digitalWrite(13, HIGH);
    delay(duration);
    digitalWrite(13, LOW);
    delay(duration*2);
  }
}


// used with CMPS10 lib
void Compass() {
  Serial.print("Bearing: ");  // Peilung
  Serial.println(compass.bearing());
  Serial.print("Pitch: "); // Gefaelle/Steigung
  Serial.println(compass.pitch());
  Serial.print("Roll: "); // Neigung
  Serial.println(compass.roll());
}
/*
270 --> Osten
180 --> Norden
90 --> Westen
0 or 360 --> Süden

// used without CMPS10 lib
void Compass() {
  byte byteHigh, byteLow, fine;  // highByte and lowByte store high and low bytes of the bearing and fine stores decimal place of bearing
  char pitch, roll;              // Stores pitch and roll values of CMPS10, chars are used because they support signed value
  int bearing;                   // Stores full bearing

  Wire.beginTransmission(COMPASS_I2C_ADDRESS); //starts communication with CMPS10
  Wire.write(2);                               //Sends the register we wish to start reading from
  Wire.endTransmission();

  Wire.requestFrom(COMPASS_I2C_ADDRESS, 4);    // Request 4 bytes from CMPS10
  while(Wire.available() < 4);                 // Wait for bytes to become available
  byteHigh = Wire.read();
  byteLow = Wire.read();
  pitch = Wire.read();
  roll = Wire.read();
   
  bearing = ((byteHigh << 8) + byteLow) / 10;  // Calculate full bearing
  fine = ((byteHigh << 8) + byteLow) % 10;     // Calculate decimal place of bearing
 
  Serial.print("Bearing: "); Serial.println(bearing); // Peilung
  Serial.print("Bearing decimal: "); Serial.println(fine); // Peilung
  Serial.print("Pitch: "); Serial.println(pitch); // Gefaelle/Steigung
  Serial.print("Roll: "); Serial.println(roll); // Neigung
}
*/


// ****************************************************************
// Read 1.1V reference against AVcc - Courtesty of Scott Daniels - July 9, 2012 
// http://provideyourown.com/2012/secret-arduino-voltmeter-measure-battery-voltage/
// ****************************************************************
long readVcc() {
    // Set the reference to Vcc and the measurement to the internal 1.1V reference
    #if defined(__AVR_ATmega32U4__) || defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
        ADMUX = _BV(REFS0) | _BV(MUX4) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1);
    #elif defined (__AVR_ATtiny24__) || defined(__AVR_ATtiny44__) || defined(__AVR_ATtiny84__)
        ADMUX = _BV(MUX5) | _BV(MUX0);
    #elif defined (__AVR_ATtiny25__) || defined(__AVR_ATtiny45__) || defined(__AVR_ATtiny85__)
        ADMUX = _BV(MUX3) | _BV(MUX2);
    #else
        ADMUX = _BV(REFS0) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1);
    #endif  
 
    delay(2);                           // Wait for Vref to settle
    ADCSRA |= _BV(ADSC);                // Start conversion
    while (bit_is_set(ADCSRA,ADSC));    // measuring
 
    delay(20);
    uint8_t low  = ADCL;                // Read ADCL first - it then locks ADCH
    delay(20);
    uint8_t high = ADCH;                // Unlocks both
 
    long result = (high<<8) | low;

    // Calculate Vcc (in mV); 1125300 = 1.1*1023*1000 - (Uno 1098073L, Mega 1066957L)
//    result = 1066957L / result;         
    
    return result;                      // Vcc in millivolts
}



/* ************************************************************************
Interface is driven from the Python side so loop basically waits for serial input.
Handshake is initiated by a "%" to which a "#" is sent in response.
The command is then sent terminated by a "@".
Results are returned to Python with a prefix of "0" for OK or "1" for error followed
a return value (0 if not appropriate) and then a narrative response (if debug is on):

    % -->                                    from Python to Arduino
    <-- #                                    from Arduino to Python
    DR13@ -->                                from Python to Arduino
    <-- 0,1,Digital read from pin 13         from Arduino to Python
    
Commands that provide two arguments would have a comma separating the
first and second argument (e.g. DW13,20).
************************************************************************ */ 

/* ************************************************************************
Command Execution
************************************************************************ */ 
int executeCommand() {
    int intReturn = 0;
    unsigned long longReturn = 0;
    double doubleReturn = 0;

    int cmdSubInvalid = TRUE;
    String outputLine = "";
 
    int lcdLine = 0;
    char lcdLineChar;
    String lcdMessage = "";
    
    // For the LCD status display
    commandsLastMinute++;
    
    switch(cmdMain) {
        // ****************************************************************
        // STANDARD COMMANDS
        // ****************************************************************
        // *****
        // (P)in Mode Commands
        // *****
        case 'P':
            switch(cmdSub) {
                // ***** Set pin to input
                case 'I':
                    pinMode(arg1, INPUT);
                    outputLine = "0,";
                    if (debugOn == TRUE) {
                        outputLine += ",Pin " + arg1String + " set to Input";
                    }
                    serialPrint(outputLine);
                    cmdSubInvalid = FALSE;
                    break;
    
                // ***** Set pin to output
                case 'O':
                    pinMode(arg1, OUTPUT);
                    outputLine = "0,";
                    if (debugOn == TRUE) {
                        outputLine += ",Pin " + arg1String + " set to Output";
                    }
                    serialPrint(outputLine);
                    cmdSubInvalid = FALSE;
                    break;
            }
            break;

        // *****
        // (D)igital Commands
        // *****
        case 'D':
            switch(cmdSub) {
                // ***** Set digital high
                case 'H':
                    digitalWrite(arg1, HIGH);
                    outputLine = "0,";
                    if (debugOn == TRUE) {
                        outputLine += ",Pin " + arg1String + " set HIGH";
                    }
                    serialPrint(outputLine);
                    cmdSubInvalid = FALSE;
                    break;
    
                // ***** Set digital low
                case 'L':
                    digitalWrite(arg1, LOW);
                    outputLine = "0,";
                    if (debugOn == TRUE) {
                        outputLine += ",Pin " + arg1String + " set LOW";
                    }
                    serialPrint(outputLine);
                    cmdSubInvalid = FALSE;
                    break;
    
                // ***** Read digital value
                case 'R':
                    intReturn = digitalRead(arg1);
                    outputLine = "0,";
                    outputLine += String(intReturn);
                    if (debugOn == TRUE) {
                        outputLine += ",Digital read from pin " + arg1String;
                    }
                    serialPrint(outputLine);
                    cmdSubInvalid = FALSE;
                    break;

                // ***** Write digital value
                case 'W':
                    digitalWrite(arg1, arg2);
                    outputLine = "0,";
                    if (debugOn == TRUE) {
                        outputLine += ",Pin " + arg1String + " set to " + arg2String;
                    }
                    serialPrint(outputLine);
                    cmdSubInvalid = FALSE;
                    break;
            }
            break;
        
        // *****
        // (A)nalog Commands
        // *****
        case 'A':
            switch(cmdSub) {
            
                // ***** Write analog value
                case 'W':
                    analogWrite(arg1, arg2);
                    outputLine = "0,";
                    if (debugOn == TRUE) {
                        outputLine += ",Pin " + arg1String + " set to " + arg2String;
                    }
                    serialPrint(outputLine);
                    cmdSubInvalid = FALSE;
                    break;
            
                // ***** Read analog value
                case 'R':
                    intReturn = analogRead(arg1);
                    outputLine = "0,";
                    outputLine += String(intReturn);
                    if (debugOn == TRUE) {
                        outputLine += ",Analog read from pin " + arg1String;
                    }
                    serialPrint(outputLine);
                    cmdSubInvalid = FALSE;
                    break;

                // ***** Read pulse low
                case 'L':
                    digitalWrite(arg2, LOW);
                    digitalWrite(arg2, HIGH);
                    longReturn = pulseIn(arg1, LOW);
                    outputLine = "0,";
                    outputLine += String(longReturn);
                    if (debugOn == TRUE) {
                        outputLine += ",Pulse in from " + arg1String + " triggered by " + arg2String;
                    }
                    serialPrint(outputLine);
                    cmdSubInvalid = FALSE;
                    break;

                // ***** Read pulse high
                case 'H':
                    digitalWrite(arg2, LOW);
                    digitalWrite(arg2, HIGH);
                    longReturn = pulseIn(arg1, HIGH);
                    outputLine = "0,";
                    outputLine += String(longReturn);
                    if (debugOn == TRUE) {
                        outputLine += ",Pulse in from " + arg1String + " triggered by " + arg2String;
                    }
                    serialPrint(outputLine);
                    cmdSubInvalid = FALSE;
                    break;
            }
            break;
            
        // *****
        // (S)ervo Commands
        // *****
        case 'S':
            switch(cmdSub) {
                // ***** Attach a servo
                case 'A':
                    switch (arg1) {
                        case 1:
                            myservo1.attach(arg2);
                            break;
                        case 2:
                            myservo2.attach(arg2);
                            break;
                        case 3:
                            myservo3.attach(arg2);
                            break;
                        case 4:
                            myservo4.attach(arg2);
                            break;
                        default:
                            outputLine = "1,,Invalid servo specified (must be 1-4):" + arg1String;
                            serialPrint(outputLine);
                            return(-1);
                    }
                    outputLine = "0,";
                    if (debugOn == TRUE) {
                        outputLine += ",Servo " + arg1String + " attached to " + arg2String;
                    }
                    serialPrint(outputLine);

                    cmdSubInvalid = FALSE;
                    break;
        
                // ***** Command a servo
                case 'C':
                    switch (arg1) {
                        case 1:
                            myservo1.write(arg2);
                            break;
                        case 2:
                            myservo2.write(arg2);
                            break;
                        case 3:
                            myservo3.write(arg2);
                            break;
                        case 4:
                            myservo4.write(arg2);
                            break;
                        default:
                            outputLine = "1,,Invalid servo specified (must be 1-4):" + arg1String;
                            serialPrint(outputLine);
                            return(-1);
                    }
                    outputLine = "0,";
                    if (debugOn == TRUE) {
                        outputLine += ",Servo " + arg1String + " commanded to " + arg2String;
                    }
                    serialPrint(outputLine);

                    cmdSubInvalid = FALSE;
                    break;

                // ***** Detach a servo
                case 'D':
                    switch (arg1) {
                        case 1:
                            myservo1.detach();
                            break;
                        case 2:
                            myservo2.detach();
                            break;
                        case 3:
                            myservo3.detach();
                            break;
                        case 4:
                            myservo4.detach();
                            break;
                        default:
                            outputLine = "1,,Invalid servo specified (must be 1-4):" + arg1String;
                            serialPrint(outputLine);
                            return(-1);
                    }
                    outputLine = "0,";
                    if (debugOn == TRUE) {
                        outputLine += ",Servo " + arg1String + " detached";
                    }
                    serialPrint(outputLine);
                    cmdSubInvalid = FALSE;
                    break;
            }
            break;

        // *****
        // (H)ousekeeping Commands
        // *****
        case 'H':
            switch(cmdSub) {
                // ***** Turn debug on or off
                case 'D':
                    debugOn = arg1;
                    outputLine = "0,";
                    if (debugOn == TRUE) {
                        outputLine += ",Debug set to " + arg1String;
                    }
                    serialPrint(outputLine);                    
                    cmdSubInvalid = FALSE;
                    break;

                // ***** Turn trace on or off (debug follows automatically)
                case 'T':
                    traceOn = arg1;
                    debugOn = arg1;
                    outputLine = "0,";
                    if (debugOn == TRUE) {
                        outputLine += ",Trace set to " + arg1String;
                    }
                    serialPrint(outputLine);                    
                    cmdSubInvalid = FALSE;
                    break;
 
                // ***** D(u)mp trace
                case 'U':
                    if (traceBuffer == 0 && traceLine == 0) {
                        outputLine = "1,,Trace dump requested but buffer is empty";
                        serialPrint(outputLine);
                        return(-1);
                    }
                    outputLine = "0,,Trace dump follows";
                    serialPrint(outputLine);
                    if (traceBuffer == 1) {
                        Serial.print(traceBuffer0);
                        Serial.print(traceBuffer1);
                    }
                    else {
                        Serial.print(traceBuffer0);
                    }
                    Serial.print("\n#EOD#\n");
                    cmdSubInvalid = FALSE;
                    break;

                // ***** Set (L)ast Time
                case 'L':
                    serialPrint("0,,Set last time for trace");
                    lastTime = arg1String;
                    cmdSubInvalid = FALSE;
                    break;

                // ***** Return Reference Voltage
                case 'V':
                    outputLine = "0,";
                    outputLine += String(readVcc());
                    if (debugOn == TRUE) {
                        outputLine += ",Reference voltage returned";
                    }
                    serialPrint(outputLine);
                    cmdSubInvalid = FALSE;
                    break;
            }
            break;
            
        // ****************************************************************
        // EXTENDED COMMANDS 
        // ****************************************************************
        // *****
        // (C)ustom Commands
        // *****
        case 'C':
            switch(cmdSub) {
                // ***** LCD
                case 'L':
                    lcdLineChar = arg1String.charAt(0);
                    lcdLine = lcdLineChar - '0';
                    lcdMessage = arg1String.substring(1);
                
                    lcd.setCursor(0, lcdLine);
                    lcd.print(lcdMessage);
                    
                    outputLine = "0,Ok";
                    if (debugOn == TRUE) {
                        outputLine += ",LCD";
                    }
                    serialPrint(outputLine);
                    cmdSubInvalid = FALSE;
                    break;
            }
            break;

        // ****************************************************************
        // COMMAND OR SUBCOMMAND ERROR
        // ****************************************************************
        // *****
        // Command error
        // *****
        default:
            outputLine = "1,Invalid command:";
            outputLine += cmdMain;
            serialPrint(outputLine);
            return(-1);
    }
    // *****
    // Subcommand error
    // *****
    if (cmdSubInvalid) {
        outputLine = "1,Invalid sub command:";
        outputLine += cmdSub;
        serialPrint(outputLine);
        return(-1);
    }
    return(0);
}


void IO_proceed() {
    switch (loopState) {
        // *****
        // Handshake
        // *****
        case 0:     
            if (Serial.available() > 0) {
                if(Serial.read() == '%') {
                    Serial.write("#");
                    loopState = 1;
                    cmdLine = "";
                }
            }
            break;
            
        // *****
        // Get command
        // *****
        case 1:     
            if (Serial.available() > 0) {
                cmdChar = Serial.read();
                if (cmdChar == '@') {
                    loopState = 2;
                } else {
                    // Getting a "%" resets us to a new command
                    if (cmdChar == '%') {
                        Serial.write("#");
                        loopState = 1;
                        cmdLine = "";
                    } else {
                        cmdLine += cmdChar;
                    }
                }
            }
            break;

        // *****
        // Process command
        // *****
        case 2:
            cmdMain = cmdLine.charAt(0);
            cmdSub = cmdLine.charAt(1);
            commaPos = cmdLine.indexOf(",");
            // Most commands take an integer argument...
            arg1 = cmdLine.substring(2, commaPos).toInt();
            arg2 = cmdLine.substring(commaPos + 1).toInt();
            // ...but preserve arg1 in string state also
            arg1String = cmdLine.substring(2, commaPos);
            arg2String = cmdLine.substring(commaPos + 1);
            executeCommand();
            loopState = 0;
            break;
    }
}


/* ************************************************************************
Main Loop
************************************************************************ */

void loop() {
  IO_proceed();

}


/* ************************************************************************
Initialization
************************************************************************ */
void setup() {
    // Connect to the serial port
    Serial.begin(57600);
    Serial.flush();
    Wire.begin();  // Connects I2C for CMPS10 Compass
    millisLast = millis();
    /*
    // Set the size of the lcd and say hi
    lcd.begin(16,2);
    lcd.print("HW Interface up");
    lcd.setCursor(0, 1);
    lcd.print("P2A:Waiting");
    */
    lastMinute = millis();
}


Create a new paste based on this one


Comments: