-
Notifications
You must be signed in to change notification settings - Fork 1
/
bitalino-riot-firmware.ino
2369 lines (2018 loc) · 79 KB
/
bitalino-riot-firmware.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
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* R-IoT :
Texas Instrument CC3200 Internet of Things / Sensor hub / Dev Platform
80 MHz 32 Bit ARM MCU + Wifi stack / modem
IRCAM - Emmanuel FLETY - Music Bricks - Rapid Mix
Rev History :
2.0 : moving to the LSM9DS1 motion sensor, new PCB from PLUX and secondary UART. UART0 : FTDI / UART1 : Bitalino
1.7 : Massive improvement in calibration and Euler angles - added bitalino support in this specific version
1.5 : adding a AP style connection to allow streaming to multiple computers / devices
1.4 : loads of fixing in the calibration process for the absolute angles (madgwick)
and webserver
*/
#include <stdio.h>
#include <strings.h>
#include <SPI.h>
#include <WiFi.h>
#include <WiFiClient.h>
#include <WiFiServer.h>
#include <WiFiUdp.h>
#include <Wire.h>
#include <bitalino1.h>
// Handles the file system of the FLASH, to store parameters
#include <SLFS.h>
#include "common.h"
#include "LSM9DS1.h"
#include "osc.h"
#include "web.h"
/////////////////////////////////////////////////////////////
// DEFAULT parameters
// your network name also called SSID
byte mac[6];
const char TheSSID[] = "riot";
const uint16_t TheDestPort = DEFAULT_UDP_PORT;
const uint8_t TheLocalIP[] = {
192,168,1,40};
const uint8_t TheSubnetMask[] = {
255,255,255,0};
const uint8_t TheGatewayIP[] = {
192,168,1,1};
const uint8_t TheDestIP[] = {
192,168,1,100};
const unsigned long TheSampleRate = DEFAULT_SAMPLE_RATE;
const uint8_t TheID = 0;
/////////////////////////////////////////////////////////////
// Global vars
WiFiServer server(80);
WiFiClient client;
byte APorStation = STATION_MODE;
char ssid[32];
char ssidAP[32];
char password[32] = "12345678";
IPAddress LocalIP;
IPAddress APIP;
IPAddress SubnetMask;
IPAddress GatewayIP;
IPAddress DestIP;
uint16_t DestPort;
uint8_t ModuleID;
unsigned long SampleRate;
boolean UseDHCP = true;
boolean UseSecurity = false;
int status = WL_IDLE_STATUS;
int statusAP = false;
int PacketStatus;
boolean ConfigurationMode = false;
boolean AcceptOSC = true;
byte PageToDisplay = CONFIG_WEB_PAGE;
unsigned int ConfigModePressCounter = 0;
// Allow config only shortly after start-up - Counter val * Sample Period
// Done in the idle 300 ms sample loop hence 17*300 ms = 5100 ms
unsigned int ConfigModeAllowCounter = 17;
int TempInt = 0;
boolean BlinkStatus = 0;
char packetBuffer[255]; //buffer to hold incoming packet
WiFiUDP UdpPacket;
WiFiUDP ConfigPacket;
OscBuffer RawSensors;
OscBuffer Message;
OscBuffer BitalinoData;
BITalinoFrame frame;
word FrameAmount = 0;
// Defines if we run the module in standalone or with bitalino support by default
// When in standalone mode, we can talk to the module via the serial port
// and get Serial.print debug / info / diag while this is muted in bitalino mode
// as the serial port is used exclusively for talking to the bitalino MCU.
boolean StandAloneMode = false;
// Variable that indicates if the bitalino has a datalogger connected to itself
// (to record the data coming from the IMU) or not
boolean logging = true;
unsigned long ElapsedTime = 0;
unsigned long ElapsedTime2 = 0;
////////////////////////////////////////////////////////////
// Sensor storage
short unsigned int SwitchState, ActualSwitchState;
short unsigned int SwitchState2, ActualSwitchState2;
short unsigned int RemoteOutputState = LOW;
Word AccelerationX, AccelerationY, AccelerationZ;
Word GyroscopeX, GyroscopeY, GyroscopeZ;
Word MagnetometerX, MagnetometerY, MagnetometerZ;
Word Temperature;
int AnalogInput1, AnalogInput2;
byte CommunicationMode = SPI_MODE;
//byte CommunicationMode = I2C_MODE;
// Defines whether you want the "raw" value with the stored offset or not
byte SendCalibrated = true;
//byte SendCalibrated = false;
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Absolute angle (madgwick)
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#define PI 3.14159265358979323846264338327950
// There is a tradeoff in the beta parameter between accuracy and response speed.
// In the original Madgwick study, beta of 0.041 (corresponding to GyroMeasError of 2.7 degrees/s) was found to give optimal accuracy.
// However, with this value, the LSM9SD0 response time is about 10 seconds to a stable initial quaternion.
// Subsequent changes also require a longish lag time to a stable output, not fast enough for a quadcopter or robot car!
// By increasing beta (GyroMeasError) by about a factor of fifteen, the response time constant is reduced to ~2 sec
// I haven't noticed any reduction in solution accuracy. This is essentially the I coefficient in a PID control sense;
// the bigger the feedback coefficient, the faster the solution converges, usually at the expense of accuracy.
// In any case, this is the free parameter in the Madgwick filtering and fusion scheme.
// Beta is called the rate of convergence of the filter. Higher value lead to a noisy output but fast response
// If beta = 0.0 => uses gyro only. A very high beta like 2.5 uses almost no gyro and only accel + magneto.
#define BETA_DEFAULT 0.4f // Much faster - noisier
#define BETA_MAX 2.0f
float beta = BETA_DEFAULT;
float madgwick_beta_max = BETA_MAX;
float madgwick_beta_gain = 1.0f;
int gyroOffsetAutocalTime = 5000; //ms = 1000 samples @5ms
long gyroOffsetAutocalThreshold = 100; //LSB
long gyroOffsetAutocalCounter; //internal
boolean gyroOffsetAutocalOn = false;
boolean gyroOffsetCalDone = false;
long gyroOffsetCalElapsed = 0;
long gyroOffsetAutocalMin[3];
long gyroOffsetAutocalMax[3];
long gyroOffsetAutocalSum[3];
long magOffsetAutocalMin[3];
long magOffsetAutocalMax[3];
long accOffsetAutocalSum[3];
float pitch, yaw, roll, heading;
float Declination = DECLINATION;
float deltat = 0.005f; // integration interval for both filter schemes - 5ms by default
int gyro_bias[3] = { 0, 0, 0};
int accel_bias[3] = { 0, 0, 0};
int mag_bias[3] = { 0, 0, 0};
int bias_samples = 32;
float abias[3] = { 0., 0., 0.};
float gbias[3] = { 0., 0., 0.};
float mbias[3] = { 0., 0., 0.};
float gRes, aRes, mRes; // Resolution = Sensor range / 2^15
float a_x, a_y, a_z, g_x, g_y, g_z, m_x, m_y, m_z; // variables to hold latest sensor data values
float gyro_norm; // used to tweak Beta
float mag_nobias[3];
float q1 = 1.0f, q2 = 0.0f, q3 = 0.0f, q4 = 0.0f; // quaternion of sensor frame relative to auxiliary frame
/////////////////////////////////////////////////////////////////
// Serial port message / buffers / temporary strings
char SerialBuffer[MAX_SERIAL];
unsigned char SerialIndex = 0;
boolean FlagSerial = FALSE;
char StringBuffer[MAX_STRING];
// To get printf to work, we redirect STDOUT and the myWrite functions
ssize_t myWrite(void *cookie, const char *buf, size_t n)
{
return Serial.write((uint8_t*)buf, n);
}
cookie_io_functions_t myVectors = {
0, myWrite, 0, 0 };
void setup() {
// Basic I/Os
pinMode(LED_RED, OUTPUT);
pinMode(LED_GREEN, OUTPUT);
pinMode(LED_BLUE, OUTPUT);
// Analog Inputs
pinMode(GPIO4, INPUT);
pinMode(GPIO5, INPUT);
// This is the former RIOT general purpose switch input, on another I/O for this version
// SWITCH_INPUT can be used in place of GPIO28, see common.h for I/0 definitions
pinMode(GPIO28, INPUT_PULLUP); // Used to trigger configuration mode
// This is an addition GPIO configured as an input and exported in the OSC message
// SWITCH2_INPUT can be used in place of GPIO13, see common.h for I/0 definitions
pinMode(GPIO13, INPUT_PULLUP);
// This is an addition GPIO configured as an input and exported in the OSC message
// REMOTE_OUTPUT can be used in place of GPIO12, see common.h for I/0 definitions
pinMode(GPIO12, OUTPUT);
digitalWrite(REMOTE_OUTPUT, RemoteOutputState);
// POWER On indicator
SetLedColor(1,0,0); // RED
//Initialize serial. Serial1 is for the bitalino board
Serial.begin(115200);
Serial1.begin(115200);
// Needed to have printf working
stdout = fopencookie((void *)0, "w", myVectors);
setlinebuf(stdout);
// Starts the file system
// This has to be done asap to determine if we are in bitalino mode or
// standalone mode.
SerFlash.begin();
// Retrieve saved params in FLASH using the file system
LoadParams();
// Bitalino framework init attempt
if(!StandAloneMode)
{
char verStr[30];
boolean ok;
BITalino.begin();
ok = BITalino.version(verStr, sizeof verStr); // get device version string
// Debug - uncomment if needed
/*Serial.print("version: ");
Serial.println(verStr);
Serial.print("Ok=");
Serial.println(ok);*/
// Here, some checks are needed to ensure we "found" the bitalino.
// Either check the version string or something else.
if(!ok)
{
StandAloneMode = true;
Serial.println("Bitalino not found, running in standalone R-IoT mode");
}
else
{
StandAloneMode = false; // Not absolutely needed but safety
Serial.println("Bitalino found, initializing at 1000 Hz");
ok = BITalino.battery(10); // set battery threshold (optional)
ok = BITalino.start(1000, 0x3F, false); // start acquisition of all channels at 1000 Hz
sprintf(StringBuffer, "/%u/bitalino\0",ModuleID);
PrepareOSC(&BitalinoData, StringBuffer, 'i', 11); // Seq # + 4 digital + 6 analog
}
}
Serial.println(VERSION_DATE);
Serial.println("Params Loaded");
// Check if we are going in configuration mode
// 2-3 second shorting the pin to ground during boot
while(!digitalRead(SWITCH_INPUT))
{
delay(20);
TempInt++;
if(BlinkStatus)
{
BlinkStatus = 0;
SetLedColor(1,0,0);
}
else
{
BlinkStatus = 1;
SetLedColor(0,0,0);
}
if(TempInt > WEB_SERVER_DELAY)
{
ConfigurationMode = true;
Serial.println("Configuration / Web Server Mode");
SetLedColor(1,0,0); // RED
break;
}
}
// Init motion sensor
Serial.println("Init Motion Sensor");
// Start SPI with defaults
SPI.begin();
// SPI settings
// 16 MHz max bit rate, clock divider 1:2 => 8 MHZ SPI clock
SPI.setClockDivider(SPI_CLOCK_DIV2);
SPI.setDataMode(SPI_MODE0);
// Sensor HW comm settings
if(CommunicationMode == SPI_MODE)
{
// Motion sensor I/Os
pinMode(ACC_CS, OUTPUT);
pinMode(MAG_CS, OUTPUT);
digitalWrite(ACC_CS, HIGH);
digitalWrite(MAG_CS, HIGH);
}
else
{
Wire.begin();
}
delay(10);
RebootLSM9DS1();
delay(10);
//////////////////////////////////////////
//// Init Motion sensor
InitLSM9DS1();
delay(40);
SetLedColor(0,1,0);
// Scaling to obtain gs and deg/s
// Must match the init settings of the LSM9DS1
gRes = 2000.0 / 32768.0; // +- 2000 deg/s
aRes = 8.0 / 32768.0; // +- 8g
mRes = 2.0 / 32768.0; // +- 2 gauss
// Finalize the bias unit conversion
for(int i = 0 ; i < 3 ; i++)
{
gbias[i] = gRes * (float)gyro_bias[i];
abias[i] = aRes * (float)accel_bias[i];
mbias[i] = mRes * (float)mag_bias[i];
}
if(!ConfigurationMode)
{
SetLedColor(0,1,0);
if(APorStation == STATION_MODE)
{
// Attempt to connect to Wifi network:
Serial.print("R-IoT connecting to: ");
// print the network name (SSID);
Serial.println(ssid);
Connect();
}
else // AP mode
{
// attempt to connect to Wifi network:
Serial.print("R-IoT creates network: ");
// print the network name (SSID);
Serial.println(ssid);
// Creates the AP & config
APIP = IPAddress(TheGatewayIP);
WiFi.config(APIP);
if(!UseSecurity)
WiFi.beginNetwork((char *)ssid);
else
WiFi.beginNetwork((char *)ssid, (char*)password);
}
if(StandAloneMode)
WiFi.macAddress(mac);
// Prep the UDP packet
UdpPacket.begin(DestPort);
UdpPacket.beginPacket(DestIP, DestPort);
// Open the service port to talk to the module (config, calibration)
ConfigPacket.begin(DEFAULT_UDP_SERVICE_PORT);
// Prepare the OSC message structure
// Now we send all data at once in a single message with only floats
sprintf(StringBuffer, "/%u/raw\0",ModuleID);
PrepareOSC(&RawSensors, StringBuffer, 'f', 23); // All float
} // END OF IF NORMAL (!CONFIG) MODE
// If in configuration mode we setup a webserver for configuring the unit
// The module becomes an AP with DHCP
else
{
APIP = IPAddress(TheGatewayIP);
WiFi.config(APIP);
randomSeed(analogRead(GPIO5));
sprintf(ssidAP, "RIOT-%04x\0",random(16000));
if(StandAloneMode)
{
Serial.print("Setting up Access Point named: ");
Serial.println(ssidAP);
}
WiFi.beginNetwork((char *)ssidAP);
WiFi.macAddress(mac);
}
ElapsedTime = millis();
ElapsedTime2 = millis();
if(ConfigModeAllowCounter)
Serial.println("Calibration enabled for now");
}
void loop() {
if(!ConfigurationMode)
{
if((millis() - ElapsedTime2) > 300) // Perform the check not too often
{
ElapsedTime2 = millis();
if(APorStation == STATION_MODE)
{
int CurrentStatus = WiFi.status();
if(CurrentStatus != WL_CONNECTED)
{
// print dots while we wait to connect and blink the power led
Serial.print(".");
if(BlinkStatus)
{
BlinkStatus = 0;
SetLedColor(0,0,0);
}
else
{
BlinkStatus = 1;
SetLedColor(0,1,0);
}
}
// Newly connected to the network, locks until DHCP answers
// if enabled
if((status != WL_CONNECTED) && (WiFi.status() == WL_CONNECTED))
{
status = WiFi.status();
SetLedColor(0,0,1); // Blue
Serial.println("\nConnected to the network");
while ((WiFi.localIP() == INADDR_NONE))
{
// print dots while we wait for an ip addresss
Serial.print(".");
delay(300);
}
// you're connected now, so print out the status
printCurrentNet();
printWifiData();
}
// Disconnected from the network, try to reconnect
if((status == WL_CONNECTED) && (WiFi.status() != WL_CONNECTED))
{
Serial.println("Network Lost, trying to reconnect");
status = WiFi.status();
}
} // End of Station mode connection
else // AP mode
{
if(WiFi.localIP() == INADDR_NONE) // Indicates AP isn't ready yet
{
// print dots while we wait to connect and blink the power led
if(StandAloneMode)
Serial.print(".");
if(BlinkStatus)
{
BlinkStatus = 0;
SetLedColor(0,0,0);
}
else
{
BlinkStatus = 1;
SetLedColor(0,1,0);
}
}
else if (!statusAP)
{
statusAP = true;
SetLedColor(0,0,1);
Serial.println("AP active.");
printCurrentNet();
printWifiData();
}
} // End of AP mode connection
// Enter IMU Calibration (even if not connected)
// Allow configuration mode only shortly after start-up
if(ConfigModeAllowCounter > 0)
{
--ConfigModeAllowCounter;
SwitchState = digitalRead(SWITCH_INPUT);
if(!SwitchState)
{
ConfigModePressCounter++;
if(ConfigModePressCounter > 10) // 10*300ms here = 3 sec after mainloop has started
{
ConfigModeAllowCounter = 0;
ConfigModePressCounter = 0;
CalibrateAccGyroMag();
}
}
else
{
// end of initial period that allows for calibration
ConfigModePressCounter = 0;
}
if(!ConfigModeAllowCounter)
Serial.println("Calibration is now disabled");
}
} // end of IF(elapsed time)
if(AcceptOSC)
{
// Parses incoming OSC messages
int packetSize = ConfigPacket.parsePacket();
if (packetSize)
{
// Debug Info
//Serial.print("Received packet of size ");
//Serial.println(packetSize);
//Serial.print("From ");
//IPAddress remoteIp = ConfigPacket.remoteIP();
//Serial.print(remoteIp);
//Serial.print(", port ");
//Serial.println(ConfigPacket.remotePort());
// read the packet into packetBufffer
int Index = 0;
int len = ConfigPacket.read(packetBuffer, 255);
if (len > 0) packetBuffer[len] = 0; // Add a terminator in the buffer
//Debug
/*Serial.println("Contents:");
Serial.println(packetBuffer);
Serial.println("Packet Len:");
Serial.println(len);
for (int i=0 ; i < len ; i++)
{
if(packetBuffer[i] == '\0')
printf("_");
else
printf("%c",packetBuffer[i]);
}
printf("\n");
printf("Generated Osc Message:\n");
for (int i=0 ; i < len ; i++)
{
if(Message.buf[i] == '\0')
printf("_");
else
printf("%c",Message.buf[i]);
}
printf("\n");*/
// Actual parsing
// Checks that's for the proper ID / module
sprintf(StringBuffer, "/%u/\0",ModuleID);
if(!strncmp(packetBuffer, StringBuffer, strlen(StringBuffer)))
{ // that's for us
char *pUDP = packetBuffer;
int Index = strlen(StringBuffer); // Skips the ID
// Parsing / decoding (basic)
if(!strncmp(&(pUDP[Index]), "output", 6))
{
Index += strlen("output");
Index = OscSkipToValue(pUDP, Index);
//Serial.println("After OSC SKIP");
//printf("Index = %d\n", Index);
int OscRemoteValue, TempInt;
TempInt = pUDP[Index];
OscRemoteValue = TempInt << 24;
Index++;
TempInt = pUDP[Index];
OscRemoteValue += OscRemoteValue || (TempInt << 16);
Index++;
TempInt = pUDP[Index];
OscRemoteValue += OscRemoteValue || (TempInt << 8);
Index++;
TempInt = pUDP[Index];
OscRemoteValue += OscRemoteValue || TempInt;
RemoteOutputState = OscRemoteValue;
if(RemoteOutputState)
RemoteOutputState = HIGH;
else
RemoteOutputState = LOW;
// Debug
printf("Remote Control Output update = %d\n", RemoteOutputState);
digitalWrite(REMOTE_OUTPUT,RemoteOutputState);
}
// add here other keywords like changing the sample rate and saving
// data => see parse serial
}
}
}
// The main sampling loop
if((millis() - ElapsedTime >= SampleRate) && !ConfigurationMode &&
((((WiFi.status()==WL_CONNECTED) || (logging == true)) && (APorStation==STATION_MODE)) ||
(statusAP && (APorStation==AP_MODE))) && ConfigModePressCounter == 0)
{
ElapsedTime = millis();
SetLedColor(0,0,1); // Turns blue
SwitchState = digitalRead(SWITCH_INPUT);
ActualSwitchState = !SwitchState;
// Second input reading
SwitchState2 = digitalRead(SWITCH2_INPUT);
ActualSwitchState2 = !SwitchState2;
// Debug
ReadAccel();
ReadGyro();
ReadMagneto();
ReadTemperature();
// Comment those 2 if you don't need the analog inputs to be exported by OSC
AnalogInput1 = analogRead(GPIO4);
AnalogInput2 = analogRead(GPIO5);
// Auto calibration of Acc and Gyro offsets if enabled
if((millis() - gyroOffsetCalElapsed > gyroOffsetAutocalTime) && gyroOffsetCalDone)
{
gyroOffsetCalElapsed = millis();
gyroOffsetCalDone = false;
}
if(!gyroOffsetCalDone && gyroOffsetAutocalOn)
{
gyroOffsetCalibration();
}
g_x = (gRes * (float)GyroscopeX.Value) - gbias[0]; // Convert to degrees per seconds, remove gyro biases
g_y = (gRes * (float)GyroscopeY.Value) - gbias[1];
g_z = (gRes * (float)GyroscopeZ.Value) - gbias[2];
a_x = (aRes * (float)AccelerationX.Value) - abias[0]; // Convert to g's, remove accelerometer biases
a_y = (aRes * (float)AccelerationY.Value) - abias[1];
a_z = (aRes * (float)AccelerationZ.Value) - abias[2];
m_x = (mRes * (float)MagnetometerX.Value) - mbias[0]; // Convert to Gauss and correct for calibration
m_y = (mRes * (float)MagnetometerY.Value) - mbias[1];
m_z = (mRes * (float)MagnetometerZ.Value) - mbias[2];
// compute the squared norm of the gyro data => rough estimation of the movement
gyro_norm = g_x * g_x + g_y * g_y + g_z * g_z;
mag_nobias[0] = m_x;
mag_nobias[1] = m_y;
mag_nobias[2] = m_z;
////////////////////////////////////////////////////////////////////////////////////
// Note regarding the sensor orientation & angles :
// We alter the sensor sign in order to "redefine gravity" and axis so that it behaves
// the same whether the sensor is up or down. However, for the heading computation and
// correction against angles, the "real" sensor orientation and pitch / roll proper
// signing must be used. We therefore do a double signe inversion when the sensor
// is on the bottom. [looks crappy but works and for good reasons]
// Different orientation of the LS1 vs LS0 for the magnetometers
MadgwickAHRSupdate(a_x, a_y, a_z, g_x*PI/180.0f, g_y*PI/180.0f, g_z*PI/180.0f, m_x, m_y, -m_z);
//MadgwickAHRSupdate(a_x, a_y, a_z, g_x*PI/180.0f, g_y*PI/180.0f, g_z*PI/180.0f, m_x, m_y, m_z);
yaw = atan2(2.0f * (q2 * q3 + q1 * q4), q1*q1 + q2*q2 - q3*q3 - q4*q4);
pitch = -asin(2.0f * ((q2*q4) - (q1*q3)));
roll = atan2(2.0f * (q1*q2 + q3*q4), (q1*q1) - (q2*q2) - (q3*q3) + (q4*q4));
// Compute heading *BEFORE* the final export of yaw pitch roll to save float computation of deg2rad / rad2deg
ComputeHeading();
/////////////////////////////////////////////////////////////////////////////////
// Degree per second conversion and declination correction
pitch *= 180.0f / PI;
yaw *= 180.0f / PI;
yaw -= Declination;
roll *= 180.0f / PI;
// Update sensors data in the main OSC message
char *pData = RawSensors.pData;
float TempFloat;
TempFloat = (float)millis();
FloatToBigEndian(pData, &TempFloat);
pData += sizeof(float);
if(logging == true){
Serial1.print(TempFloat); Serial1.print(",");
}
FloatToBigEndian(pData, &a_x);
pData += sizeof(float);
FloatToBigEndian(pData, &a_y);
pData += sizeof(float);
FloatToBigEndian(pData, &a_z);
pData += sizeof(float);
// Rescaling to deg/s to have a more human readable value
// and decent numbers similar to accel
float g_x_scaled, g_y_scaled, g_z_scaled;
g_x_scaled = g_x / 1000.; // Sending °/s
g_y_scaled = g_y / 1000.; // Sending °/s
g_z_scaled = g_z / 1000.; // Sending °/s
FloatToBigEndian(pData, &g_x_scaled);
pData += sizeof(float);
FloatToBigEndian(pData, &g_y_scaled);
pData += sizeof(float);
FloatToBigEndian(pData, &g_z_scaled);
pData += sizeof(float);
FloatToBigEndian(pData, &m_x);
pData += sizeof(float);
FloatToBigEndian(pData, &m_y);
pData += sizeof(float);
FloatToBigEndian(pData, &m_z);
pData += sizeof(float);
// Temperature
TempFloat = (float)Temperature.Value;
// Conversion to decimal °C here before float export
TempFloat = (TempFloat / (float)(LSM_TEMP_SCALE)) + (float)(LSM_BIAS_TEMPERATURE);
FloatToBigEndian(pData, &TempFloat);
pData += sizeof(float);
//if(logging == true){
// Serial1.print(millis()); Serial1.print(",");
// Serial1.print(TempFloat); Serial1.print(",");
//}
TempFloat = (float)ActualSwitchState;
FloatToBigEndian(pData, &TempFloat);
pData += sizeof(float);
TempFloat = (float)ActualSwitchState2;
FloatToBigEndian(pData, &TempFloat);
pData += sizeof(float);
// Analog Inputs (12 bits)
TempFloat = (float)AnalogInput1;
FloatToBigEndian(pData, &TempFloat);
pData += sizeof(float);
TempFloat = (float)AnalogInput2;
FloatToBigEndian(pData, &TempFloat);
pData += sizeof(float);
// Quaternions
FloatToBigEndian(pData, &q1);
pData += sizeof(float);
FloatToBigEndian(pData, &q2);
pData += sizeof(float);
FloatToBigEndian(pData, &q3);
pData += sizeof(float);
FloatToBigEndian(pData, &q4);
pData += sizeof(float);
// Euler Angles + Heading
FloatToBigEndian(pData, &yaw);
pData += sizeof(float);
FloatToBigEndian(pData, &pitch);
pData += sizeof(float);
FloatToBigEndian(pData, &roll);
pData += sizeof(float);
FloatToBigEndian(pData, &heading);
if(logging == true){
// Serial1.print(q1); Serial1.print(",");
// Serial1.print(q2); Serial1.print(",");
// Serial1.print(q3); Serial1.print(",");
// Serial1.print(q4); Serial1.print(",");
Serial1.print(yaw); Serial1.print(",");
Serial1.print(pitch); Serial1.print(",");
Serial1.print(roll); Serial1.print(",");
Serial1.print(heading); Serial1.print(",");
Serial1.print(a_x); Serial1.print(",");
Serial1.print(a_y); Serial1.print(",");
Serial1.print(a_z); Serial1.print(",");
Serial1.print(g_x_scaled); Serial1.print(",");
Serial1.print(g_y_scaled); Serial1.print(",");
Serial1.print(g_z_scaled); Serial1.print(",");
Serial1.print(m_x); Serial1.print(",");
Serial1.print(m_y); Serial1.print(",");
Serial1.println(m_z);
}
UdpPacket.write((uint8_t*)RawSensors.buf, RawSensors.PacketSize);
UdpPacket.endPacket();
if (FrameAmount == 1 && !StandAloneMode)
{
// Update the bitalino data/sensors data in the bitalino OSC message
pData = BitalinoData.pData;
int k;
// Sequence #
ShortToBigEndian(pData, frame.seq);
pData += sizeof(int);
// digital first
for(k=0 ; k < 4 ; k++)
{
ShortToBigEndian(pData, frame.digital[k]);
pData += sizeof(int);
}
// then analog
for(k=0 ; k < 6 ; k++)
{
ShortToBigEndian(pData, frame.analog[k]);
pData += sizeof(int);
}
UdpPacket.write((uint8_t*)BitalinoData.buf, BitalinoData.PacketSize);
UdpPacket.endPacket();
FrameAmount = 0;
}
SetLedColor(0,0,0);
}
// Process the bitalino serial stream separately from the first UART
if(Serial.available())
{
//////////////////////////////////////////////////////////////////////////////////
// Incoming serial message (config, control)
if(GrabSerialMessage())
{
ProcessSerial();
FlagSerial = false;
}
}
if(Serial1.available())
{
FrameAmount = BITalino.readSingle(&frame);
}
}
//////////////////////////////////////////////////////////////////////////////////
// Handles the web server for configuration via the webpage
else
{
if(WiFi.localIP() == INADDR_NONE)
{
if((millis() - ElapsedTime2) > 100) // Blinks faster than during normal mode
{
ElapsedTime2 = millis();
// print dots while we wait to connect and blink the power led
if(StandAloneMode)
Serial.print(".");
if(BlinkStatus)
{
BlinkStatus = 0;
SetLedColor(0,0,0);
}
else
{
BlinkStatus = 1;
SetLedColor(0,1,0);
}
}
}
else if (!statusAP) {
statusAP = true;
SetLedColor(0,0,1);
Serial.println("AP active.");
printCurrentNet();
printWifiData();
Serial.println("Starting webserver on port 80");
server.begin();
Serial.println("Webserver started!");
}
if(statusAP) // We can accept clients
{
char c;
char LocalHttpBuffer[300];
int HttpBufferIndex = 0;
unsigned int Index, Rank;
client = server.available();
if (client) {
if(StandAloneMode)
Serial.println("new client");
// an http request ends with a blank line
boolean currentLineIsBlank = true;
boolean StayConnected = true;
while (client.connected() && StayConnected )
{
if (client.available())
{
c = client.read();
Serial.write(c);
if(c != '\r')
LocalHttpBuffer[HttpBufferIndex++] = c;
if(!currentLineIsBlank && c == '\n')
{
LocalHttpBuffer[HttpBufferIndex++] = '\0';
// Process HTTP contents
//Serial.println("new http line - processing");
//Serial.print(LocalHttpBuffer);
HttpBufferIndex = 0;
if(!strncmp(LocalHttpBuffer, "GET / ", 6))
PageToDisplay = CONFIG_WEB_PAGE;
else if(!strncmp(LocalHttpBuffer, "GET /params", 11))
{ // Apply settings request - parsing all parameters, stores, update, reboot
char *pHtml = LocalHttpBuffer;
// position the pointer on the first param
while(*pHtml != '?' && *pHtml != '\0') pHtml++;
pHtml++; // skips the ?
while(*pHtml != '\0')
{
pHtml += GrabNextParam(pHtml, StringBuffer);
//Serial.print("Param found: ");
//Serial.println(StringBuffer);
// Parsing params withing the submitted URL
if(!strncmp("ssid", StringBuffer, 4))
{
Index = SkipToValue(StringBuffer);
strcpy(ssid, &(StringBuffer[Index]));
Serial.print("Updated SSID: ");
Serial.println(ssid);
}
if(!strncmp("pass", StringBuffer, 4))
{
Index = SkipToValue(StringBuffer);
strcpy(password, &(StringBuffer[Index]));
Serial.print("Updated password: ");
Serial.println(password);
}
if(!strncmp("security", StringBuffer, 8))
{
Index = SkipToValue(StringBuffer);
if(!strncmp(&(StringBuffer[Index]), "WPA2", 4))
UseSecurity = true;
else
UseSecurity = false;
Serial.print("Updated Security: ");
Serial.println(UseSecurity);
}
if(!strncmp("mode", StringBuffer, 4))
{
Index = SkipToValue(StringBuffer);
if(!strncmp(&(StringBuffer[Index]), "station", 7))
APorStation = STATION_MODE;
else
APorStation = AP_MODE;
Serial.print("Updated Mode: ");
Serial.println(APorStation);
}
if(!strncmp("type", StringBuffer, 4))
{
Index = SkipToValue(StringBuffer);
if(!strncmp(&(StringBuffer[Index]), "static", 6))
UseDHCP = false;
else
UseDHCP = true;
Serial.print("Updated DHCP: ");