-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMartiansAtMakerFaire2019.ino
698 lines (587 loc) · 16.2 KB
/
MartiansAtMakerFaire2019.ino
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
/*
Martians Project for Maker Faire 2019
Two light creatures, with animated colors point towards each other,
and animate when not close to each other.
Teaches:
Wireless communication
GPS location tracking
Magnatometer (compass) tracking
Data Serialization
Real-time and multi-tasking software engineering
8-bit processor environments (Arduino)
Battery operated and portable environments
LED display technology
Video of Martian's in action:
https://youtu.be/dwj0wr4Axek
Jim Henson’s Muppets work on Sesame Street inspired this project:
https://www.youtube.com/watch?v=KTc3PsW5ghQ
I brought the Martians to the Maker Faire, San Mateo, California. May 17 to 19, 2019.
http://makerfaire.com
Martians is a free GPL open source project. Find all code,
wiring, components, and everything else at:
https://github.com/frankcohen/Martians
See Marians Wiring Guide 2019.pdf for wiring instructions.
Martians uses the following parts:
TMRh20/RF24 wireless radios, https://github.com/tmrh20/RF24/
Neo7 GPS board, https://www.ebay.com/i/273760042170?chn=ps
Magnetometer, https://learn.adafruit.com/lsm303-accelerometer-slash-compass-breakout/coding
WS2812b LED strip, http://bit.ly/2W06RPd
Arduino Mega
Software libraries:
TinyGPS+
Adafruit_Sensor and Adafruit_LSM303_U to read compass and accelerometer
ArduinoJson - serialize and deserialize data between Martians
FastLED - drives LED display
Plastic housing found at IKEA. SOLVINDEN solar powered table light, $15
https://www.ikea.com/us/en/catalog/products/40422098/
-Frank Cohen, May 16, 2019
*/
#include <SPI.h>
#include <nRF24L01.h> // TMRh20/RF24, https://github.com/tmrh20/RF24/
#include <RF24.h>
#include <TinyGPS++.h>
#include <Wire.h>
#include <Adafruit_Sensor.h> // Adafruit Sensor and LSM303 compass libraries
#include <Adafruit_LSM303_U.h>
#include <ArduinoJson.h> // AdruinoJson: to serialize messages between martians
#include "printf.h"
#include "FastLED.h" // https://github.com/FastLED/FastLED
#include <math.h>
int radioNumber = 0; // 0 = Transmitter, 1 = Receiver
// Helper definitions to position the LEDs
// ring 0 0-34
// ring 1 35-66
// ring 2 67-95
// ring 3 96-120
// ring 4 121-140
#define ring0 0
#define ring0count 34
#define ring1 35
#define ring1count 31
#define ring2 67
#define ring2count 28
#define ring3 96
#define ring3count 24
#define ring4 121
#define ring4count 19
int rows[] = {ring0, ring1, ring2, ring3, ring4};
int rowscount[] = {ring0count, ring1count, ring2count, ring3count, ring4count};
// Helper to calculate headings
const float Pi = 3.14159;
static const uint32_t GPSBaud = 9600;
// Light animation show, based on FastLED ColorPalette example
#define UPDATES_PER_SECOND 50
#define LED_PIN 3
#define NUM_LEDS 144
#define BRIGHTNESS 64
#define LED_TYPE WS2812
#define COLOR_ORDER GRB
CRGB leds[NUM_LEDS];
CRGBPalette16 currentPalette;
TBlendType currentBlending;
// Storage for positions and headings
double magxrec = 0;
double magyrec = 0;
double magzrec = 0;
double lat = 0;
double lng = 0;
double latrec = 0;
double lngrec = 0;
long magxrecvalid = 0;
long magyrecvalid = 0;
long magzrecvalid = 0;
long latvalid = 0;
long lngvalid = 0;
long latrecvalid = 0;
long lngrecvalid = 0;
Adafruit_LSM303_Mag_Unified mag = Adafruit_LSM303_Mag_Unified(12345);
TinyGPSPlus gps;
RF24 radio(7, 8); // CE, CSN
// Radio pipe addresses for the 2 nodes to communicate.
const uint64_t pipes[2] = { 0xDBCDABCD71LL, 0xD44d52687CLL };
long messageCounter = 0;
int rrobin = 0;
int rrobin2 = 0;
int rrobin3 = 0;
#define timeoutval 6000
long showtime = millis();
#define showduration 15000
int showstage = 0;
boolean newshow = false;
int showblob = 0;
long showtime2 = millis() + (1000 / UPDATES_PER_SECOND);
uint8_t startIndex = 0;
boolean singleeyeotherflag = false;
boolean singleeyenorthflag = false;
void runLightShow()
{
if ( showtime + showduration < millis() )
{
// Change to new show
showtime = millis();
showstage++;
if ( showstage > 1 ) showstage = 0;
if ( showstage == 0 )
{
// If we have live remote gps then eye towards the other, with a blue background
if ( lat != 0 && lng != 0 && latrec != 0 && lngrec != 0 )
{
for ( int i = 0; i<NUM_LEDS; i++) { leds[ i ] = CRGB::Blue; }
if ( newshow )
{
newshow = false;
}
// Yearning: we have recent GPS results, background is blue, eye points towards other's bearing
SingleEyeTowardsOther( lat, lng, latrec, lngrec, 0 );
singleeyeotherflag = true;
singleeyenorthflag = false;
}
else
{
// If we have live remote compass then point the same heading as the other
if ( magyrec != 0 && magxrec != 0 )
{
if ( newshow )
{
newshow = false;
}
singleeyenorthflag = false;
singleeyeotherflag = true;
}
else
{
// Use the live local compass then point north
if ( newshow )
{
newshow = false;
}
// Syncopation (when GPS is invalid, one uses the other's compass heading background is red)
singleeyenorthflag = true;
singleeyeotherflag = false;
}
}
}
// Alternate betweeen RainbowStripeColors and CloudColors
if ( showstage == 1 )
{
if ( showblob == 0 ) { currentPalette = RainbowStripeColors_p; currentBlending = LINEARBLEND; }
if ( showblob == 1 ) { currentPalette = CloudColors_p; currentBlending = LINEARBLEND; }
showblob++;
if ( showblob > 1 ) showblob = 0;
}
}
if (millis() >= showtime2)
{
showtime2 = millis() + (1000 / UPDATES_PER_SECOND);
// Update the light show for rainbows and clouds
if ( showstage == 0 && singleeyenorthflag )
{
sensors_event_t event;
mag.getEvent(&event);
SingleEyeNorth( event.magnetic.y, event.magnetic.x, 0 );
}
if ( showstage == 0 && singleeyeotherflag )
{
// Syncopation (when GPS is invalid, one uses the other's compass heading background is red)
SingleEyeNorth( magyrec, magxrec, 0 );
}
if ( showstage == 1 )
{
startIndex = startIndex + 1; /* motion speed */
FillLEDsFromPaletteColors( startIndex );
}
FastLED.show();
}
}
void FillLEDsFromPaletteColors( uint8_t colorIndex)
{
uint8_t brightness = 255;
for( int i = 0; i < NUM_LEDS; i++) {
leds[i] = ColorFromPalette( currentPalette, colorIndex, brightness, currentBlending);
colorIndex += 3;
}
}
// Single row eye points north
void SingleEyeNorth( float y, float x, int row)
{
if ( y == 0 && x == 0 ) return;
float heading = (atan2(y,x) * 180) / Pi;
if (heading < 0) heading = 360 + heading;
for ( int i=0; i<NUM_LEDS; i++ )
{
leds[i] = CRGB::DarkRed;
leds[i].fadeLightBy( 200 );
}
int lightnum = (int) heading / ( 360 / rowscount[ row ] );
leds[ rows[ row ] + lightnum - 1 ] = CRGB::Blue;
leds[ rows[ row ] + lightnum ] = CRGB::Red;
leds[ rows[ row ] + lightnum + 1 ] = CRGB::Blue;
leds[ rows[ row ] + lightnum - 1 ].maximizeBrightness();
leds[ rows[ row ] + lightnum ].maximizeBrightness();
leds[ rows[ row ] + lightnum + 1 ].maximizeBrightness();
}
void SingleEyeTowardsOther( double lat1, double lon1, double lat2, double lon2, int row)
{
if ( lat1 == 0 || lon1 == 0 || lat2 == 0 || lon2 == 0 ) return;
// radians
float heading = atan2(lat1 - lat2, lon1 - lon2);
// convert to degrees 0 to 180/-180
heading *= (180 / 3.14159);
// convert to 0-360 compass degrees, North = 0
heading = (450 - (int)heading) % 360;
for ( int i=0; i<NUM_LEDS; i++ ) leds[i] = CRGB::Black;
int lightnum = (int) heading / ( 360 / rowscount[ row ] );
leds[ rows[ row ] + lightnum - 1 ] = CRGB::Blue;
leds[ rows[ row ] + lightnum ] = CRGB::Red;
leds[ rows[ row ] + lightnum + 1 ] = CRGB::Blue;
}
void initCompass()
{
#ifndef ESP8266
while (!Serial); // will pause Zero, Leonardo, etc until serial console opens
#endif
Serial.println("Compass set-up"); Serial.println("");
/* Enable auto-gain */
mag.enableAutoRange(true);
/* Initialise the sensor */
if(!mag.begin())
{
/* There was a problem detecting the LSM303 ... check your connections */
Serial.println("Ooops, no LSM303 detected ... Check your wiring!");
while(1);
}
}
static void printFloat(float val, bool valid, int len, int prec)
{
if (!valid)
{
while (len-- > 1)
Serial.print('*');
Serial.print(' ');
}
else
{
Serial.print(val, prec);
int vi = abs((int)val);
int flen = prec + (val < 0.0 ? 2 : 1); // . and -
flen += vi >= 1000 ? 4 : vi >= 100 ? 3 : vi >= 10 ? 2 : 1;
for (int i=flen; i<len; ++i)
Serial.print(' ');
}
smartDelay(10);
}
/* Delay and keeps the GPS feeding data and the light show animating */
static void smartDelay(unsigned long ms)
{
unsigned long start = millis();
do
{
runLightShow();
while (Serial3.available()) gps.encode(Serial3.read());
} while (millis() - start < ms);
}
// Remove the GPS and compass settings that have timed-out
void timeoutGPSvals()
{
if ( latrecvalid != 0 )
{
if ( millis() - latrecvalid > timeoutval )
{
latrecvalid = 0;
latrec = 0;
}
}
if ( lngrecvalid != 0 )
{
if ( millis() - lngrecvalid > timeoutval )
{
lngrecvalid = 0;
lngrec = 0;
}
}
if ( latvalid != 0 )
{
if ( millis() - latvalid > timeoutval )
{
latvalid = 0;
lat = 0;
}
}
if ( latvalid != 0 )
{
if ( millis() - latvalid > timeoutval )
{
latvalid = 0;
lat = 0;
}
}
}
void setup() {
Serial.begin(9600);
while (!Serial) continue;
printf_begin();
Serial.println( "Martians 2019 by Frank Cohen, [email protected], 2019");
Serial3.begin(GPSBaud); // Neo7L GPS
initCompass();
delay( 3000 ); // power-up safety delay
FastLED.addLeds<LED_TYPE, LED_PIN, COLOR_ORDER>(leds, NUM_LEDS).setCorrection( TypicalLEDStrip );
FastLED.setBrightness( BRIGHTNESS );
// Streaking blobs
currentPalette = RainbowStripeColors_p; currentBlending = LINEARBLEND;
// Spinning clouds
//currentPalette = CloudColors_p; currentBlending = LINEARBLEND;
radio.begin();
radio.enableDynamicPayloads();
radio.setRetries(5,15); // Smallest time between retries, max no. of retries
if ( radioNumber == 0 )
{
Serial.println("Setup transmitter.");
radio.openWritingPipe(pipes[0]);
radio.openReadingPipe(1,pipes[1]);
Serial.println("I am a transmitter.");
}
else
{
Serial.println("Setup receiver.");
radio.openWritingPipe(pipes[1]);
radio.openReadingPipe(1,pipes[0]);
Serial.println("I am a receiver.");
}
radio.startListening();
}
void loop()
{
timeoutGPSvals();
/* for debugging
Serial.print( lat );
Serial.print( " " );
Serial.print( lng );
Serial.print( " " );
Serial.print( latrec );
Serial.print( " " );
Serial.print( lngrec );
Serial.print( " " );
Serial.print( magxrec );
Serial.print( " " );
Serial.print( magyrec );
Serial.print( " " );
Serial.print( magzrec );
Serial.println( " " );
*/
if ( radioNumber == 0 )
{
// You are the transmitter, send your details
DynamicJsonDocument doc(30);
if ( rrobin3 == 0 )
{
if ( gps.location.isValid() )
{
if ( rrobin2 == 0 )
{
doc[ "lat" ] = gps.location.lat();
lat = gps.location.lat();
latvalid = millis();
}
if ( rrobin2 == 1 )
{
doc[ "lng" ] = gps.location.lng();
lng = gps.location.lng();
lngvalid = millis();
}
rrobin2++;
if ( rrobin2 > 1 ) rrobin2 = 0;
}
}
else
{
sensors_event_t event;
mag.getEvent(&event);
if ( rrobin == 0 )
{
doc[ "magneticx" ] = event.magnetic.x;
}
if ( rrobin == 1 )
{
doc[ "magneticy" ] = event.magnetic.y;
}
if ( rrobin == 2 )
{
doc[ "magneticz" ] = event.magnetic.z;
}
rrobin++;
if ( rrobin >2 ) rrobin = 0;
}
rrobin3++;
if ( rrobin3 > 1 ) rrobin3 = 0;
char output[30];
serializeJson(doc, output);
radio.stopListening();
radio.write(&output, 30);
radio.startListening();
// Wait here until we get a response, or timeout
unsigned long started_waiting_at = millis();
bool timeout = false;
while ( ! radio.available() && ! timeout )
{
smartDelay(10);
if (millis() - started_waiting_at > 500 )
timeout = true;
}
// Describe the results
if ( timeout )
{
//Serial.println("Timeout waiting for response");
smartDelay(100);
return;
}
else
{
char ackinput[30] = "";
radio.read(&ackinput, sizeof(ackinput));
DynamicJsonDocument ack2doc(30);
DeserializationError error = deserializeJson(ack2doc, ackinput);
if (error) {
Serial.print(F("deserializeJson() failed: "));
Serial.println( error.c_str() );
smartDelay(500);
return;
}
double magx2 = 0;
double magy2 = 0;
double magz2 = 0;
magx2 = ack2doc["magneticx"];
magy2 = ack2doc["magneticy"];
magz2 = ack2doc["magneticz"];
if ( magx2 != 0 )
{
magxrec = magx2;
magxrecvalid = millis();
}
if ( magy2 != 0 )
{
magyrec = magy2;
magyrecvalid = millis();
}
if ( magz2 != 0 )
{
magzrec = magz2;
magzrecvalid = millis();
}
double lat2 = 0;
double lng2 = 0;
lat2 = ack2doc["lat"];
lng2 = ack2doc["lng"];
if ( lat2 != 0 )
{
latrec = lat2;
latrecvalid = millis();
}
if ( lng2 != 0 )
{
lngrec = lng2;
lngrecvalid = millis();
}
}
}
else
{
// You are the receiver
if ( radio.available() )
{
char input[30] = "";
radio.read(&input, sizeof(input));
DynamicJsonDocument doc(30);
DeserializationError error = deserializeJson(doc, input);
if (error) {
Serial.print(F("deserializeJson() failed: "));
Serial.println(error.c_str());
smartDelay(500);
return;
}
double magx2 = 0;
double magy2 = 0;
double magz2 = 0;
magx2 = doc["magneticx"];
magy2 = doc["magneticy"];
magz2 = doc["magneticz"];
if ( magx2 != 0 )
{
magxrec = magx2;
magxrecvalid = millis();
}
if ( magy2 != 0 )
{
magyrec = magy2;
magyrecvalid = millis();
}
if ( magz2 != 0 )
{
magzrec = magz2;
magzrecvalid = millis();
}
double lat2 = 0;
double lng2 = 0;
lat2 = doc["lat"];
lng2 = doc["lng"];
if ( lat2 != 0 )
{
lat = lat2;
latvalid = millis();
}
if ( lng2 != 0 )
{
lng = lng2;
lngvalid = millis();
}
// Send the your details to the Transmitter
DynamicJsonDocument ackdoc(30);
if ( rrobin3 == 0 )
{
if ( gps.location.isValid() )
{
if ( rrobin2 == 0 )
{
ackdoc[ "lat" ] = gps.location.lat();
latrec = gps.location.lat();
latrecvalid = millis();
}
if ( rrobin2 == 1 )
{
ackdoc[ "lng" ] = gps.location.lng();
lngrec = gps.location.lat();
lngrecvalid = millis();
}
rrobin2++;
if ( rrobin2 > 1 ) rrobin2 = 0;
}
}
else
{
sensors_event_t event;
mag.getEvent(&event);
if ( rrobin == 0 )
{
ackdoc[ "magneticx" ] = event.magnetic.x;
}
if ( rrobin == 1 )
{
ackdoc[ "magneticy" ] = event.magnetic.y;
}
if ( rrobin == 2 )
{
ackdoc[ "magneticz" ] = event.magnetic.z;
}
rrobin++;
if ( rrobin >2 ) rrobin = 0;
}
rrobin3++;
if ( rrobin3 > 1 ) rrobin3 = 0;
char ackoutput[30];
serializeJson(ackdoc, ackoutput);
radio.stopListening();
radio.write(&ackoutput, 30);
radio.startListening();
}
}
smartDelay(1000);
}