-
Notifications
You must be signed in to change notification settings - Fork 416
/
Copy pathSX126x.cpp
2356 lines (1929 loc) · 80.8 KB
/
SX126x.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
#include "SX126x.h"
#include <string.h>
#include <math.h>
#if !RADIOLIB_EXCLUDE_SX126X
SX126x::SX126x(Module* mod) : PhysicalLayer(RADIOLIB_SX126X_FREQUENCY_STEP_SIZE, RADIOLIB_SX126X_MAX_PACKET_LENGTH) {
this->mod = mod;
this->XTAL = false;
this->standbyXOSC = false;
this->irqMap[RADIOLIB_IRQ_TX_DONE] = RADIOLIB_SX126X_IRQ_TX_DONE;
this->irqMap[RADIOLIB_IRQ_RX_DONE] = RADIOLIB_SX126X_IRQ_RX_DONE;
this->irqMap[RADIOLIB_IRQ_PREAMBLE_DETECTED] = RADIOLIB_SX126X_IRQ_PREAMBLE_DETECTED;
this->irqMap[RADIOLIB_IRQ_SYNC_WORD_VALID] = RADIOLIB_SX126X_IRQ_SYNC_WORD_VALID;
this->irqMap[RADIOLIB_IRQ_HEADER_VALID] = RADIOLIB_SX126X_IRQ_HEADER_VALID;
this->irqMap[RADIOLIB_IRQ_HEADER_ERR] = RADIOLIB_SX126X_IRQ_HEADER_ERR;
this->irqMap[RADIOLIB_IRQ_CRC_ERR] = RADIOLIB_SX126X_IRQ_CRC_ERR;
this->irqMap[RADIOLIB_IRQ_CAD_DONE] = RADIOLIB_SX126X_IRQ_CAD_DONE;
this->irqMap[RADIOLIB_IRQ_CAD_DETECTED] = RADIOLIB_SX126X_IRQ_CAD_DETECTED;
this->irqMap[RADIOLIB_IRQ_TIMEOUT] = RADIOLIB_SX126X_IRQ_TIMEOUT;
}
int16_t SX126x::begin(uint8_t cr, uint8_t syncWord, uint16_t preambleLength, float tcxoVoltage, bool useRegulatorLDO) {
// BW in kHz and SF are required in order to calculate LDRO for setModulationParams
// set the defaults, this will get overwritten later anyway
this->bandwidthKhz = 500.0;
this->spreadingFactor = 9;
// initialize configuration variables (will be overwritten during public settings configuration)
this->bandwidth = RADIOLIB_SX126X_LORA_BW_500_0; // initialized to 500 kHz, since lower values will interfere with LLCC68
this->codingRate = RADIOLIB_SX126X_LORA_CR_4_7;
this->ldrOptimize = 0x00;
this->crcTypeLoRa = RADIOLIB_SX126X_LORA_CRC_ON;
this->preambleLengthLoRa = preambleLength;
this->tcxoDelay = 0;
this->headerType = RADIOLIB_SX126X_LORA_HEADER_EXPLICIT;
this->implicitLen = 0xFF;
// set module properties and perform initial setup
int16_t state = this->modSetup(tcxoVoltage, useRegulatorLDO, RADIOLIB_SX126X_PACKET_TYPE_LORA);
RADIOLIB_ASSERT(state);
// configure publicly accessible settings
state = setCodingRate(cr);
RADIOLIB_ASSERT(state);
state = setSyncWord(syncWord);
RADIOLIB_ASSERT(state);
state = setPreambleLength(preambleLength);
RADIOLIB_ASSERT(state);
// set publicly accessible settings that are not a part of begin method
state = setCurrentLimit(60.0);
RADIOLIB_ASSERT(state);
state = setDio2AsRfSwitch(true);
RADIOLIB_ASSERT(state);
state = setCRC(2);
RADIOLIB_ASSERT(state);
state = invertIQ(false);
RADIOLIB_ASSERT(state);
return(state);
}
int16_t SX126x::beginFSK(float br, float freqDev, float rxBw, uint16_t preambleLength, float tcxoVoltage, bool useRegulatorLDO) {
// initialize configuration variables (will be overwritten during public settings configuration)
this->bitRate = 21333; // 48.0 kbps
this->frequencyDev = 52428; // 50.0 kHz
this->rxBandwidth = RADIOLIB_SX126X_GFSK_RX_BW_156_2;
this->rxBandwidthKhz = 156.2;
this->pulseShape = RADIOLIB_SX126X_GFSK_FILTER_GAUSS_0_5;
this->crcTypeFSK = RADIOLIB_SX126X_GFSK_CRC_2_BYTE_INV; // CCITT CRC configuration
this->preambleLengthFSK = preambleLength;
// set module properties and perform initial setup
int16_t state = this->modSetup(tcxoVoltage, useRegulatorLDO, RADIOLIB_SX126X_PACKET_TYPE_GFSK);
RADIOLIB_ASSERT(state);
// configure publicly accessible settings
state = setBitRate(br);
RADIOLIB_ASSERT(state);
state = setFrequencyDeviation(freqDev);
RADIOLIB_ASSERT(state);
state = setRxBandwidth(rxBw);
RADIOLIB_ASSERT(state);
state = setCurrentLimit(60.0);
RADIOLIB_ASSERT(state);
state = setPreambleLength(preambleLength);
RADIOLIB_ASSERT(state);
// set publicly accessible settings that are not a part of begin method
uint8_t sync[] = {0x12, 0xAD};
state = setSyncWord(sync, 2);
RADIOLIB_ASSERT(state);
state = setDataShaping(RADIOLIB_SHAPING_NONE);
RADIOLIB_ASSERT(state);
state = setEncoding(RADIOLIB_ENCODING_NRZ);
RADIOLIB_ASSERT(state);
state = variablePacketLengthMode(RADIOLIB_SX126X_MAX_PACKET_LENGTH);
RADIOLIB_ASSERT(state);
state = setCRC(2);
RADIOLIB_ASSERT(state);
state = setDio2AsRfSwitch(true);
RADIOLIB_ASSERT(state);
return(state);
}
int16_t SX126x::beginLRFHSS(uint8_t bw, uint8_t cr, bool narrowGrid, float tcxoVoltage, bool useRegulatorLDO) {
this->lrFhssGridNonFcc = narrowGrid;
// set module properties and perform initial setup
int16_t state = this->modSetup(tcxoVoltage, useRegulatorLDO, RADIOLIB_SX126X_PACKET_TYPE_LR_FHSS);
RADIOLIB_ASSERT(state);
// set publicly accessible settings that are not a part of begin method
state = setCurrentLimit(60.0);
RADIOLIB_ASSERT(state);
state = setDio2AsRfSwitch(true);
RADIOLIB_ASSERT(state);
// set all packet params to 0 (packet engine is disabled in LR-FHSS mode)
state = setPacketParamsFSK(0, 0, 0, 0, 0, 0, 0, 0);
RADIOLIB_ASSERT(state);
// set bit rate
this->rxBandwidth = 0;
this->frequencyDev = 0;
this->pulseShape = RADIOLIB_SX126X_GFSK_FILTER_GAUSS_1;
state = setBitRate(0.48828125f);
RADIOLIB_ASSERT(state);
return(setLrFhssConfig(bw, cr));
}
int16_t SX126x::setLrFhssConfig(uint8_t bw, uint8_t cr, uint8_t hdrCount, uint16_t hopSeqId) {
// check and cache all parameters
RADIOLIB_CHECK_RANGE((int8_t)cr, (int8_t)RADIOLIB_SX126X_LR_FHSS_CR_5_6, (int8_t)RADIOLIB_SX126X_LR_FHSS_CR_1_3, RADIOLIB_ERR_INVALID_CODING_RATE);
this->lrFhssCr = cr;
RADIOLIB_CHECK_RANGE((int8_t)bw, (int8_t)RADIOLIB_SX126X_LR_FHSS_BW_39_06, (int8_t)RADIOLIB_SX126X_LR_FHSS_BW_1574_2, RADIOLIB_ERR_INVALID_BANDWIDTH);
this->lrFhssBw = bw;
RADIOLIB_CHECK_RANGE(hdrCount, 1, 4, RADIOLIB_ERR_INVALID_BIT_RANGE);
this->lrFhssHdrCount = hdrCount;
RADIOLIB_CHECK_RANGE((int16_t)hopSeqId, (int16_t)0x000, (int16_t)0x1FF, RADIOLIB_ERR_INVALID_DATA_SHAPING);
this->lrFhssHopSeqId = hopSeqId;
return(RADIOLIB_ERR_NONE);
}
int16_t SX126x::reset(bool verify) {
// run the reset sequence
this->mod->hal->pinMode(this->mod->getRst(), this->mod->hal->GpioModeOutput);
this->mod->hal->digitalWrite(this->mod->getRst(), this->mod->hal->GpioLevelLow);
this->mod->hal->delay(1);
this->mod->hal->digitalWrite(this->mod->getRst(), this->mod->hal->GpioLevelHigh);
// return immediately when verification is disabled
if(!verify) {
return(RADIOLIB_ERR_NONE);
}
// set mode to standby - SX126x often refuses first few commands after reset
RadioLibTime_t start = this->mod->hal->millis();
while(true) {
// try to set mode to standby
int16_t state = standby();
if(state == RADIOLIB_ERR_NONE) {
// standby command successful
return(RADIOLIB_ERR_NONE);
}
// standby command failed, check timeout and try again
if(this->mod->hal->millis() - start >= 1000) {
// timed out, possibly incorrect wiring
return(state);
}
// wait a bit to not spam the module
this->mod->hal->delay(10);
}
}
int16_t SX126x::transmit(const uint8_t* data, size_t len, uint8_t addr) {
// set mode to standby
int16_t state = standby();
RADIOLIB_ASSERT(state);
// check packet length
if(len > RADIOLIB_SX126X_MAX_PACKET_LENGTH) {
return(RADIOLIB_ERR_PACKET_TOO_LONG);
}
// calculate timeout in ms (5ms + 500 % of expected time-on-air)
RadioLibTime_t timeout = 5 + (getTimeOnAir(len) * 5) / 1000;
RADIOLIB_DEBUG_BASIC_PRINTLN("Timeout in %lu ms", timeout);
// start transmission
state = startTransmit(data, len, addr);
RADIOLIB_ASSERT(state);
// wait for packet transmission or timeout
uint8_t modem = getPacketType();
RadioLibTime_t start = this->mod->hal->millis();
while(true) {
// yield for multi-threaded platforms
this->mod->hal->yield();
// check timeout
if(this->mod->hal->millis() - start > timeout) {
finishTransmit();
return(RADIOLIB_ERR_TX_TIMEOUT);
}
// poll the interrupt pin
if(this->mod->hal->digitalRead(this->mod->getIrq())) {
// in LoRa or GFSK, only Tx done interrupt is enabled
if(modem != RADIOLIB_SX126X_PACKET_TYPE_LR_FHSS) {
break;
}
// in LR-FHSS, IRQ signals both Tx done as frequency hop request
if(this->getIrqFlags() & RADIOLIB_SX126X_IRQ_TX_DONE) {
break;
} else {
// handle frequency hop
this->setLRFHSSHop(this->lrFhssHopNum % 16);
clearIrqStatus();
}
}
}
// update data rate
RadioLibTime_t elapsed = this->mod->hal->millis() - start;
this->dataRateMeasured = (len*8.0f)/((float)elapsed/1000.0f);
return(finishTransmit());
}
int16_t SX126x::receive(uint8_t* data, size_t len) {
// set mode to standby
int16_t state = standby();
RADIOLIB_ASSERT(state);
RadioLibTime_t timeout = 0;
// get currently active modem
uint8_t modem = getPacketType();
if(modem == RADIOLIB_SX126X_PACKET_TYPE_LORA) {
// calculate timeout (100 LoRa symbols, the default for SX127x series)
float symbolLength = (float)(uint32_t(1) << this->spreadingFactor) / (float)this->bandwidthKhz;
timeout = (RadioLibTime_t)(symbolLength * 100.0f);
} else if(modem == RADIOLIB_SX126X_PACKET_TYPE_GFSK) {
// calculate timeout (500 % of expected time-one-air)
size_t maxLen = len;
if(len == 0) {
maxLen = 0xFF;
}
float brBps = (RADIOLIB_SX126X_CRYSTAL_FREQ * 1000000.0f * 32.0f) / (float)this->bitRate;
timeout = (RadioLibTime_t)(((maxLen * 8.0f) / brBps) * 1000.0f * 5.0f);
} else {
return(RADIOLIB_ERR_UNKNOWN);
}
RADIOLIB_DEBUG_BASIC_PRINTLN("Timeout in %lu ms", timeout);
// start reception
uint32_t timeoutValue = (uint32_t)(((float)timeout * 1000.0f) / 15.625f);
state = startReceive(timeoutValue);
RADIOLIB_ASSERT(state);
// wait for packet reception or timeout
bool softTimeout = false;
RadioLibTime_t start = this->mod->hal->millis();
while(!this->mod->hal->digitalRead(this->mod->getIrq())) {
this->mod->hal->yield();
// safety check, the timeout should be done by the radio
if(this->mod->hal->millis() - start > timeout) {
softTimeout = true;
break;
}
}
// if it was a timeout, this will return an error code
state = standby();
if((state != RADIOLIB_ERR_NONE) && (state != RADIOLIB_ERR_SPI_CMD_TIMEOUT)) {
return(state);
}
// check whether this was a timeout or not
if((getIrqFlags() & RADIOLIB_SX126X_IRQ_TIMEOUT) || softTimeout) {
standby();
fixImplicitTimeout();
clearIrqStatus();
return(RADIOLIB_ERR_RX_TIMEOUT);
}
// fix timeout in implicit LoRa mode
if(((this->headerType == RADIOLIB_SX126X_LORA_HEADER_IMPLICIT) && (getPacketType() == RADIOLIB_SX126X_PACKET_TYPE_LORA))) {
state = fixImplicitTimeout();
RADIOLIB_ASSERT(state);
}
// read the received data
return(readData(data, len));
}
int16_t SX126x::transmitDirect(uint32_t frf) {
// set RF switch (if present)
this->mod->setRfSwitchState(this->txMode);
// user requested to start transmitting immediately (required for RTTY)
int16_t state = RADIOLIB_ERR_NONE;
if(frf != 0) {
state = setRfFrequency(frf);
}
RADIOLIB_ASSERT(state);
// direct mode activation intentionally skipped here, as it seems to lead to much worse results
const uint8_t data[] = { RADIOLIB_SX126X_CMD_NOP };
return(this->mod->SPIwriteStream(RADIOLIB_SX126X_CMD_SET_TX_CONTINUOUS_WAVE, data, 1));
}
int16_t SX126x::receiveDirect() {
// set RF switch (if present)
this->mod->setRfSwitchState(Module::MODE_RX);
// SX126x is unable to output received data directly
return(RADIOLIB_ERR_UNKNOWN);
}
int16_t SX126x::directMode() {
// check modem
if(getPacketType() != RADIOLIB_SX126X_PACKET_TYPE_GFSK) {
return(RADIOLIB_ERR_WRONG_MODEM);
}
// set mode to standby
int16_t state = standby();
RADIOLIB_ASSERT(state);
// disable DIO2 RF switch
state = setDio2AsRfSwitch(false);
RADIOLIB_ASSERT(state);
// set DIO2 to clock output and DIO3 to data input
// this is done exclusively by writing magic values to even more magic registers
state = this->mod->SPIsetRegValue(RADIOLIB_SX126X_REG_TX_BITBANG_ENABLE_1, RADIOLIB_SX126X_TX_BITBANG_1_ENABLED, 6, 4);
RADIOLIB_ASSERT(state);
state = this->mod->SPIsetRegValue(RADIOLIB_SX126X_REG_TX_BITBANG_ENABLE_0, RADIOLIB_SX126X_TX_BITBANG_0_ENABLED, 3, 0);
RADIOLIB_ASSERT(state);
state = this->mod->SPIsetRegValue(RADIOLIB_SX126X_REG_DIOX_OUT_ENABLE, RADIOLIB_SX126X_DIO3_OUT_DISABLED, 3, 3);
RADIOLIB_ASSERT(state);
state = this->mod->SPIsetRegValue(RADIOLIB_SX126X_REG_DIOX_IN_ENABLE, RADIOLIB_SX126X_DIO3_IN_ENABLED, 3, 3);
RADIOLIB_ASSERT(state);
// enable TxDone interrupt
state = setDioIrqParams(RADIOLIB_SX126X_IRQ_TX_DONE, RADIOLIB_SX126X_IRQ_TX_DONE);
RADIOLIB_ASSERT(state);
// set preamble length to the maximum to prevent SX126x from exiting Tx mode for a while
state = setPreambleLength(0xFFFF);
RADIOLIB_ASSERT(state);
return(state);
}
int16_t SX126x::packetMode() {
// set mode to standby
int16_t state = standby();
RADIOLIB_ASSERT(state);
// set preamble length to the default
state = setPreambleLength(16);
RADIOLIB_ASSERT(state);
// disable TxDone interrupt
state = setDioIrqParams(RADIOLIB_SX126X_IRQ_NONE, RADIOLIB_SX126X_IRQ_NONE);
RADIOLIB_ASSERT(state);
// restore the magic registers
state = this->mod->SPIsetRegValue(RADIOLIB_SX126X_REG_DIOX_IN_ENABLE, RADIOLIB_SX126X_DIO3_IN_DISABLED, 3, 3);
RADIOLIB_ASSERT(state);
state = this->mod->SPIsetRegValue(RADIOLIB_SX126X_REG_DIOX_OUT_ENABLE, RADIOLIB_SX126X_DIO3_OUT_ENABLED, 3, 3);
RADIOLIB_ASSERT(state);
state = this->mod->SPIsetRegValue(RADIOLIB_SX126X_REG_TX_BITBANG_ENABLE_0, RADIOLIB_SX126X_TX_BITBANG_0_DISABLED, 3, 0);
RADIOLIB_ASSERT(state);
state = this->mod->SPIsetRegValue(RADIOLIB_SX126X_REG_TX_BITBANG_ENABLE_1, RADIOLIB_SX126X_TX_BITBANG_1_DISABLED, 6, 4);
RADIOLIB_ASSERT(state);
// enable DIO2 RF switch
state = setDio2AsRfSwitch(true);
RADIOLIB_ASSERT(state);
return(state);
}
int16_t SX126x::scanChannel() {
ChannelScanConfig_t cfg = {
.cad = {
.symNum = RADIOLIB_SX126X_CAD_PARAM_DEFAULT,
.detPeak = RADIOLIB_SX126X_CAD_PARAM_DEFAULT,
.detMin = RADIOLIB_SX126X_CAD_PARAM_DEFAULT,
.exitMode = RADIOLIB_SX126X_CAD_PARAM_DEFAULT,
.timeout = 0,
.irqFlags = RADIOLIB_IRQ_CAD_DEFAULT_FLAGS,
.irqMask = RADIOLIB_IRQ_CAD_DEFAULT_MASK,
},
};
return(this->scanChannel(cfg));
}
int16_t SX126x::scanChannel(const ChannelScanConfig_t &config) {
// set mode to CAD
int state = startChannelScan(config);
RADIOLIB_ASSERT(state);
// wait for channel activity detected or timeout
while(!this->mod->hal->digitalRead(this->mod->getIrq())) {
this->mod->hal->yield();
}
// check CAD result
return(getChannelScanResult());
}
int16_t SX126x::sleep() {
return(SX126x::sleep(true));
}
int16_t SX126x::sleep(bool retainConfig) {
// set RF switch (if present)
this->mod->setRfSwitchState(Module::MODE_IDLE);
uint8_t sleepMode = RADIOLIB_SX126X_SLEEP_START_WARM | RADIOLIB_SX126X_SLEEP_RTC_OFF;
if(!retainConfig) {
sleepMode = RADIOLIB_SX126X_SLEEP_START_COLD | RADIOLIB_SX126X_SLEEP_RTC_OFF;
}
int16_t state = this->mod->SPIwriteStream(RADIOLIB_SX126X_CMD_SET_SLEEP, &sleepMode, 1, false, false);
// wait for SX126x to safely enter sleep mode
this->mod->hal->delay(1);
return(state);
}
int16_t SX126x::standby() {
return(SX126x::standby(this->standbyXOSC ? RADIOLIB_SX126X_STANDBY_XOSC : RADIOLIB_SX126X_STANDBY_RC));
}
int16_t SX126x::standby(uint8_t mode, bool wakeup) {
// set RF switch (if present)
this->mod->setRfSwitchState(Module::MODE_IDLE);
if(wakeup) {
// send a NOP command - this pulls the NSS low to exit the sleep mode,
// while preventing interference with possible other SPI transactions
// see https://github.com/jgromes/RadioLib/discussions/1364
(void)this->mod->SPIwriteStream((uint16_t)RADIOLIB_SX126X_CMD_NOP, NULL, 0, false, false);
}
const uint8_t data[] = { mode };
return(this->mod->SPIwriteStream(RADIOLIB_SX126X_CMD_SET_STANDBY, data, 1));
}
void SX126x::setDio1Action(void (*func)(void)) {
this->mod->hal->attachInterrupt(this->mod->hal->pinToInterrupt(this->mod->getIrq()), func, this->mod->hal->GpioInterruptRising);
}
void SX126x::clearDio1Action() {
this->mod->hal->detachInterrupt(this->mod->hal->pinToInterrupt(this->mod->getIrq()));
}
void SX126x::setPacketReceivedAction(void (*func)(void)) {
this->setDio1Action(func);
}
void SX126x::clearPacketReceivedAction() {
this->clearDio1Action();
}
void SX126x::setPacketSentAction(void (*func)(void)) {
this->setDio1Action(func);
}
void SX126x::clearPacketSentAction() {
this->clearDio1Action();
}
void SX126x::setChannelScanAction(void (*func)(void)) {
this->setDio1Action(func);
}
void SX126x::clearChannelScanAction() {
this->clearDio1Action();
}
int16_t SX126x::startTransmit(const uint8_t* data, size_t len, uint8_t addr) {
(void)addr;
// check packet length
if(len > RADIOLIB_SX126X_MAX_PACKET_LENGTH) {
return(RADIOLIB_ERR_PACKET_TOO_LONG);
}
// maximum packet length is decreased by 1 when address filtering is active
if((RADIOLIB_SX126X_GFSK_ADDRESS_FILT_OFF != RADIOLIB_SX126X_GFSK_ADDRESS_FILT_OFF) && (len > RADIOLIB_SX126X_MAX_PACKET_LENGTH - 1)) {
return(RADIOLIB_ERR_PACKET_TOO_LONG);
}
// set packet Length
int16_t state = RADIOLIB_ERR_NONE;
uint8_t modem = getPacketType();
if(modem == RADIOLIB_SX126X_PACKET_TYPE_LORA) {
state = setPacketParams(this->preambleLengthLoRa, this->crcTypeLoRa, len, this->headerType, this->invertIQEnabled);
} else if(modem == RADIOLIB_SX126X_PACKET_TYPE_GFSK) {
state = setPacketParamsFSK(this->preambleLengthFSK, this->preambleDetLength, this->crcTypeFSK, this->syncWordLength, RADIOLIB_SX126X_GFSK_ADDRESS_FILT_OFF, this->whitening, this->packetType, len);
} else if(modem != RADIOLIB_SX126X_PACKET_TYPE_LR_FHSS) {
return(RADIOLIB_ERR_UNKNOWN);
}
RADIOLIB_ASSERT(state);
// set DIO mapping
if(modem != RADIOLIB_SX126X_PACKET_TYPE_LR_FHSS) {
state = setDioIrqParams(RADIOLIB_SX126X_IRQ_TX_DONE | RADIOLIB_SX126X_IRQ_TIMEOUT, RADIOLIB_SX126X_IRQ_TX_DONE);
} else {
state = setDioIrqParams(RADIOLIB_SX126X_IRQ_TX_DONE | RADIOLIB_SX126X_IRQ_LR_FHSS_HOP, RADIOLIB_SX126X_IRQ_TX_DONE | RADIOLIB_SX126X_IRQ_LR_FHSS_HOP);
}
RADIOLIB_ASSERT(state);
// set buffer pointers
state = setBufferBaseAddress();
RADIOLIB_ASSERT(state);
// write packet to buffer
if(modem != RADIOLIB_SX126X_PACKET_TYPE_LR_FHSS) {
state = writeBuffer(const_cast<uint8_t*>(data), len);
} else {
// first, reset the LR-FHSS state machine
state = resetLRFHSS();
RADIOLIB_ASSERT(state);
// skip hopping for the first 4 - lrFhssHdrCount blocks
for(int i = 0; i < 4 - this->lrFhssHdrCount; ++i ) {
stepLRFHSS();
}
// in LR-FHSS mode, we need to build the entire packet manually
uint8_t frame[RADIOLIB_SX126X_MAX_PACKET_LENGTH] = { 0 };
size_t frameLen = 0;
this->lrFhssFrameBitsRem = 0;
this->lrFhssFrameHopsRem = 0;
this->lrFhssHopNum = 0;
state = buildLRFHSSPacket(const_cast<uint8_t*>(data), len, frame, &frameLen, &this->lrFhssFrameBitsRem, &this->lrFhssFrameHopsRem);
RADIOLIB_ASSERT(state);
// FIXME check max len for FHSS
state = writeBuffer(frame, frameLen);
RADIOLIB_ASSERT(state);
// activate hopping
uint8_t hopCfg[] = { RADIOLIB_SX126X_HOPPING_ENABLED, (uint8_t)frameLen, (uint8_t)this->lrFhssFrameHopsRem };
state = writeRegister(RADIOLIB_SX126X_REG_HOPPING_ENABLE, hopCfg, 3);
RADIOLIB_ASSERT(state);
// write the initial hopping table
uint8_t initHops = this->lrFhssFrameHopsRem;
if(initHops > 16) {
initHops = 16;
};
for(size_t i = 0; i < initHops; i++) {
// set the hop frequency and symbols
state = this->setLRFHSSHop(i);
RADIOLIB_ASSERT(state);
}
}
RADIOLIB_ASSERT(state);
// clear interrupt flags
state = clearIrqStatus();
RADIOLIB_ASSERT(state);
// fix sensitivity
state = fixSensitivity();
RADIOLIB_ASSERT(state);
// set RF switch (if present)
this->mod->setRfSwitchState(this->txMode);
// start transmission
state = setTx(RADIOLIB_SX126X_TX_TIMEOUT_NONE);
RADIOLIB_ASSERT(state);
// wait for BUSY to go low (= PA ramp up done)
while(this->mod->hal->digitalRead(this->mod->getGpio())) {
this->mod->hal->yield();
}
return(state);
}
int16_t SX126x::finishTransmit() {
// clear interrupt flags
int16_t state = clearIrqStatus();
RADIOLIB_ASSERT(state);
// set mode to standby to disable transmitter/RF switch
return(standby());
}
int16_t SX126x::startReceive() {
return(this->startReceive(RADIOLIB_SX126X_RX_TIMEOUT_INF, RADIOLIB_IRQ_RX_DEFAULT_FLAGS, RADIOLIB_IRQ_RX_DEFAULT_MASK, 0));
}
int16_t SX126x::startReceive(uint32_t timeout, RadioLibIrqFlags_t irqFlags, RadioLibIrqFlags_t irqMask, size_t len) {
// in implicit header mode, use the provided length if it is nonzero
// otherwise we trust the user has previously set the payload length manually
if((this->headerType == RADIOLIB_SX126X_LORA_HEADER_IMPLICIT) && (len != 0)) {
this->implicitLen = len;
}
int16_t state = startReceiveCommon(timeout, irqFlags, irqMask);
RADIOLIB_ASSERT(state);
// set RF switch (if present)
this->mod->setRfSwitchState(Module::MODE_RX);
// set mode to receive
state = setRx(timeout);
return(state);
}
int16_t SX126x::startReceiveDutyCycle(uint32_t rxPeriod, uint32_t sleepPeriod, RadioLibIrqFlags_t irqFlags, RadioLibIrqFlags_t irqMask) {
// datasheet claims time to go to sleep is ~500us, same to wake up, compensate for that with 1 ms + TCXO delay
uint32_t transitionTime = this->tcxoDelay + 1000;
sleepPeriod -= transitionTime;
// divide by 15.625
uint32_t rxPeriodRaw = (rxPeriod * 8) / 125;
uint32_t sleepPeriodRaw = (sleepPeriod * 8) / 125;
// check 24 bit limit and zero value (likely not intended)
if((rxPeriodRaw & 0xFF000000) || (rxPeriodRaw == 0)) {
return(RADIOLIB_ERR_INVALID_RX_PERIOD);
}
// this check of the high byte also catches underflow when we subtracted transitionTime
if((sleepPeriodRaw & 0xFF000000) || (sleepPeriodRaw == 0)) {
return(RADIOLIB_ERR_INVALID_SLEEP_PERIOD);
}
int16_t state = startReceiveCommon(RADIOLIB_SX126X_RX_TIMEOUT_INF, irqFlags, irqMask);
RADIOLIB_ASSERT(state);
const uint8_t data[6] = {(uint8_t)((rxPeriodRaw >> 16) & 0xFF), (uint8_t)((rxPeriodRaw >> 8) & 0xFF), (uint8_t)(rxPeriodRaw & 0xFF),
(uint8_t)((sleepPeriodRaw >> 16) & 0xFF), (uint8_t)((sleepPeriodRaw >> 8) & 0xFF), (uint8_t)(sleepPeriodRaw & 0xFF)};
return(this->mod->SPIwriteStream(RADIOLIB_SX126X_CMD_SET_RX_DUTY_CYCLE, data, 6));
}
int16_t SX126x::startReceiveDutyCycleAuto(uint16_t senderPreambleLength, uint16_t minSymbols, RadioLibIrqFlags_t irqFlags, RadioLibIrqFlags_t irqMask) {
if(senderPreambleLength == 0) {
senderPreambleLength = this->preambleLengthLoRa;
}
// worst case is that the sender starts transmitting when we're just less than minSymbols from going back to sleep.
// in this case, we don't catch minSymbols before going to sleep,
// so we must be awake for at least that long before the sender stops transmitting.
uint16_t sleepSymbols = senderPreambleLength - 2 * minSymbols;
// if we're not to sleep at all, just use the standard startReceive.
if(2 * minSymbols > senderPreambleLength) {
return(startReceive(RADIOLIB_SX126X_RX_TIMEOUT_INF, irqFlags, irqMask));
}
uint32_t symbolLength = ((uint32_t)(10 * 1000) << this->spreadingFactor) / (10 * this->bandwidthKhz);
uint32_t sleepPeriod = symbolLength * sleepSymbols;
RADIOLIB_DEBUG_BASIC_PRINTLN("Auto sleep period: %lu", (long unsigned int)sleepPeriod);
// when the unit detects a preamble, it starts a timer that will timeout if it doesn't receive a header in time.
// the duration is sleepPeriod + 2 * wakePeriod.
// The sleepPeriod doesn't take into account shutdown and startup time for the unit (~1ms)
// We need to ensure that the timeout is longer than senderPreambleLength.
// So we must satisfy: wakePeriod > (preamblePeriod - (sleepPeriod - 1000)) / 2. (A)
// we also need to ensure the unit is awake to see at least minSymbols. (B)
uint32_t wakePeriod = RADIOLIB_MAX(
(symbolLength * (senderPreambleLength + 1) - (sleepPeriod - 1000)) / 2, // (A)
symbolLength * (minSymbols + 1)); //(B)
RADIOLIB_DEBUG_BASIC_PRINTLN("Auto wake period: %lu", (long unsigned int)wakePeriod);
// If our sleep period is shorter than our transition time, just use the standard startReceive
if(sleepPeriod < this->tcxoDelay + 1016) {
return(startReceive(RADIOLIB_SX126X_RX_TIMEOUT_INF, irqFlags, irqMask));
}
return(startReceiveDutyCycle(wakePeriod, sleepPeriod, irqFlags, irqMask));
}
int16_t SX126x::startReceiveCommon(uint32_t timeout, RadioLibIrqFlags_t irqFlags, RadioLibIrqFlags_t irqMask) {
// ensure we are in standby
int16_t state = standby();
RADIOLIB_ASSERT(state);
// set DIO mapping
if(timeout != RADIOLIB_SX126X_RX_TIMEOUT_INF) {
irqMask |= (1UL << RADIOLIB_IRQ_TIMEOUT);
}
state = setDioIrqParams(getIrqMapped(irqFlags), getIrqMapped(irqMask));
RADIOLIB_ASSERT(state);
// set buffer pointers
state = setBufferBaseAddress();
RADIOLIB_ASSERT(state);
// clear interrupt flags
state = clearIrqStatus();
// restore original packet length
uint8_t modem = getPacketType();
if(modem == RADIOLIB_SX126X_PACKET_TYPE_LORA) {
state = setPacketParams(this->preambleLengthLoRa, this->crcTypeLoRa, this->implicitLen, this->headerType, this->invertIQEnabled);
} else if(modem == RADIOLIB_SX126X_PACKET_TYPE_GFSK) {
state = setPacketParamsFSK(this->preambleLengthFSK, this->preambleDetLength, this->crcTypeFSK, this->syncWordLength, RADIOLIB_SX126X_GFSK_ADDRESS_FILT_OFF, this->whitening, this->packetType);
} else {
return(RADIOLIB_ERR_UNKNOWN);
}
return(state);
}
int16_t SX126x::readData(uint8_t* data, size_t len) {
// this method may get called from receive() after Rx timeout
// if that's the case, the first call will return "SPI command timeout error"
// check the IRQ to be sure this really originated from timeout event
int16_t state = this->mod->SPIcheckStream();
uint16_t irq = getIrqFlags();
if((state == RADIOLIB_ERR_SPI_CMD_TIMEOUT) && (irq & RADIOLIB_SX126X_IRQ_TIMEOUT)) {
// this is definitely Rx timeout
return(RADIOLIB_ERR_RX_TIMEOUT);
}
RADIOLIB_ASSERT(state);
// check integrity CRC
int16_t crcState = RADIOLIB_ERR_NONE;
// Report CRC mismatch when there's a payload CRC error, or a header error and no valid header (to avoid false alarm from previous packet)
if((irq & RADIOLIB_SX126X_IRQ_CRC_ERR) || ((irq & RADIOLIB_SX126X_IRQ_HEADER_ERR) && !(irq & RADIOLIB_SX126X_IRQ_HEADER_VALID))) {
crcState = RADIOLIB_ERR_CRC_MISMATCH;
}
// get packet length and Rx buffer offset
uint8_t offset = 0;
size_t length = getPacketLength(true, &offset);
if((len != 0) && (len < length)) {
// user requested less data than we got, only return what was requested
length = len;
}
// read packet data starting at offset
state = readBuffer(data, length, offset);
RADIOLIB_ASSERT(state);
// clear interrupt flags
state = clearIrqStatus();
// check if CRC failed - this is done after reading data to give user the option to keep them
RADIOLIB_ASSERT(crcState);
return(state);
}
int16_t SX126x::startChannelScan() {
ChannelScanConfig_t cfg = {
.cad = {
.symNum = RADIOLIB_SX126X_CAD_PARAM_DEFAULT,
.detPeak = RADIOLIB_SX126X_CAD_PARAM_DEFAULT,
.detMin = RADIOLIB_SX126X_CAD_PARAM_DEFAULT,
.exitMode = RADIOLIB_SX126X_CAD_PARAM_DEFAULT,
.timeout = 0,
.irqFlags = RADIOLIB_IRQ_CAD_DEFAULT_FLAGS,
.irqMask = RADIOLIB_IRQ_CAD_DEFAULT_MASK,
},
};
return(this->startChannelScan(cfg));
}
int16_t SX126x::startChannelScan(const ChannelScanConfig_t &config) {
// check active modem
if(getPacketType() != RADIOLIB_SX126X_PACKET_TYPE_LORA) {
return(RADIOLIB_ERR_WRONG_MODEM);
}
// set mode to standby
int16_t state = standby();
RADIOLIB_ASSERT(state);
// set RF switch (if present)
this->mod->setRfSwitchState(Module::MODE_RX);
// set DIO pin mapping
state = setDioIrqParams(getIrqMapped(config.cad.irqFlags), getIrqMapped(config.cad.irqMask));
RADIOLIB_ASSERT(state);
// clear interrupt flags
state = clearIrqStatus();
RADIOLIB_ASSERT(state);
// set mode to CAD
state = setCad(config.cad.symNum, config.cad.detPeak, config.cad.detMin, config.cad.exitMode, config.cad.timeout);
return(state);
}
int16_t SX126x::getChannelScanResult() {
// check active modem
if(getPacketType() != RADIOLIB_SX126X_PACKET_TYPE_LORA) {
return(RADIOLIB_ERR_WRONG_MODEM);
}
// check CAD result
uint16_t cadResult = getIrqFlags();
if(cadResult & RADIOLIB_SX126X_IRQ_CAD_DETECTED) {
// detected some LoRa activity
return(RADIOLIB_LORA_DETECTED);
} else if(cadResult & RADIOLIB_SX126X_IRQ_CAD_DONE) {
// channel is free
return(RADIOLIB_CHANNEL_FREE);
}
return(RADIOLIB_ERR_UNKNOWN);
}
int16_t SX126x::setBandwidth(float bw) {
// check active modem
if(getPacketType() != RADIOLIB_SX126X_PACKET_TYPE_LORA) {
return(RADIOLIB_ERR_WRONG_MODEM);
}
// ensure byte conversion doesn't overflow
RADIOLIB_CHECK_RANGE(bw, 0.0f, 510.0f, RADIOLIB_ERR_INVALID_BANDWIDTH);
// check allowed bandwidth values
uint8_t bw_div2 = bw / 2 + 0.01f;
switch (bw_div2) {
case 3: // 7.8:
this->bandwidth = RADIOLIB_SX126X_LORA_BW_7_8;
break;
case 5: // 10.4:
this->bandwidth = RADIOLIB_SX126X_LORA_BW_10_4;
break;
case 7: // 15.6:
this->bandwidth = RADIOLIB_SX126X_LORA_BW_15_6;
break;
case 10: // 20.8:
this->bandwidth = RADIOLIB_SX126X_LORA_BW_20_8;
break;
case 15: // 31.25:
this->bandwidth = RADIOLIB_SX126X_LORA_BW_31_25;
break;
case 20: // 41.7:
this->bandwidth = RADIOLIB_SX126X_LORA_BW_41_7;
break;
case 31: // 62.5:
this->bandwidth = RADIOLIB_SX126X_LORA_BW_62_5;
break;
case 62: // 125.0:
this->bandwidth = RADIOLIB_SX126X_LORA_BW_125_0;
break;
case 125: // 250.0
this->bandwidth = RADIOLIB_SX126X_LORA_BW_250_0;
break;
case 250: // 500.0
this->bandwidth = RADIOLIB_SX126X_LORA_BW_500_0;
break;
default:
return(RADIOLIB_ERR_INVALID_BANDWIDTH);
}
// update modulation parameters
this->bandwidthKhz = bw;
return(setModulationParams(this->spreadingFactor, this->bandwidth, this->codingRate, this->ldrOptimize));
}
int16_t SX126x::setSpreadingFactor(uint8_t sf) {
// check active modem
if(getPacketType() != RADIOLIB_SX126X_PACKET_TYPE_LORA) {
return(RADIOLIB_ERR_WRONG_MODEM);
}
RADIOLIB_CHECK_RANGE(sf, 5, 12, RADIOLIB_ERR_INVALID_SPREADING_FACTOR);
// update modulation parameters
this->spreadingFactor = sf;
return(setModulationParams(this->spreadingFactor, this->bandwidth, this->codingRate, this->ldrOptimize));
}
int16_t SX126x::setCodingRate(uint8_t cr) {
// check active modem
if(getPacketType() != RADIOLIB_SX126X_PACKET_TYPE_LORA) {
return(RADIOLIB_ERR_WRONG_MODEM);
}
RADIOLIB_CHECK_RANGE(cr, 5, 8, RADIOLIB_ERR_INVALID_CODING_RATE);
// update modulation parameters
this->codingRate = cr - 4;
return(setModulationParams(this->spreadingFactor, this->bandwidth, this->codingRate, this->ldrOptimize));
}
int16_t SX126x::setSyncWord(uint8_t syncWord, uint8_t controlBits) {
// check active modem
if(getPacketType() != RADIOLIB_SX126X_PACKET_TYPE_LORA) {
return(RADIOLIB_ERR_WRONG_MODEM);
}
// update register
const uint8_t data[2] = {(uint8_t)((syncWord & 0xF0) | ((controlBits & 0xF0) >> 4)), (uint8_t)(((syncWord & 0x0F) << 4) | (controlBits & 0x0F))};
return(writeRegister(RADIOLIB_SX126X_REG_LORA_SYNC_WORD_MSB, data, 2));
}
int16_t SX126x::setCurrentLimit(float currentLimit) {
// check allowed range
if(!((currentLimit >= 0) && (currentLimit <= 140))) {
return(RADIOLIB_ERR_INVALID_CURRENT_LIMIT);
}
// calculate raw value
uint8_t rawLimit = (uint8_t)(currentLimit / 2.5f);
// update register
return(writeRegister(RADIOLIB_SX126X_REG_OCP_CONFIGURATION, &rawLimit, 1));
}
float SX126x::getCurrentLimit() {
// get the raw value
uint8_t ocp = 0;
readRegister(RADIOLIB_SX126X_REG_OCP_CONFIGURATION, &ocp, 1);
// return the actual value
return((float)ocp * 2.5f);
}
int16_t SX126x::setPreambleLength(size_t preambleLength) {
uint8_t modem = getPacketType();
if(modem == RADIOLIB_SX126X_PACKET_TYPE_LORA) {
this->preambleLengthLoRa = preambleLength;
return(setPacketParams(this->preambleLengthLoRa, this->crcTypeLoRa, this->implicitLen, this->headerType, this->invertIQEnabled));
} else if(modem == RADIOLIB_SX126X_PACKET_TYPE_GFSK) {
this->preambleLengthFSK = preambleLength;
// maximum preamble detector length is limited by sync word length
// for details, see the note in SX1261 datasheet, Rev 2.1, section 6.2.2.1, page 45
uint8_t maxDetLen = RADIOLIB_MIN(this->syncWordLength, this->preambleLengthFSK);
this->preambleDetLength = maxDetLen >= 32 ? RADIOLIB_SX126X_GFSK_PREAMBLE_DETECT_32 :
maxDetLen >= 24 ? RADIOLIB_SX126X_GFSK_PREAMBLE_DETECT_24 :
maxDetLen >= 16 ? RADIOLIB_SX126X_GFSK_PREAMBLE_DETECT_16 :
maxDetLen > 0 ? RADIOLIB_SX126X_GFSK_PREAMBLE_DETECT_8 :
RADIOLIB_SX126X_GFSK_PREAMBLE_DETECT_OFF;
return(setPacketParamsFSK(this->preambleLengthFSK, this->preambleDetLength, this->crcTypeFSK, this->syncWordLength, RADIOLIB_SX126X_GFSK_ADDRESS_FILT_OFF, this->whitening, this->packetType));
}
return(RADIOLIB_ERR_UNKNOWN);
}
int16_t SX126x::setFrequencyDeviation(float freqDev) {
// check active modem
if(getPacketType() != RADIOLIB_SX126X_PACKET_TYPE_GFSK) {
return(RADIOLIB_ERR_WRONG_MODEM);
}
// set frequency deviation to lowest available setting (required for digimodes)
float newFreqDev = freqDev;
if(freqDev < 0.0f) {
newFreqDev = 0.6f;
}
RADIOLIB_CHECK_RANGE(newFreqDev, 0.6f, 200.0f, RADIOLIB_ERR_INVALID_FREQUENCY_DEVIATION);
// calculate raw frequency deviation value
uint32_t freqDevRaw = (uint32_t)(((newFreqDev * 1000.0f) * (float)((uint32_t)(1) << 25)) / (RADIOLIB_SX126X_CRYSTAL_FREQ * 1000000.0f));
// check modulation parameters
this->frequencyDev = freqDevRaw;