This repository was archived by the owner on Jan 28, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 85
/
Copy pathSparkFun_Ublox_Arduino_Library.cpp
1767 lines (1494 loc) · 58.4 KB
/
SparkFun_Ublox_Arduino_Library.cpp
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
/*
This is a library written for the Ublox NEO-M8P-2
SparkFun sells these at its website: www.sparkfun.com
Do you like this library? Help support SparkFun. Buy a board!
https://www.sparkfun.com/products/14586
Written by Nathan Seidle @ SparkFun Electronics, September 6th, 2018
The NEO-M8P-2 is a powerful GPS receiver capable of calculating correction data
to achieve 2cm accuracy.
This library handles the configuration of 'survey-in', RTCM messages, and to output
the RTCM messages to the user's selected stream
https://github.com/sparkfun/SparkFun_RTK_Arduino_Library
Development environment specifics:
Arduino IDE 1.8.5
Modified by David Mann @ Loggerhead Instruments, 16 April 2019
- Added support for parsing date and time
- Added functions getYear(), getMonth(), getDay(), getHour(), getMinute(), getSecond()
Modified by Steven Rowland, June 11th, 2019
- Added functionality for reading HPPOSLLH (High Precision Geodetic Position)
- Added getTimeOfWeek(), getHighResLatitude(). getHighResLongitude(), getElipsoid(),
getMeanSeaLevel(), getHorizontalAccuracy(), getVerticalAccuracy(), getHPPOSLLH()
- Modified ProcessUBXPacket to parse HPPOSLLH packet
- Added query staleness verification for HPPOSLLH data
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.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "SparkFun_Ublox_Arduino_Library.h"
SFE_UBLOX_GPS::SFE_UBLOX_GPS(void)
{
// Constructor
}
//Initialize the Serial port
boolean SFE_UBLOX_GPS::begin(TwoWire &wirePort, uint8_t deviceAddress)
{
commType = COMM_TYPE_I2C;
_i2cPort = &wirePort; //Grab which port the user wants us to use
//We expect caller to begin their I2C port, with the speed of their choice external to the library
//But if they forget, we start the hardware here.
//We're moving away from the practice of starting Wire hardware in a library. This is to avoid cross platform issues.
//ie, there are some platforms that don't handle multiple starts to the wire hardware. Also, every time you start the wire
//hardware the clock speed reverts back to 100kHz regardless of previous Wire.setClocks().
//_i2cPort->begin();
_gpsI2Caddress = deviceAddress; //Store the I2C address from user
return (isConnected());
}
//Initialize the Serial port
boolean SFE_UBLOX_GPS::begin(Stream &serialPort)
{
commType = COMM_TYPE_SERIAL;
_serialPort = &serialPort; //Grab which port the user wants us to use
return (isConnected());
}
//Enable or disable the printing of sent/response HEX values.
//Use this in conjunction with 'Transport Logging' from the Universal Reader Assistant to see what they're doing that we're not
void SFE_UBLOX_GPS::enableDebugging(Stream &debugPort)
{
_debugSerial = &debugPort; //Grab which port the user wants us to use for debugging
_printDebug = true; //Should we print the commands we send? Good for debugging
}
void SFE_UBLOX_GPS::disableDebugging(void)
{
_printDebug = false; //Turn off extra print statements
}
//Safely print messages
void SFE_UBLOX_GPS::debugPrint(char *message)
{
if (_printDebug == true)
{
_debugSerial->print(message);
}
}
//Safely print messages
void SFE_UBLOX_GPS::debugPrintln(char *message)
{
if (_printDebug == true)
{
_debugSerial->println(message);
}
}
void SFE_UBLOX_GPS::factoryReset()
{
// Copy default settings to permanent
packetCfg.cls = UBX_CLASS_CFG;
packetCfg.id = UBX_CFG_CFG;
packetCfg.len = 13;
packetCfg.startingSpot = 0;
for (uint8_t i = 0; i < 4; i++)
{
payloadCfg[0 + i] = 0xff; // clear mask: copy default config to permanent config
payloadCfg[4 + i] = 0x00; // save mask: don't save current to permanent
payloadCfg[8 + i] = 0x00; // load mask: don't copy permanent config to current
}
payloadCfg[12] = 0xff; // all forms of permanent memory
sendCommand(packetCfg, 0); // don't expect ACK
hardReset(); // cause factory default config to actually be loaded and used cleanly
}
void SFE_UBLOX_GPS::hardReset()
{
// Issue hard reset
packetCfg.cls = UBX_CLASS_CFG;
packetCfg.id = UBX_CFG_RST;
packetCfg.len = 4;
packetCfg.startingSpot = 0;
payloadCfg[0] = 0xff; // cold start
payloadCfg[1] = 0xff; // cold start
payloadCfg[2] = 0; // 0=HW reset
payloadCfg[3] = 0; // reserved
sendCommand(packetCfg, 0); // don't expect ACK
}
//Changes the serial baud rate of the Ublox module, can't return success/fail 'cause ACK from modem
//is lost due to baud rate change
void SFE_UBLOX_GPS::setSerialRate(uint32_t baudrate, uint8_t uartPort, uint16_t maxWait)
{
//Get the current config values for the UART port
getPortSettings(uartPort, maxWait); //This will load the payloadCfg array with current port settings
if (_printDebug == true)
{
_debugSerial->print("Current baud rate: ");
_debugSerial->println(((uint32_t)payloadCfg[10] << 16) | ((uint32_t)payloadCfg[9] << 8) | payloadCfg[8]);
}
packetCfg.cls = UBX_CLASS_CFG;
packetCfg.id = UBX_CFG_PRT;
packetCfg.len = 20;
packetCfg.startingSpot = 0;
//payloadCfg is now loaded with current bytes. Change only the ones we need to
payloadCfg[8] = baudrate;
payloadCfg[9] = baudrate >> 8;
payloadCfg[10] = baudrate >> 16;
payloadCfg[11] = baudrate >> 24;
if (_printDebug == true)
{
_debugSerial->print("New baud rate:");
_debugSerial->println(((uint32_t)payloadCfg[10] << 16) | ((uint32_t)payloadCfg[9] << 8) | payloadCfg[8]);
}
sendCommand(packetCfg);
}
//Changes the I2C address that the Ublox module responds to
//0x42 is the default but can be changed with this command
boolean SFE_UBLOX_GPS::setI2CAddress(uint8_t deviceAddress, uint16_t maxWait)
{
//Get the current config values for the I2C port
getPortSettings(COM_PORT_I2C); //This will load the payloadCfg array with current port settings
packetCfg.cls = UBX_CLASS_CFG;
packetCfg.id = UBX_CFG_PRT;
packetCfg.len = 20;
packetCfg.startingSpot = 0;
//payloadCfg is now loaded with current bytes. Change only the ones we need to
payloadCfg[4] = deviceAddress << 1; //DDC mode LSB
if (sendCommand(packetCfg, maxWait) == true)
{
//Success! Now change our internal global.
_gpsI2Caddress = deviceAddress; //Store the I2C address from user
return (true);
}
return (false);
}
//Want to see the NMEA messages on the Serial port? Here's how
void SFE_UBLOX_GPS::setNMEAOutputPort(Stream &nmeaOutputPort)
{
_nmeaOutputPort = &nmeaOutputPort; //Store the port from user
}
//Called regularly to check for available bytes on the user' specified port
boolean SFE_UBLOX_GPS::checkUblox()
{
if (commType == COMM_TYPE_I2C)
return (checkUbloxI2C());
else if (commType == COMM_TYPE_SERIAL)
return (checkUbloxSerial());
return false;
}
//Polls I2C for data, passing any new bytes to process()
//Returns true if new bytes are available
boolean SFE_UBLOX_GPS::checkUbloxI2C()
{
if (millis() - lastCheck >= I2C_POLLING_WAIT_MS)
{
//Get the number of bytes available from the module
uint16_t bytesAvailable = 0;
_i2cPort->beginTransmission(_gpsI2Caddress);
_i2cPort->write(0xFD); //0xFD (MSB) and 0xFE (LSB) are the registers that contain number of bytes available
if (_i2cPort->endTransmission(false) != 0) //Send a restart command. Do not release bus.
return (false); //Sensor did not ACK
_i2cPort->requestFrom((uint8_t)_gpsI2Caddress, (uint8_t)2);
if (_i2cPort->available())
{
uint8_t msb = _i2cPort->read();
uint8_t lsb = _i2cPort->read();
if (lsb == 0xFF)
{
debugPrintln("No bytes available");
lastCheck = millis(); //Put off checking to avoid I2C bus traffic
return (false);
}
bytesAvailable = (uint16_t)msb << 8 | lsb;
}
if (bytesAvailable == 0)
{
debugPrintln("Zero bytes available");
lastCheck = millis(); //Put off checking to avoid I2C bus traffic
return (false);
}
while (bytesAvailable)
{
_i2cPort->beginTransmission(_gpsI2Caddress);
_i2cPort->write(0xFF); //0xFF is the register to read data from
if (_i2cPort->endTransmission(false) != 0) //Send a restart command. Do not release bus.
return (false); //Sensor did not ACK
//Limit to 32 bytes or whatever the buffer limit is for given platform
uint16_t bytesToRead = bytesAvailable;
if (bytesToRead > I2C_BUFFER_LENGTH)
bytesToRead = I2C_BUFFER_LENGTH;
TRY_AGAIN:
_i2cPort->requestFrom((uint8_t)_gpsI2Caddress, (uint8_t)bytesToRead);
if (_i2cPort->available())
{
for (uint16_t x = 0; x < bytesToRead; x++)
{
uint8_t incoming = _i2cPort->read(); //Grab the actual character
//Check to see if the first read is 0x7F. If it is, the module is not ready
//to respond. Stop, wait, and try again
if (x == 0)
{
if (incoming == 0x7F)
{
debugPrintln("Module not ready with data");
delay(5); //In logic analyzation, the module starting responding after 1.48ms
goto TRY_AGAIN;
}
}
process(incoming); //Process this valid character
}
}
else
return (false); //Sensor did not respond
bytesAvailable -= bytesToRead;
}
}
return (true);
} //end checkUbloxI2C()
//Checks Serial for data, passing any new bytes to process()
boolean SFE_UBLOX_GPS::checkUbloxSerial()
{
while (_serialPort->available())
{
process(_serialPort->read());
}
return (true);
} //end checkUbloxSerial()
//Processes NMEA and UBX binary sentences one byte at a time
//Take a given byte and file it into the proper array
void SFE_UBLOX_GPS::process(uint8_t incoming)
{
if (_printDebug == true)
{
//if (currentSentence == NONE && incoming == 0xB5) //UBX binary frames start with 0xB5, aka μ
// _debugSerial->println(); //Show new packet start
//_debugSerial->print(" ");
//_debugSerial->print(incoming, HEX);
}
if (currentSentence == NONE || currentSentence == NMEA)
{
if (incoming == 0xB5) //UBX binary frames start with 0xB5, aka μ
{
//This is the start of a binary sentence. Reset flags.
//We still don't know the response class
ubxFrameCounter = 0;
rollingChecksumA = 0; //Reset our rolling checksums
rollingChecksumB = 0;
currentSentence = UBX;
}
else if (incoming == '$')
{
currentSentence = NMEA;
}
else if (incoming == 0xD3) //RTCM frames start with 0xD3
{
rtcmFrameCounter = 0;
currentSentence = RTCM;
}
else
{
//This character is unknown or we missed the previous start of a sentence
}
}
//Depending on the sentence, pass the character to the individual processor
if (currentSentence == UBX)
{
//Decide what type of response this is
if (ubxFrameCounter == 0 && incoming != 0xB5) //ISO 'μ'
currentSentence = NONE; //Something went wrong. Reset.
else if (ubxFrameCounter == 1 && incoming != 0x62) //ASCII 'b'
currentSentence = NONE; //Something went wrong. Reset.
else if (ubxFrameCounter == 2) //Class
{
packetAck.counter = 0;
packetAck.valid = false;
packetCfg.counter = 0;
packetCfg.valid = false;
//We can now identify the type of response
if (incoming == UBX_CLASS_ACK)
ubxFrameClass = CLASS_ACK;
else
ubxFrameClass = CLASS_NOT_AN_ACK;
}
ubxFrameCounter++;
//Depending on this frame's class, pass different structs and payload arrays
if (ubxFrameClass == CLASS_ACK)
processUBX(incoming, &packetAck);
else if (ubxFrameClass == CLASS_NOT_AN_ACK)
processUBX(incoming, &packetCfg);
}
else if (currentSentence == NMEA)
{
processNMEA(incoming); //Process each NMEA character
}
else if (currentSentence == RTCM)
{
processRTCMframe(incoming); //Deal with RTCM bytes
}
}
//This is the default or generic NMEA processor. We're only going to pipe the data to serial port so we can see it.
//User could overwrite this function to pipe characters to nmea.process(c) of tinyGPS or MicroNMEA
//Or user could pipe each character to a buffer, radio, etc.
void SFE_UBLOX_GPS::processNMEA(char incoming)
{
//If user has assigned an output port then pipe the characters there
if (_nmeaOutputPort != NULL)
_nmeaOutputPort->write(incoming); //Echo this byte to the serial port
}
//We need to be able to identify an RTCM packet and then the length
//so that we know when the RTCM message is completely received and we then start
//listening for other sentences (like NMEA or UBX)
//RTCM packet structure is very odd. I never found RTCM STANDARD 10403.2 but
//http://d1.amobbs.com/bbs_upload782111/files_39/ourdev_635123CK0HJT.pdf is good
//https://dspace.cvut.cz/bitstream/handle/10467/65205/F3-BP-2016-Shkalikava-Anastasiya-Prenos%20polohove%20informace%20prostrednictvim%20datove%20site.pdf?sequence=-1
//Lead me to: https://forum.u-blox.com/index.php/4348/how-to-read-rtcm-messages-from-neo-m8p
//RTCM 3.2 bytes look like this:
//Byte 0: Always 0xD3
//Byte 1: 6-bits of zero
//Byte 2: 10-bits of length of this packet including the first two-ish header bytes, + 6.
//byte 3 + 4 bits: Msg type 12 bits
//Example: D3 00 7C 43 F0 ... / 0x7C = 124+6 = 130 bytes in this packet, 0x43F = Msg type 1087
void SFE_UBLOX_GPS::processRTCMframe(uint8_t incoming)
{
if (rtcmFrameCounter == 1)
{
rtcmLen = (incoming & 0x03) << 8; //Get the last two bits of this byte. Bits 8&9 of 10-bit length
}
else if (rtcmFrameCounter == 2)
{
rtcmLen |= incoming; //Bits 0-7 of packet length
rtcmLen += 6; //There are 6 additional bytes of what we presume is header, msgType, CRC, and stuff
}
/*else if (rtcmFrameCounter == 3)
{
rtcmMsgType = incoming << 4; //Message Type, MS 4 bits
}
else if (rtcmFrameCounter == 4)
{
rtcmMsgType |= (incoming >> 4); //Message Type, bits 0-7
}*/
rtcmFrameCounter++;
processRTCM(incoming); //Here is where we expose this byte to the user
if (rtcmFrameCounter == rtcmLen)
{
//We're done!
currentSentence = NONE; //Reset and start looking for next sentence type
}
}
//This function is called for each byte of an RTCM frame
//Ths user can overwrite this function and process the RTCM frame as they please
//Bytes can be piped to Serial or other interface. The consumer could be a radio or the internet (Ntrip broadcaster)
void SFE_UBLOX_GPS::processRTCM(uint8_t incoming)
{
//Radio.sendReliable((String)incoming); //An example of passing this byte to a radio
//_debugSerial->write(incoming); //An example of passing this byte out the serial port
//Debug printing
// _debugSerial->print(" ");
// if(incoming < 0x10) _debugSerial->print("0");
// if(incoming < 0x10) _debugSerial->print("0");
// _debugSerial->print(incoming, HEX);
// if(rtcmFrameCounter % 16 == 0) _debugSerial->println();
}
//Given a character, file it away into the uxb packet structure
//Set valid = true once sentence is completely received and passes CRC
//The payload portion of the packet can be 100s of bytes but the max array
//size is roughly 64 bytes. startingSpot can be set so we only record
//a subset of bytes within a larger packet.
void SFE_UBLOX_GPS::processUBX(uint8_t incoming, ubxPacket *incomingUBX)
{
//Add all incoming bytes to the rolling checksum
//Stop at len+4 as this is the checksum bytes to that should not be added to the rolling checksum
if (incomingUBX->counter < incomingUBX->len + 4)
addToChecksum(incoming);
if (incomingUBX->counter == 0)
{
incomingUBX->cls = incoming;
}
else if (incomingUBX->counter == 1)
{
incomingUBX->id = incoming;
}
else if (incomingUBX->counter == 2) //Len LSB
{
incomingUBX->len = incoming;
}
else if (incomingUBX->counter == 3) //Len MSB
{
incomingUBX->len |= incoming << 8;
}
else if (incomingUBX->counter == incomingUBX->len + 4) //ChecksumA
{
incomingUBX->checksumA = incoming;
}
else if (incomingUBX->counter == incomingUBX->len + 5) //ChecksumB
{
incomingUBX->checksumB = incoming;
currentSentence = NONE; //We're done! Reset the sentence to being looking for a new start char
//Validate this sentence
if (incomingUBX->checksumA == rollingChecksumA && incomingUBX->checksumB == rollingChecksumB)
{
if (_printDebug == true)
{
_debugSerial->print("Size: ");
_debugSerial->print(incomingUBX->len);
_debugSerial->print(" Received: ");
printPacket(incomingUBX);
}
incomingUBX->valid = true;
processUBXpacket(incomingUBX); //We've got a valid packet, now do something with it
}
else
{
if (_printDebug == true)
{
debugPrintln("Checksum failed. Response too big?");
digitalWrite(2, LOW);
delay(10);
digitalWrite(2, HIGH);
_debugSerial->print("Received: ");
printPacket(incomingUBX);
_debugSerial->print("Size: ");
_debugSerial->print(incomingUBX->len);
_debugSerial->print(" checksumA: ");
_debugSerial->print(incomingUBX->checksumA);
_debugSerial->print(" checksumB: ");
_debugSerial->print(incomingUBX->checksumB);
_debugSerial->print(" rollingChecksumA: ");
_debugSerial->print(rollingChecksumA);
_debugSerial->print(" rollingChecksumB: ");
_debugSerial->print(rollingChecksumB);
_debugSerial->println();
}
}
}
else //Load this byte into the payload array
{
//If a UBX_NAV_PVT packet comes in asynchronously, we need to fudge the startingSpot
uint16_t startingSpot = incomingUBX->startingSpot;
if (incomingUBX->cls == UBX_CLASS_NAV && incomingUBX->id == UBX_NAV_PVT)
startingSpot = 0;
//Begin recording if counter goes past startingSpot
if ((incomingUBX->counter - 4) >= startingSpot)
{
//Check to see if we have room for this byte
if (((incomingUBX->counter - 4) - startingSpot) < MAX_PAYLOAD_SIZE) //If counter = 208, starting spot = 200, we're good to record.
incomingUBX->payload[incomingUBX->counter - 4 - startingSpot] = incoming; //Store this byte into payload array
}
}
incomingUBX->counter++;
}
//Once a packet has been received and validated, identify this packet's class/id and update internal flags
void SFE_UBLOX_GPS::processUBXpacket(ubxPacket *msg)
{
switch (msg->cls)
{
case UBX_CLASS_ACK:
//We don't want to store ACK packets, just set commandAck flag
if (msg->id == UBX_ACK_ACK && msg->payload[0] == packetCfg.cls && msg->payload[1] == packetCfg.id)
{
//The ack we just received matched the CLS/ID of last packetCfg sent
debugPrintln("Command sent/ack'd successfully");
commandAck = true;
}
break;
case UBX_CLASS_NAV:
if (msg->id == UBX_NAV_PVT && msg->len == 92)
{
//Parse various byte fields into global vars
constexpr int startingSpot = 0; //fixed value used in processUBX
gpsMillisecond = extractLong(0) % 1000; //Get last three digits of iTOW
gpsYear = extractInt(4);
gpsMonth = extractByte(6);
gpsDay = extractByte(7);
gpsHour = extractByte(8);
gpsMinute = extractByte(9);
gpsSecond = extractByte(10);
gpsNanosecond = extractLong(16); //Includes milliseconds
fixType = extractByte(20 - startingSpot);
carrierSolution = extractByte(21 - startingSpot) >> 6; //Get 6th&7th bits of this byte
SIV = extractByte(23 - startingSpot);
longitude = extractLong(24 - startingSpot);
latitude = extractLong(28 - startingSpot);
altitude = extractLong(32 - startingSpot);
altitudeMSL = extractLong(36 - startingSpot);
groundSpeed = extractLong(60 - startingSpot);
headingOfMotion = extractLong(64 - startingSpot);
pDOP = extractLong(76 - startingSpot);
//Mark all datums as fresh (not read before)
moduleQueried.gpsYear = true;
moduleQueried.gpsMonth = true;
moduleQueried.gpsDay = true;
moduleQueried.gpsHour = true;
moduleQueried.gpsMinute = true;
moduleQueried.gpsSecond = true;
moduleQueried.gpsNanosecond = true;
moduleQueried.all = true;
moduleQueried.longitude = true;
moduleQueried.latitude = true;
moduleQueried.altitude = true;
moduleQueried.altitudeMSL = true;
moduleQueried.SIV = true;
moduleQueried.fixType = true;
moduleQueried.carrierSolution = true;
moduleQueried.groundSpeed = true;
moduleQueried.headingOfMotion = true;
moduleQueried.pDOP = true;
}
else if (msg->id == UBX_NAV_HPPOSLLH && msg->len == 36)
{
timeOfWeek = extractLong(4);
highResLatitude = extractLong(8);
highResLongitude = extractLong(12);
elipsoid = extractLong(16);
meanSeaLevel = extractLong(20);
geoidSeparation = extractLong(24);
horizontalAccuracy = extractLong(28);
verticalAccuracy = extractLong(32);
highResModuleQueried.all = true;
highResModuleQueried.timeOfWeek = true;
highResModuleQueried.highResLatitude = true;
highResModuleQueried.highResLongitude = true;
highResModuleQueried.elipsoid = true;
highResModuleQueried.meanSeaLevel = true;
highResModuleQueried.geoidSeparation = true;
highResModuleQueried.horizontalAccuracy = true;
highResModuleQueried.verticalAccuracy = true;
if (_printDebug == true)
{
_debugSerial->print("Sec: ");
_debugSerial->print(((float)extractLong(4)) / 1000.0f);
_debugSerial->print(" ");
_debugSerial->print("LON: ");
_debugSerial->print(((float)(int32_t)extractLong(8)) / 10000000.0f);
_debugSerial->print(" ");
_debugSerial->print("LAT: ");
_debugSerial->print(((float)(int32_t)extractLong(12)) / 10000000.0f);
_debugSerial->print(" ");
_debugSerial->print("ELI M: ");
_debugSerial->print(((float)(int32_t)extractLong(16)) / 1000.0f);
_debugSerial->print(" ");
_debugSerial->print("MSL M: ");
_debugSerial->print(((float)(int32_t)extractLong(20)) / 1000.0f);
_debugSerial->print(" ");
_debugSerial->print("GEO: ");
_debugSerial->print(((float)(int32_t)extractLong(24)) / 1000.0f);
_debugSerial->print(" ");
_debugSerial->print("HA 2D M: ");
_debugSerial->print(((float)extractLong(28)) / 1000.0f);
_debugSerial->print(" ");
_debugSerial->print("VERT M: ");
_debugSerial->print(((float)extractLong(32)) / 1000.0f);
_debugSerial->print(" ");
}
}
break;
}
}
//Given a packet and payload, send everything including CRC bytes via I2C port
boolean SFE_UBLOX_GPS::sendCommand(ubxPacket outgoingUBX, uint16_t maxWait)
{
commandAck = false; //We're about to send a command. Begin waiting for ack.
calcChecksum(&outgoingUBX); //Sets checksum A and B bytes of the packet
if (_printDebug == true)
{
_debugSerial->print("Sending: ");
printPacket(&outgoingUBX);
}
if (commType == COMM_TYPE_I2C)
{
if (!sendI2cCommand(outgoingUBX, maxWait))
return false;
}
else if (commType == COMM_TYPE_SERIAL)
{
sendSerialCommand(outgoingUBX);
}
if (maxWait > 0)
{
//Give waitForResponse the cls/id to check for
return waitForResponse(outgoingUBX.cls, outgoingUBX.id, maxWait); //Wait for Ack response
}
return true;
}
boolean SFE_UBLOX_GPS::sendI2cCommand(ubxPacket outgoingUBX, uint16_t maxWait)
{
//Point at 0xFF data register
_i2cPort->beginTransmission((uint8_t)_gpsI2Caddress); //There is no register to write to, we just begin writing data bytes
_i2cPort->write(0xFF);
if (_i2cPort->endTransmission() != 0) //Don't release bus
return (false); //Sensor did not ACK
//Write header bytes
_i2cPort->beginTransmission((uint8_t)_gpsI2Caddress); //There is no register to write to, we just begin writing data bytes
_i2cPort->write(UBX_SYNCH_1); //μ - oh ublox, you're funny. I will call you micro-blox from now on.
_i2cPort->write(UBX_SYNCH_2); //b
_i2cPort->write(outgoingUBX.cls);
_i2cPort->write(outgoingUBX.id);
_i2cPort->write(outgoingUBX.len & 0xFF); //LSB
_i2cPort->write(outgoingUBX.len >> 8); //MSB
if (_i2cPort->endTransmission(false) != 0) //Do not release bus
return (false); //Sensor did not ACK
//Write payload. Limit the sends into 32 byte chunks
//This code based on ublox: https://forum.u-blox.com/index.php/20528/how-to-use-i2c-to-get-the-nmea-frames
uint16_t bytesToSend = outgoingUBX.len;
//"The number of data bytes must be at least 2 to properly distinguish
//from the write access to set the address counter in random read accesses."
uint16_t startSpot = 0;
while (bytesToSend > 1)
{
uint8_t len = bytesToSend;
if (len > I2C_BUFFER_LENGTH)
len = I2C_BUFFER_LENGTH;
_i2cPort->beginTransmission((uint8_t)_gpsI2Caddress);
//_i2cPort->write(outgoingUBX.payload, len); //Write a portion of the payload to the bus
for (uint16_t x = 0; x < len; x++)
_i2cPort->write(outgoingUBX.payload[startSpot + x]); //Write a portion of the payload to the bus
if (_i2cPort->endTransmission(false) != 0) //Don't release bus
return (false); //Sensor did not ACK
//*outgoingUBX.payload += len; //Move the pointer forward
startSpot += len; //Move the pointer forward
bytesToSend -= len;
}
//Write checksum
_i2cPort->beginTransmission((uint8_t)_gpsI2Caddress);
if (bytesToSend == 1)
_i2cPort->write(outgoingUBX.payload, 1);
_i2cPort->write(outgoingUBX.checksumA);
_i2cPort->write(outgoingUBX.checksumB);
//All done transmitting bytes. Release bus.
if (_i2cPort->endTransmission() != 0)
return (false); //Sensor did not ACK
return (true);
}
//Given a packet and payload, send everything including CRC bytesA via Serial port
void SFE_UBLOX_GPS::sendSerialCommand(ubxPacket outgoingUBX)
{
//Write header bytes
_serialPort->write(UBX_SYNCH_1); //μ - oh ublox, you're funny. I will call you micro-blox from now on.
_serialPort->write(UBX_SYNCH_2); //b
_serialPort->write(outgoingUBX.cls);
_serialPort->write(outgoingUBX.id);
_serialPort->write(outgoingUBX.len & 0xFF); //LSB
_serialPort->write(outgoingUBX.len >> 8); //MSB
//Write payload.
for (int i = 0; i < outgoingUBX.len; i++)
{
_serialPort->write(outgoingUBX.payload[i]);
}
//Write checksum
_serialPort->write(outgoingUBX.checksumA);
_serialPort->write(outgoingUBX.checksumB);
}
//Returns true if I2C device ack's
boolean SFE_UBLOX_GPS::isConnected()
{
if (commType == COMM_TYPE_I2C)
{
_i2cPort->beginTransmission((uint8_t)_gpsI2Caddress);
return _i2cPort->endTransmission() == 0;
}
else if (commType == COMM_TYPE_SERIAL)
{
// Query navigation rate to see whether we get a meaningful response
packetCfg.cls = UBX_CLASS_CFG;
packetCfg.id = UBX_CFG_RATE;
packetCfg.len = 0;
packetCfg.startingSpot = 0;
return sendCommand(packetCfg);
}
return false;
}
//Given a message, calc and store the two byte "8-Bit Fletcher" checksum over the entirety of the message
//This is called before we send a command message
void SFE_UBLOX_GPS::calcChecksum(ubxPacket *msg)
{
msg->checksumA = 0;
msg->checksumB = 0;
msg->checksumA += msg->cls;
msg->checksumB += msg->checksumA;
msg->checksumA += msg->id;
msg->checksumB += msg->checksumA;
msg->checksumA += (msg->len & 0xFF);
msg->checksumB += msg->checksumA;
msg->checksumA += (msg->len >> 8);
msg->checksumB += msg->checksumA;
for (uint16_t i = 0; i < msg->len; i++)
{
msg->checksumA += msg->payload[i];
msg->checksumB += msg->checksumA;
}
}
//Given a message and a byte, add to rolling "8-Bit Fletcher" checksum
//This is used when receiving messages from module
void SFE_UBLOX_GPS::addToChecksum(uint8_t incoming)
{
rollingChecksumA += incoming;
rollingChecksumB += rollingChecksumA;
}
//Pretty prints the current ubxPacket
void SFE_UBLOX_GPS::printPacket(ubxPacket *packet)
{
if (_printDebug == true)
{
_debugSerial->print("CLS:");
_debugSerial->print(packet->cls, HEX);
_debugSerial->print(" ID:");
_debugSerial->print(packet->id, HEX);
_debugSerial->print(" Len: 0x");
_debugSerial->print(packet->len, HEX);
_debugSerial->print(" Payload:");
for (int x = 0; x < packet->len; x++)
{
_debugSerial->print(" ");
_debugSerial->print(packet->payload[x], HEX);
}
_debugSerial->println();
}
}
//=-=-=-=-=-=-=-= Specific commands =-=-=-=-=-=-=-==-=-=-=-=-=-=-=
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-==-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
//Poll the module until and ack is received
boolean SFE_UBLOX_GPS::waitForResponse(uint8_t requestedClass, uint8_t requestedID, uint16_t maxTime)
{
commandAck = false; //Reset flag
packetCfg.valid = false; //This will go true when we receive a response to the packet we sent
unsigned long startTime = millis();
while (millis() - startTime < maxTime)
{
if (checkUblox() == true) //See if new data is available. Process bytes as they come in.
{
if (commandAck == true)
return (true); //If the packet we just sent was a CFG packet then we'll get an ACK
if (packetCfg.valid == true)
{
//Did we receive a config packet that matches the cls/id we requested?
if (packetCfg.cls == requestedClass && packetCfg.id == requestedID)
{
debugPrintln("CLS/ID match!");
return (true); //If the packet we just sent was a NAV packet then we'll just get data back
}
else
{
if (_printDebug == true)
{
_debugSerial->print("Packet didn't match CLS/ID");
printPacket(&packetCfg);
}
}
}
}
delay(1);
}
debugPrintln("waitForResponse timeout");
return (false);
}
//Save current configuration to flash and BBR (battery backed RAM)
//This still works but it is the old way of configuring ublox modules. See getVal and setVal for the new methods
boolean SFE_UBLOX_GPS::saveConfiguration(uint16_t maxWait)
{
packetCfg.cls = UBX_CLASS_CFG;
packetCfg.id = UBX_CFG_CFG;
packetCfg.len = 12;
packetCfg.startingSpot = 0;
//Clear packet payload
for (uint8_t x = 0; x < packetCfg.len; x++)
packetCfg.payload[x] = 0;
packetCfg.payload[4] = 0xFF; //Set any bit in the saveMask field to save current config to Flash and BBR
if (sendCommand(packetCfg, maxWait) == false)
return (false); //If command send fails then bail
return (true);
}
//Reset module to factory defaults
//This still works but it is the old way of configuring ublox modules. See getVal and setVal for the new methods
boolean SFE_UBLOX_GPS::factoryDefault(uint16_t maxWait)
{
packetCfg.cls = UBX_CLASS_CFG;
packetCfg.id = UBX_CFG_CFG;
packetCfg.len = 12;
packetCfg.startingSpot = 0;
//Clear packet payload
for (uint8_t x = 0; x < packetCfg.len; x++)
packetCfg.payload[x] = 0;
packetCfg.payload[0] = 0xFF; //Set any bit in the clearMask field to clear saved config
packetCfg.payload[8] = 0xFF; //Set any bit in the loadMask field to discard current config and rebuild from lower non-volatile memory layers
if (sendCommand(packetCfg, maxWait) == false)
return (false); //If command send fails then bail
return (true);
}
//Given a group, ID and size, return the value of this config spot
//The 32-bit key is put together from group/ID/size. See other getVal to send key directly.
//Configuration of modern Ublox modules is now done via getVal/setVal/delVal, ie protocol v27 and above found on ZED-F9P
uint8_t SFE_UBLOX_GPS::getVal8(uint16_t group, uint16_t id, uint8_t size, uint8_t layer, uint16_t maxWait)
{
//Create key
uint32_t key = 0;
key |= (uint32_t)id;
key |= (uint32_t)group << 16;
key |= (uint32_t)size << 28;
if (_printDebug == true)
{
_debugSerial->print("key: 0x");
_debugSerial->print(key, HEX);
_debugSerial->println();
}
return getVal8(key, layer, maxWait);
}
//Given a key, return its value
//This function takes a full 32-bit key
//Default layer is BBR
//Configuration of modern Ublox modules is now done via getVal/setVal/delVal, ie protocol v27 and above found on ZED-F9P
uint8_t SFE_UBLOX_GPS::getVal8(uint32_t key, uint8_t layer, uint16_t maxWait)
{
packetCfg.cls = UBX_CLASS_CFG;
packetCfg.id = UBX_CFG_VALGET;
packetCfg.len = 4 + 4 * 1; //While multiple keys are allowed, we will send only one key at a time
packetCfg.startingSpot = 0;
//Clear packet payload
for (uint8_t x = 0; x < packetCfg.len; x++)
packetCfg.payload[x] = 0;
payloadCfg[0] = 0; //Message Version - set to 0
payloadCfg[1] = layer; //By default we ask for the BBR layer
//Load key into outgoing payload
payloadCfg[4] = key >> 8 * 0; //Key LSB
payloadCfg[5] = key >> 8 * 1;
payloadCfg[6] = key >> 8 * 2;
payloadCfg[7] = key >> 8 * 3;
if (_printDebug == true)
{
_debugSerial->print("key: 0x");
_debugSerial->print(key, HEX);
_debugSerial->println();
}
//Send VALGET command with this key
if (sendCommand(packetCfg, maxWait) == false)
return (false); //If command send fails then bail
//Verify the response is the correct length as compared to what the user called (did the module respond with 8-bits but the user called getVal32?)
//Response is 8 bytes plus cfg data