-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathRH_SX126x.cpp
More file actions
1288 lines (1146 loc) · 37.2 KB
/
RH_SX126x.cpp
File metadata and controls
1288 lines (1146 loc) · 37.2 KB
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
// RH_SX126x.cpp
//
// Copyright (C) 2023 Mike McCauley
// $Id: RH_SX126x.cpp,v 1.27 2020/07/05 08:52:21 mikem Exp $
//
// UNFINISHED. TODO:
// power setting for different device types
// specific subclasses for 1261, 1262, 1268?
#include <RH_SX126x.h>
// Maybe a mutex for multithreading on Raspberry Pi?
#ifdef RH_USE_MUTEX
RH_DECLARE_MUTEX(lock);
#endif
// Interrupt vectors for the 3 Arduino interrupt pins
// Each interrupt can be handled by a different instance of RH_SX126x, allowing you to have
// 2 or more LORAs per Arduino
RH_SX126x* RH_SX126x::_deviceForInterrupt[RH_SX126x_NUM_INTERRUPTS] = {0, 0, 0};
// These are indexed by the values of ModemConfigChoice
// Stored in flash (program) memory to save SRAM
PROGMEM static const RH_SX126x::ModemConfig MODEM_CONFIG_TABLE[] =
{
// packetType, p1, p2, p3, p4, p5, p6, p7, p8
// LoRa_Bw125Cr45Sf128 Works with RH_RF95
{ RH_SX126x::PacketTypeLoRa, RH_SX126x_LORA_SF_128, RH_SX126x_LORA_BW_125_0, RH_SX126x_LORA_CR_4_5, RH_SX126x_LORA_LOW_DATA_RATE_OPTIMIZE_OFF, 0, 0, 0, 0},
// LoRa_Bw500Cr45Sf128 Works with RH_RF95
{ RH_SX126x::PacketTypeLoRa, RH_SX126x_LORA_SF_128, RH_SX126x_LORA_BW_500_0, RH_SX126x_LORA_CR_4_5, RH_SX126x_LORA_LOW_DATA_RATE_OPTIMIZE_OFF, 0, 0, 0, 0},
// LoRa_Bw31_25Cr48Sf512 no interop with RH_RF95 WHY????
{ RH_SX126x::PacketTypeLoRa, RH_SX126x_LORA_SF_512, RH_SX126x_LORA_BW_31_25, RH_SX126x_LORA_CR_4_8, RH_SX126x_LORA_LOW_DATA_RATE_OPTIMIZE_ON, 0, 0, 0, 0},
// LoRa_Bw125Cr48Sf4096 Works with RH_RF95
{ RH_SX126x::PacketTypeLoRa, RH_SX126x_LORA_SF_4096, RH_SX126x_LORA_BW_125_0, RH_SX126x_LORA_CR_4_8, RH_SX126x_LORA_LOW_DATA_RATE_OPTIMIZE_ON, 0, 0, 0, 0},
// LoRa_Bw125Cr45Sf2048 Works with RH_RF95
{ RH_SX126x::PacketTypeLoRa, RH_SX126x_LORA_SF_2048, RH_SX126x_LORA_BW_125_0, RH_SX126x_LORA_CR_4_5, RH_SX126x_LORA_LOW_DATA_RATE_OPTIMIZE_ON, 0, 0, 0, 0},
};
RH_SX126x::RH_SX126x(uint8_t slaveSelectPin, uint8_t interruptPin, uint8_t busyPin, uint8_t resetPin,
RHGenericSPI& spi, RadioPinConfig* radioPinConfig)
:
RHSPIDriver(slaveSelectPin, spi),
_rxBufValid(0)
{
_interruptPin = interruptPin;
_busyPin = busyPin;
_resetPin = resetPin;
_myInterruptIndex = 0xff; // Not allocated yet
_enableCRC = true;
// There should be (but may not be) a configuration structure toi tell us how to manage the
// radio RF switch control pins
setRadioPinConfig(radioPinConfig);
}
bool RH_SX126x::init()
{
if (!RHSPIDriver::init())
return false;
#ifdef RH_USE_MUTEX
if (RH_MUTEX_INIT(lock) != 0)
{
Serial.println("\n mutex init has failed\n");
return false;
}
#endif
if (!setupInterruptHandler())
return false;
// Reset the radio, if we know the reset pin:
if (_resetPin != RH_INVALID_PIN)
{
pinMode(_resetPin, OUTPUT);
digitalWrite(_resetPin, HIGH);
digitalWrite(_resetPin, LOW);
delay(2);
digitalWrite(_resetPin, HIGH);
// Expect to be busy for about 1ms after this
delay(200); // After reset: else can get runt transmission during startup
}
// Configure the BUSY pin if available
if (_busyPin != RH_INVALID_PIN)
pinMode(_busyPin, INPUT);
// No way to check the device type :-(
// Can read data like 'SX1261 TKF 1A11', at register 0x0320 RH_SX126x_REG_VERSION_STRING but it does not change for SX1261
// Get the current status and guess if we are connected
uint8_t status = getStatus();
if (status == 0x00 || status == 0xff) // Should never get this: probably not connected by SPI
return false;
setModeIdle();
setRegulatorMode(RH_SX126x_REGULATOR_DC_DC); // == SMPS mode
clearDeviceErrors();
setRxFallbackMode(RH_SX126x_RX_TX_FALLBACK_MODE_STDBY_RC);
calibrate(RH_SX126x_CALIBRATE_ALL); // All blocks get (re)calibrated when setFrequency() is called with calibrate true
// This LoRa Sync word 0x1424 is compatible with single byte 0x12 default for RH_RF95.
// https://forum.lora-developers.semtech.com/t/sx1272-and-sx1262-lora-sync-word-compatibility/988/13
setLoRaSyncWord(0x1424);
// You may need to change these after init to suit your radio and its wiring:
setDIO2AsRfSwitchCtrl(true); // Use the radios DIO2 pin control the transmitter. This is common in 3rd party RF modules
setTCXO(3.3, 100); // Enable the TCXO. Typical values for the control voltage and delay
// These are the interrupts we are willing to process
setDioIrqParams(_irqMask, _irqMask, RH_SX126x_IRQ_NONE, RH_SX126x_IRQ_NONE);
// Set up default configuration
setModemConfig(LoRa_Bw125Cr45Sf128); // Radio default
// setModemConfig(LoRa_Bw125Cr48Sf4096); // slow and reliable?
// Default preamble length is 8, so dont set it here
// An innocuous ISM frequency, in the HF range for the WiO-E5, compatible with RH_RF95
setFrequency(915.0);
// Lowish power
setTxPower(13);
return true;
}
void RH_SX126x::enableCrcErrorIrq(bool enable)
{
if ( enable )
_irqMask |= RH_SX126x_IRQ_CRC_ERR;
else
_irqMask &= ~RH_SX126x_IRQ_CRC_ERR;
setDioIrqParams(_irqMask, _irqMask, RH_SX126x_IRQ_NONE, RH_SX126x_IRQ_NONE);
}
void RH_SX126x::enableRawMode(bool enable)
{
_raw = enable;
}
// Some subclasses may need to override
bool RH_SX126x::setupInterruptHandler()
{
// For some subclasses (eg RH_ABZ) we dont want to set up interrupt
int interruptNumber = NOT_AN_INTERRUPT;
if (_interruptPin != RH_INVALID_PIN)
{
// Determine the interrupt number that corresponds to the interruptPin
interruptNumber = digitalPinToInterrupt(_interruptPin);
if (interruptNumber == NOT_AN_INTERRUPT)
return false;
#ifdef RH_ATTACHINTERRUPT_TAKES_PIN_NUMBER
interruptNumber = _interruptPin;
#endif
// Tell the low level SPI interface we will use SPI within this interrupt
spiUsingInterrupt(interruptNumber);
}
if (_interruptPin != RH_INVALID_PIN)
{
// Add by Adrien van den Bossche <vandenbo@univ-tlse2.fr> for Teensy
// ARM M4 requires the below. else pin interrupt doesn't work properly.
// On all other platforms, its innocuous, belt and braces
pinMode(_interruptPin, INPUT);
// Set up interrupt handler
// Since there are a limited number of interrupt glue functions isr*() available,
// we can only support a limited number of devices simultaneously
// ON some devices, notably most Arduinos, the interrupt pin passed in is actually the
// interrupt number. You have to figure out the interruptnumber-to-interruptpin mapping
// yourself based on knwledge of what Arduino board you are running on.
if (_myInterruptIndex == 0xff)
{
static uint8_t interruptCount = 0; // Index into _deviceForInterrupt for next device
// First run, no interrupt allocated yet
if (interruptCount <= RH_SX126x_NUM_INTERRUPTS)
_myInterruptIndex = interruptCount++;
else
return false; // Too many devices, not enough interrupt vectors
}
_deviceForInterrupt[_myInterruptIndex] = this;
if (_myInterruptIndex == 0)
attachInterrupt(interruptNumber, isr0, RISING);
else if (_myInterruptIndex == 1)
attachInterrupt(interruptNumber, isr1, RISING);
else if (_myInterruptIndex == 2)
attachInterrupt(interruptNumber, isr2, RISING);
else
return false; // Too many devices, not enough interrupt vectors
}
return true;
}
// C++ level interrupt handler for this instance
// LORA is unusual in that it has several interrupt lines, and not a single, combined one.
// On MiniWirelessLoRa, only one of the several interrupt lines (DI0) from the RFM95 is usefuly
// connnected to the processor.
// We use this to get RxDone and TxDone interrupts
void RH_SX126x::handleInterrupt()
{
RH_MUTEX_LOCK(lock); // Multithreading support
uint16_t interrupts = getIrqStatus();
_lastirq = interrupts;
_iflag = true; // Debugging
clearIrqStatus(interrupts);
// Serial.print("int: ");
// Serial.println(interrupts, HEX);
if (_mode == RHModeRx && (interrupts & (RH_SX126x_IRQ_CRC_ERR | RH_SX126x_IRQ_HEADER_ERR)))
{
// CrcErr HeaderErr
_rxBad++;
clearRxBuf();
// If there was an error, the SX126x is now in standby mode. Need to force RH state back to idle too
_mode = RHModeIdle;
// setModeRx(); // Keep trying?
}
else if (_mode == RHModeRx && (interrupts & RH_SX126x_IRQ_RX_DONE))
{
// RxDone
// Should now be in STDBY
// Get received packet length
uint8_t rxbufferstatus[2]; // PayloadLengthRx, RxStartBufferPointer
getCommand(RH_SX126x_CMD_GET_RX_BUFFER_STATUS, rxbufferstatus, sizeof(rxbufferstatus));
_bufLen = rxbufferstatus[0];
uint8_t offset = rxbufferstatus[1];
// Get the packet
readBuffer(offset, _buf, _bufLen);
uint8_t packetstatus[3];
getCommand(RH_SX126x_CMD_GET_PKT_STATUS, packetstatus, sizeof(packetstatus));
if (_packetType == PacketTypeLoRa)
{
_lastRssi = -(packetstatus[0] / 2); // dBm
_lastSNR = (packetstatus[1] / 4);
}
else if (_packetType == PacketTypeGFSK)
{
_lastRssi = -(packetstatus[2] / 2); // dBm
_lastSNR = 0; // Unobtainable
}
validateRxBuf();
if (_rxBufValid)
setModeIdle(); // Got one
}
else if (_mode == RHModeTx && (interrupts & RH_SX126x_IRQ_TX_DONE))
{
// TxDone
// Should now be in STDBY
_txGood++;
setModeIdle();
}
else if (_mode == RHModeCad && (interrupts & RH_SX126x_IRQ_CAD_DONE))
{
// Serial.println("caddone");
// CadDone
// Should now be in STDBY_RX
setModeIdle();
}
else if (_mode == RHModeCad && (interrupts & RH_SX126x_IRQ_CAD_DETECTED))
{
// CadDetected: there was activity
// Serial.println("caddetected");
_cad = true;
setModeIdle();
}
RH_MUTEX_UNLOCK(lock);
}
// These are low level functions that call the interrupt handler for the correct
// instance of RH_SX126x.
// 3 interrupts allows us to have 3 different devices
void RH_INTERRUPT_ATTR RH_SX126x::isr0()
{
if (_deviceForInterrupt[0])
_deviceForInterrupt[0]->handleInterrupt();
}
void RH_INTERRUPT_ATTR RH_SX126x::isr1()
{
if (_deviceForInterrupt[1])
_deviceForInterrupt[1]->handleInterrupt();
}
void RH_INTERRUPT_ATTR RH_SX126x::isr2()
{
if (_deviceForInterrupt[2])
_deviceForInterrupt[2]->handleInterrupt();
}
// Check whether the latest received message is complete and uncorrupted
void RH_SX126x::validateRxBuf()
{
if (_bufLen < 4)
return; // Too short to be a real message
// Extract the 4 headers
_rxHeaderTo = _buf[0];
_rxHeaderFrom = _buf[1];
_rxHeaderId = _buf[2];
_rxHeaderFlags = _buf[3];
if (_promiscuous ||
_rxHeaderTo == _thisAddress ||
_rxHeaderTo == RH_BROADCAST_ADDRESS)
{
_rxGood++;
_rxBufValid = true;
}
}
bool RH_SX126x::available()
{
RH_MUTEX_LOCK(lock); // Multithreading support
if (_mode == RHModeTx)
{
RH_MUTEX_UNLOCK(lock);
return false;
}
setModeRx();
RH_MUTEX_UNLOCK(lock);
return _rxBufValid; // Will be set by the interrupt handler when a good message is received
}
void RH_SX126x::clearRxBuf()
{
waitUntilNotBusy();
ATOMIC_BLOCK_START;
_rxBufValid = false;
_bufLen = 0;
ATOMIC_BLOCK_END;
}
bool RH_SX126x::recv(uint8_t* buf, uint8_t* len)
{
uint8_t hdr_len = RH_SX126x_HEADER_LEN;
if (!available())
return false;
if ( _raw )
hdr_len = 0;
if (buf && len)
{
ATOMIC_BLOCK_START;
// Skip the 4 headers that are at the beginning of the rxBuf
if (*len > _bufLen-hdr_len)
*len = _bufLen-hdr_len;
memcpy(buf, _buf+hdr_len, *len);
ATOMIC_BLOCK_END;
}
clearRxBuf(); // This message accepted and cleared
RH_MUTEX_UNLOCK(lock);
return true;
}
bool RH_SX126x::send(const uint8_t* data, uint8_t len)
{
if (len > RH_SX126x_MAX_MESSAGE_LEN)
return false;
waitPacketSent(); // Make sure we dont interrupt an outgoing message
setModeIdle();
if (!waitCAD())
return false; // Check channel activity
setBufferBaseAddress(0, 0);
// The headers
if ( _raw )
{
// The message data
writeBuffer(0, data, len);
setPacketParametersLoRa(len); // Tell modem how much to send
}
else
{
uint8_t headers[RH_SX126x_HEADER_LEN] = {_txHeaderTo, _txHeaderFrom, _txHeaderId, _txHeaderFlags };
writeBuffer(0, headers, sizeof(headers));
// The message data
writeBuffer(RH_SX126x_HEADER_LEN, data, len);
setPacketParametersLoRa(len + RH_SX126x_HEADER_LEN); // Tell modem how much to send
}
RH_MUTEX_LOCK(lock); // Multithreading support
setModeTx(); // Start the transmitter
RH_MUTEX_UNLOCK(lock);
// Hmmmm, some chips fail to enter TX mode the first time,and need to be tried again
// Why?
if (getStatus() == 0x2a)
{
// Retry Tx mode directly
RH_MUTEX_LOCK(lock); // Multithreading support
setTx(RH_SX126x_RX_TIMEOUT_NONE); // Timeout 0
RH_MUTEX_UNLOCK(lock);
}
// when Tx is done, interruptHandler will fire and radio mode will return to STANDBY
return true;
}
uint8_t RH_SX126x::maxMessageLength()
{
return RH_SX126x_MAX_MESSAGE_LEN;
}
bool RH_SX126x::setFrequency(float centre, bool calibrate)
{
if (calibrate)
{
if (centre > 900.0)
calibrateImage(RH_SX126x_CAL_IMG_902_MHZ_1, RH_SX126x_CAL_IMG_902_MHZ_2);
else if (centre > 850.0)
calibrateImage(RH_SX126x_CAL_IMG_863_MHZ_1, RH_SX126x_CAL_IMG_863_MHZ_2);
else if (centre > 770.0)
calibrateImage(RH_SX126x_CAL_IMG_779_MHZ_1, RH_SX126x_CAL_IMG_779_MHZ_2);
else if (centre > 460.0)
calibrateImage(RH_SX126x_CAL_IMG_470_MHZ_1, RH_SX126x_CAL_IMG_470_MHZ_2);
else
calibrateImage(RH_SX126x_CAL_IMG_430_MHZ_1, RH_SX126x_CAL_IMG_430_MHZ_2);
}
// Frf = FRF / FSTEP
uint32_t frf = (centre * 1000000.0) / RH_SX126x_FSTEP;
uint8_t setting[] =
{static_cast<uint8_t>(frf >> 24),
static_cast<uint8_t>(frf >> 16),
static_cast<uint8_t>(frf >> 8),
static_cast<uint8_t>(frf)};
return sendCommand(RH_SX126x_CMD_SET_RF_FREQUENCY, setting, sizeof(setting));
}
void RH_SX126x::setModeIdle()
{
if (_mode != RHModeIdle)
{
modeWillChange(RHModeIdle);
setStandby(RH_SX126x_STANDBY_RC);
_mode = RHModeIdle;
}
}
bool RH_SX126x::sleep()
{
if (_mode != RHModeSleep)
{
modeWillChange(RHModeSleep);
setSleep(RH_SX126x_SLEEP_START_WARM);
_mode = RHModeSleep;
}
return true;
}
void RH_SX126x::setModeRx()
{
if (_mode != RHModeRx)
{
modeWillChange(RHModeRx);
setPacketParametersLoRa(RH_SX126x_MAX_PAYLOAD_LEN);
setRx(RH_SX126x_RX_TIMEOUT_NONE); // Timeout 0
_mode = RHModeRx;
}
}
void RH_SX126x::setModeTx()
{
if (_mode != RHModeTx)
{
modeWillChange(RHModeTx);
setTx(RH_SX126x_RX_TIMEOUT_NONE); // Timeout 0
// Expect to be busy for about 0.5ms
_mode = RHModeTx;
}
}
// Sets registers from a canned modem configuration structure
bool RH_SX126x::setModemRegisters(const ModemConfig* config)
{
_packetType = config->packetType;
switch (_packetType)
{
case PacketTypeLoRa:
sendCommand(RH_SX126x_CMD_SET_PKT_TYPE, RH_SX126x_PACKET_TYPE_LORA);
break;
case PacketTypeGFSK:
sendCommand(RH_SX126x_CMD_SET_PKT_TYPE, RH_SX126x_PACKET_TYPE_GFSK);
break;
}
return setModulationParameters(
config->p1,
config->p2,
config->p3,
config->p4,
config->p5,
config->p6,
config->p7,
config->p8);
}
// Set one of the canned FSK Modem configs
// Returns true if its a valid choice
bool RH_SX126x::setModemConfig(ModemConfigChoice index)
{
if (index > (signed int)(sizeof(MODEM_CONFIG_TABLE) / sizeof(ModemConfig)))
return false;
// Get it out of PROG_MEM
ModemConfig cfg;
memcpy_P(&cfg, &MODEM_CONFIG_TABLE[index], sizeof(RH_SX126x::ModemConfig));
return setModemRegisters(&cfg);
}
void RH_SX126x::setPreambleLength(uint16_t bytes)
{
_preambleLength = bytes;
}
bool RH_SX126x::isChannelActive()
{
// Set mode RHModeCad
if (_mode != RHModeCad)
{
modeWillChange(RHModeCad);
setCad();
_mode = RHModeCad;
}
while (_mode == RHModeCad)
YIELD;
return _cad;
}
int RH_SX126x::lastSNR()
{
return _lastSNR;
}
//////////////////////////////////////////////////
// Specialised SPI routines.
// This device has slightly unusual SPI behaviour: including no RH_SPI_WRITE_MASK, so need to rewrite
// most SPI access functions
bool RH_SX126x::waitUntilNotBusy()
{
uint8_t busy_timeout_cnt = 0;
if (_busyPin == RH_INVALID_PIN)
return false;
while (digitalRead(_busyPin))
{
delay(1);
busy_timeout_cnt++;
// Need to wait up to 150us when in sleep mode, see table 8-1
if (busy_timeout_cnt > 10) // Should be configurable
{
Serial.println("ERROR: waitUntilNotBusy TIMEOUT");
return false;
}
}
return true; // OK
}
uint8_t RH_SX126x::getStatus()
{
waitUntilNotBusy();
uint8_t status;
ATOMIC_BLOCK_START;
beginTransaction();
_spi.transfer(RH_SX126x_CMD_GET_STATUS);
status = _spi.transfer(RH_SX126x_CMD_NOP);
endTransaction();
ATOMIC_BLOCK_END;
return status;
}
bool RH_SX126x::sendCommand(uint8_t command, uint8_t data[], uint8_t len)
{
#if 0
Serial.print("sendCommand ");
Serial.print(command, HEX);
Serial.print(" ");
for (uint8_t i = 0; i < len; i++)
{
Serial.print(data[i], HEX);
Serial.print(" ");
}
Serial.println("");
#endif
ATOMIC_BLOCK_START;
beginTransaction();
waitUntilNotBusy();
_spi.transfer(command);
for (uint8_t i = 0; i < len; i++)
_spi.transfer(data[i]);
endTransaction();
ATOMIC_BLOCK_END;
return true;
}
// Single value command
bool RH_SX126x::sendCommand(uint8_t command, uint8_t value)
{
uint8_t data = value;
return sendCommand(command, &data, sizeof(data));
}
bool RH_SX126x::sendCommand(uint8_t command)
{
ATOMIC_BLOCK_START;
beginTransaction();
waitUntilNotBusy();
_spi.transfer(command);
endTransaction();
ATOMIC_BLOCK_END;
return true;
}
bool RH_SX126x::getCommand(uint8_t command, uint8_t data[], uint8_t len)
{
ATOMIC_BLOCK_START;
beginTransaction();
waitUntilNotBusy();
_spi.transfer(command);
_spi.transfer(0); // Wait for data
for (uint8_t i = 0; i < len; i++)
data[i] = _spi.transfer(0);
endTransaction();
ATOMIC_BLOCK_END;
return true;
}
bool RH_SX126x::readRegisters(uint16_t address, uint8_t data[], uint8_t len)
{
ATOMIC_BLOCK_START;
beginTransaction();
waitUntilNotBusy();
_spi.transfer(RH_SX126x_CMD_READ_REGISTER);
_spi.transfer(static_cast<uint8_t>(address >> 8));
_spi.transfer(static_cast<uint8_t>(address));
_spi.transfer(RH_SX126x_CMD_NOP); // Wait for data
for (uint8_t i = 0; i < len; i++)
data[i] = _spi.transfer(0);
endTransaction();
ATOMIC_BLOCK_END;
return true;
}
uint8_t RH_SX126x::readRegister(uint16_t address)
{
uint8_t data = 0;
readRegisters(address, &data, 1);
return data;
}
bool RH_SX126x::writeRegisters(uint16_t address, uint8_t data[], uint8_t len)
{
#if 0
Serial.print("writeRegisters ");
Serial.print(address, HEX);
Serial.print(" ");
for (uint8_t i = 0; i < len; i++)
{
Serial.print(data[i], HEX);
Serial.print(" ");
}
Serial.println("");
#endif
ATOMIC_BLOCK_START;
beginTransaction();
waitUntilNotBusy();
_spi.transfer(RH_SX126x_CMD_WRITE_REGISTER);
_spi.transfer(static_cast<uint8_t>(address >> 8));
_spi.transfer(static_cast<uint8_t>(address));
for (uint8_t i = 0; i < len; i++)
_spi.transfer(data[i]);
endTransaction();
ATOMIC_BLOCK_END;
return true;
}
bool RH_SX126x::writeRegister(uint16_t address, uint8_t data)
{
uint8_t d = data; // Single register bye to write
return writeRegisters(address, &d, 1);
}
bool RH_SX126x::writeBuffer(uint8_t offset, const uint8_t data[], uint8_t len)
{
// A bit different to sendCommand because of offset
ATOMIC_BLOCK_START;
beginTransaction();
waitUntilNotBusy();
_spi.transfer(RH_SX126x_CMD_WRITE_BUFFER);
_spi.transfer(offset);
for (uint8_t i = 0; i < len; i++)
_spi.transfer(data[i]);
endTransaction();
ATOMIC_BLOCK_END;
return true;
}
bool RH_SX126x::writeBuffer(uint8_t offset, const char* text)
{
return writeBuffer(offset, (uint8_t*) text, strlen(text));
}
bool RH_SX126x::readBuffer(uint8_t offset, uint8_t data[], uint8_t len)
{
// This is a bit different from getCommand, because of offset
ATOMIC_BLOCK_START;
beginTransaction();
waitUntilNotBusy();
_spi.transfer(RH_SX126x_CMD_READ_BUFFER);
_spi.transfer(offset);
_spi.transfer(RH_SX126x_CMD_NOP); // Wait for data
for (uint8_t i = 0; i < len; i++)
data[i] = _spi.transfer(0);
endTransaction();
ATOMIC_BLOCK_END;
return true;
}
bool RH_SX126x::setPaConfig(uint8_t paDutyCycle, uint8_t hpMax, uint8_t deviceSel, uint8_t paLut)
{
uint8_t settings[] = {paDutyCycle, hpMax, deviceSel, paLut};
return sendCommand(RH_SX126x_CMD_SET_PA_CFG, settings, sizeof(settings));
}
bool RH_SX126x::setTxParams(uint8_t power, uint8_t rampTime)
{
uint8_t settings[] = {power, rampTime};
return sendCommand(RH_SX126x_CMD_SET_TX_PARAMS, settings, sizeof(settings));
}
bool RH_SX126x::setTxPower(int8_t power)
{
// The device may have 2 transmitter power amps (PAs), low power and high power
// However, depending on the specific model and how it is connected, one or the other might not be available
// so we depend on configuration to tell what PAs are available
// STM32WLE5JC has 2, but perhaps only 1 is connected to the antenna, depending on the actual circuit
// SX1261 only has low power
// SX1262 only has high power
// SX1268 only has high power
bool lp_supported = findRadioPinConfigEntry(RadioPinConfigMode_TX_LOW_POWER) != nullptr;
bool hp_supported = findRadioPinConfigEntry(RadioPinConfigMode_TX_HIGH_POWER) != nullptr;
bool useHP = false; // Whether we are to use the high or low power amp
// REVISIT: needs more work for reduced powers
// Depends on if 1261 or 1262 or 1268
if (hp_supported && lp_supported)
{
// -17 to +22 dBm
power = constrain(power, -17, 22);
if (power > 14)
useHP = true;
else
useHP = false;
}
else if (!hp_supported && lp_supported)
{
// -17 to +15 dBm
power = constrain(power, -17, 15);
useHP = false;
}
else // Assume only HP is available
{
// -9 to +22 dBm
power = constrain(power, -9, 22);
useHP = true;
}
// Adjust for optimal settings per Table 13-1
// CAUTION: needs to change for SX1268
if (useHP)
{
// CAUTION: device power supply needs to be able to provide 3.3V at currents up to 118 mA with high power settings
// -9 to 22 dBm SX1262
_requiredPAMode = RadioPinConfigMode_TX_HIGH_POWER;
fixPAClamping(true);
switch (power)
{
case 22:
case 21:
setPaConfig(0x04, 0x07, RH_SX126x_PA_CONFIG_DEVICE_SEL_SX1262, RH_SX126x_PA_CONFIG_PA_LUT);
break;
case 20:
case 19:
case 18:
setPaConfig(0x03, 0x05, RH_SX126x_PA_CONFIG_DEVICE_SEL_SX1262, RH_SX126x_PA_CONFIG_PA_LUT);
power = power + 2;
break;
case 17:
case 16:
case 15:
setPaConfig(0x02, 0x03, RH_SX126x_PA_CONFIG_DEVICE_SEL_SX1262, RH_SX126x_PA_CONFIG_PA_LUT);
power = power + 5;
break;
default:
// 14 and less
setPaConfig(0x02, 0x02, RH_SX126x_PA_CONFIG_DEVICE_SEL_SX1262, RH_SX126x_PA_CONFIG_PA_LUT);
power = power + 8;
break;
}
}
else
{
// CAUTION: device power supply needs to be able to provide 3.3V at currents up to 32.5 mA with high power settings
// -17 to 14 dBm SX1262
_requiredPAMode = RadioPinConfigMode_TX_LOW_POWER;
switch (power)
{
case 15:
setPaConfig(0x06, 0x00, RH_SX126x_PA_CONFIG_DEVICE_SEL_SX1261, RH_SX126x_PA_CONFIG_PA_LUT);
power = 14;
break;
case 14:
case 13:
case 12:
case 11:
setPaConfig(0x04, 0x00, RH_SX126x_PA_CONFIG_DEVICE_SEL_SX1261, RH_SX126x_PA_CONFIG_PA_LUT);
break;
default:
// 10 and less
setPaConfig(0x01, 0x00, RH_SX126x_PA_CONFIG_DEVICE_SEL_SX1261, RH_SX126x_PA_CONFIG_PA_LUT);
power = power + 3;
break;
}
}
// SetTxParams with the corrected power level
return setTxParams(power, RH_SX126x_PA_RAMP_200U); // power, RampTime = 200us. REVISIT: should be configurable ramp time?
}
bool RH_SX126x::printRegisters(uint16_t address, uint8_t count)
{
#ifdef RH_HAVE_SERIAL
uint8_t buf[256];
readRegisters(address, buf, count);
Serial.print("registers starting at: ");
Serial.println(address, HEX);
for (uint8_t i = 0; i < count; i++)
{
Serial.println(buf[i], HEX);
}
#endif
return true;
}
bool RH_SX126x::clearDeviceErrors()
{
uint8_t data[] = {0x00, 0x00};
return sendCommand(RH_SX126x_CMD_CLR_DEVICE_ERRORS, data, sizeof(data));
}
bool RH_SX126x::setDIO2AsRfSwitchCtrl(bool value)
{
return sendCommand(RH_SX126x_CMD_SET_DIO2_AS_RF_SWITCH_CTRL, value);
}
bool RH_SX126x::setRxFallbackMode(uint8_t mode)
{
return sendCommand(RH_SX126x_CMD_SET_RX_TX_FALLBACK_MODE, mode);
}
bool RH_SX126x::setModulationParameters(uint8_t p1, uint8_t p2, uint8_t p3, uint8_t p4, uint8_t p5, uint8_t p6, uint8_t p7, uint8_t p8)
{
_lorabw500 = (p2 == RH_SX126x_LORA_BW_500_0); // Need to remember this for modulation quality workaround
switch(p2)
{
case RH_SX126x_LORA_BW_7_8:
_bandwidth = 7.8;
break;
case RH_SX126x_LORA_BW_10_4:
_bandwidth = 10.4;
break;
case RH_SX126x_LORA_BW_15_6:
_bandwidth = 15.6;
break;
case RH_SX126x_LORA_BW_20_8:
_bandwidth = 20.8;
break;
case RH_SX126x_LORA_BW_31_25:
_bandwidth = 31.25;
break;
case RH_SX126x_LORA_BW_41_7:
_bandwidth = 41.7;
break;
case RH_SX126x_LORA_BW_62_5:
_bandwidth = 62.5;
break;
case RH_SX126x_LORA_BW_125_0:
_bandwidth = 125.0;
break;
case RH_SX126x_LORA_BW_250_0:
_bandwidth = 250.0;
break;
case RH_SX126x_LORA_BW_500_0:
_bandwidth = 500.0;
break;
default:
_bandwidth = 0;
}
uint8_t params[] = {p1, p2, p3, p4, p5, p6, p7, p8};
return sendCommand(RH_SX126x_CMD_SET_MODULATION_PARAMS, params, sizeof(params));
}
bool RH_SX126x::setModulationParametersLoRa(uint8_t sf, float bw, uint8_t cr, bool ldro)
{
_packetType = PacketTypeLoRa;
// Set packet type LoRa. CAUTION: Must be done in STDBY_RC mode (ie in RH idle mode)
sendCommand(RH_SX126x_CMD_SET_PKT_TYPE, RH_SX126x_PACKET_TYPE_LORA);
// REVISIT: could automatically calculate LDRO based on symbollength = (1 << SF) / BW
_bandwidth = bw;
// sf must be 5 to 12
// bw must be 0.0 to 510.0
// cr must be 5 - 8 inclusive (represents 4/5, 4/6, 4/7, 4/8 respectively)
uint8_t bw_div2 = bw / 2 + 0.01;
uint8_t bwsetting = RH_SX126x_LORA_BW_125_0;
switch (bw_div2)
{
case 3: // 7.8:
bwsetting = RH_SX126x_LORA_BW_7_8;
break;
case 5: // 10.4:
bwsetting = RH_SX126x_LORA_BW_10_4;
break;
case 7: // 15.6:
bwsetting = RH_SX126x_LORA_BW_15_6;
break;
case 10: // 20.8:
bwsetting = RH_SX126x_LORA_BW_20_8;
break;
case 15: // 31.25:
bwsetting = RH_SX126x_LORA_BW_31_25;
break;
case 20: // 41.7:
bwsetting = RH_SX126x_LORA_BW_41_7;
break;
case 31: // 62.5:
bwsetting = RH_SX126x_LORA_BW_62_5;
break;
case 62: // 125.0:
bwsetting = RH_SX126x_LORA_BW_125_0;
break;
case 125: // 250.0
bwsetting = RH_SX126x_LORA_BW_250_0;
break;
case 250: // 500.0
bwsetting = RH_SX126x_LORA_BW_500_0;
break;
}
return setModulationParameters(sf, bwsetting, cr - 4, ldro, 0, 0, 0, 0);
}
bool RH_SX126x::setModulationParametersGFSK(uint32_t br, uint8_t sh, uint8_t rxBw, uint32_t freqDev)
{
_packetType = PacketTypeGFSK;
return false;
}
bool RH_SX126x::calibrate(uint8_t calib_param)
{
return sendCommand(RH_SX126x_CMD_CALIBRATE, calib_param);
}
bool RH_SX126x::calibrateImage(uint8_t f1, uint8_t f2)
{
uint8_t frequencies[] = {f1, f2};
return sendCommand(RH_SX126x_CMD_CALIBRATE_IMAGE, frequencies, sizeof(frequencies));
}
bool RH_SX126x::setLoRaSyncWord(uint16_t sync)
{
uint8_t sync_word[] = {static_cast<uint8_t>(sync >> 8), static_cast<uint8_t>(sync)};
return writeRegisters(RH_SX126x_REG_LR_SYNCWORD, sync_word, sizeof(sync_word));
}
bool RH_SX126x::setOCPConfiguration(uint8_t setting)
{
return writeRegister(RH_SX126x_REG_OCP, setting);
}
bool RH_SX126x::setDIO3AsTcxoCtrl(uint8_t voltage, uint32_t delay)
{
uint8_t settings[] = {voltage,
static_cast<uint8_t>(delay >> 16),