-
Notifications
You must be signed in to change notification settings - Fork 0
/
RFM69X.cpp
executable file
·844 lines (752 loc) · 33.9 KB
/
RFM69X.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
// From rrobinet@github.com 03/10/2016
//
// This is a modified RFM69 library used for ESP-32 processor.
// It is motivated by the fact the ESP-32 SPI transactions occurs as interrupt mode while the RFM69 library starts SPI transactions in interrupt routine simultaneously.
// The main change is the move from the SPI transactions from the interruptHandler function, to a new one; the interruptHandling, which is tested during the receiveDone.
// This version works in a mix environment (RFM69 and RFM69X libraries), however it is incompatible with virtualised versions such as the RFM_ATC one
//
// Notes :
// * The virtualised RFM69_SessionKey for ESP-32 is available (see RFM69X_SessionKey)
// * It also implement the SPI_HAS_TRANSACTION syntax from the recent SPI Library
// * A test of the presence or good functioning of the RFM transceiver is also added.
// * Because SPI transaction is now moved out of the Interrupt routine, this version is also compatible with Ethernet Shield (W5100) without further modifications
// * This version is tested on ARDUINO UNO, ARDUINO MEGA 2560, Moteino R6, MoteinoMEGA, ESP-32 (WeMoS LOLIN 32) and ESP8266 (WeMoS D1 mini)
// * From the time being running on ESP-32 seems to be a little bit slower that on other processors.
//It is based on the lowepowerlab library version of July 2014:
// **********************************************************************************
// Driver definition for HopeRF RFM69W/RFM69HW/RFM69CW/RFM69HCW, Semtech SX1231/1231H
// **********************************************************************************
// Copyright Felix Rusu (2014), felix@lowpowerlab.com
// http://lowpowerlab.com/
// **********************************************************************************
// License
// **********************************************************************************
// This program is free software; you can redistribute it
// and/or modify it under the terms of the GNU General
// Public License as published by the Free Software
// Foundation; either version 3 of the License, or
// (at your option) any later version.
//
// 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/>.
//
// Licence can be viewed at
// http://www.gnu.org/licenses/gpl-3.0.txt
//
// Please maintain this license information along with authorship
// and copyright notices in any redistribution of this code
// **********************************************************************************
#include <RFM69X.h>
#include <RFM69Xregisters.h>
#include <SPI.h>
volatile uint8_t RFM69X::DATA[RF69_MAX_DATA_LEN];
volatile uint8_t RFM69X::_mode; // current transceiver state
volatile uint8_t RFM69X::DATALEN;
volatile uint8_t RFM69X::SENDERID;
volatile uint8_t RFM69X::TARGETID; // should match _address
volatile uint8_t RFM69X::PAYLOADLEN;
volatile uint8_t RFM69X::ACK_REQUESTED;
volatile uint8_t RFM69X::ACK_RECEIVED; // should be polled immediately after sending a packet with ACK request
volatile int16_t RFM69X::RSSI; // most accurate RSSI during reception (closest to the reception)
volatile bool RFM69X::_inISR;
volatile bool RFM69X::_gotISR = false; // Added for ESP32 SPI interrupts compatibility
SPISettings settingsA(SPI_CLOCK_DIV4, MSBFIRST, SPI_MODE0); // Adapted according current SPI library (SPI_HAS_TRANSACTION)
RFM69X* RFM69X::selfPointer;
bool RFM69X::initialize(uint8_t freqBand, uint8_t nodeID, uint8_t networkID)
{
const uint8_t CONFIG[][2] =
{
/* 0x01 */ { REG_OPMODE, RF_OPMODE_SEQUENCER_ON | RF_OPMODE_LISTEN_OFF | RF_OPMODE_STANDBY },
/* 0x02 */ { REG_DATAMODUL, RF_DATAMODUL_DATAMODE_PACKET | RF_DATAMODUL_MODULATIONTYPE_FSK | RF_DATAMODUL_MODULATIONSHAPING_00 }, // no shaping
/* 0x03 */ { REG_BITRATEMSB, RF_BITRATEMSB_55555}, // default: 4.8 KBPS
/* 0x04 */ { REG_BITRATELSB, RF_BITRATELSB_55555},
/* 0x05 */ { REG_FDEVMSB, RF_FDEVMSB_50000}, // default: 5KHz, (FDEV + BitRate / 2 <= 500KHz)
/* 0x06 */ { REG_FDEVLSB, RF_FDEVLSB_50000},
/* 0x07 */ { REG_FRFMSB, (uint8_t) (freqBand==RF69_315MHZ ? RF_FRFMSB_315 : (freqBand==RF69_433MHZ ? RF_FRFMSB_433 : (freqBand==RF69_868MHZ ? RF_FRFMSB_868 : RF_FRFMSB_915))) },
/* 0x08 */ { REG_FRFMID, (uint8_t) (freqBand==RF69_315MHZ ? RF_FRFMID_315 : (freqBand==RF69_433MHZ ? RF_FRFMID_433 : (freqBand==RF69_868MHZ ? RF_FRFMID_868 : RF_FRFMID_915))) },
/* 0x09 */ { REG_FRFLSB, (uint8_t) (freqBand==RF69_315MHZ ? RF_FRFLSB_315 : (freqBand==RF69_433MHZ ? RF_FRFLSB_433 : (freqBand==RF69_868MHZ ? RF_FRFLSB_868 : RF_FRFLSB_915))) },
// looks like PA1 and PA2 are not implemented on RFM69W, hence the max output power is 13dBm
// +17dBm and +20dBm are possible on RFM69HW
// +13dBm formula: Pout = -18 + OutputPower (with PA0 or PA1**)
// +17dBm formula: Pout = -14 + OutputPower (with PA1 and PA2)**
// +20dBm formula: Pout = -11 + OutputPower (with PA1 and PA2)** and high power PA settings (section 3.3.7 in datasheet)
///* 0x11 */ { REG_PALEVEL, RF_PALEVEL_PA0_ON | RF_PALEVEL_PA1_OFF | RF_PALEVEL_PA2_OFF | RF_PALEVEL_OUTPUTPOWER_11111},
///* 0x13 */ { REG_OCP, RF_OCP_ON | RF_OCP_TRIM_95 }, // over current protection (default is 95mA)
// RXBW defaults are { REG_RXBW, RF_RXBW_DCCFREQ_010 | RF_RXBW_MANT_24 | RF_RXBW_EXP_5} (RxBw: 10.4KHz)
/* 0x19 */ { REG_RXBW, RF_RXBW_DCCFREQ_010 | RF_RXBW_MANT_16 | RF_RXBW_EXP_2 }, // (BitRate < 2 * RxBw)
//for BR-19200: /* 0x19 */ { REG_RXBW, RF_RXBW_DCCFREQ_010 | RF_RXBW_MANT_24 | RF_RXBW_EXP_3 },
/* 0x25 */ { REG_DIOMAPPING1, RF_DIOMAPPING1_DIO0_01 }, // DIO0 is the only IRQ we're using
/* 0x26 */ { REG_DIOMAPPING2, RF_DIOMAPPING2_CLKOUT_OFF }, // DIO5 ClkOut disable for power saving
/* 0x28 */ { REG_IRQFLAGS2, RF_IRQFLAGS2_FIFOOVERRUN }, // writing to this bit ensures that the FIFO & status flags are reset
/* 0x29 */ { REG_RSSITHRESH, 220 }, // must be set to dBm = (-Sensitivity / 2), default is 0xE4 = 228 so -114dBm
///* 0x2D */ { REG_PREAMBLELSB, RF_PREAMBLESIZE_LSB_VALUE } // default 3 preamble bytes 0xAAAAAA
/* 0x2E */ { REG_SYNCCONFIG, RF_SYNC_ON | RF_SYNC_FIFOFILL_AUTO | RF_SYNC_SIZE_2 | RF_SYNC_TOL_0 },
/* 0x2F */ { REG_SYNCVALUE1, 0x2D }, // attempt to make this compatible with sync1 byte of RFM12B lib
/* 0x30 */ { REG_SYNCVALUE2, networkID }, // NETWORK ID
/* 0x37 */ { REG_PACKETCONFIG1, RF_PACKET1_FORMAT_VARIABLE | RF_PACKET1_DCFREE_OFF | RF_PACKET1_CRC_ON | RF_PACKET1_CRCAUTOCLEAR_ON | RF_PACKET1_ADRSFILTERING_OFF },
/* 0x38 */ { REG_PAYLOADLENGTH, 66 }, // in variable length mode: the max frame size, not used in TX
///* 0x39 */ { REG_NODEADRS, nodeID }, // turned off because we're not using address filtering
/* 0x3C */ { REG_FIFOTHRESH, RF_FIFOTHRESH_TXSTART_FIFONOTEMPTY | RF_FIFOTHRESH_VALUE }, // TX on FIFO not empty
/* 0x3D */ { REG_PACKETCONFIG2, RF_PACKET2_RXRESTARTDELAY_2BITS | RF_PACKET2_AUTORXRESTART_ON | RF_PACKET2_AES_OFF }, // RXRESTARTDELAY must match transmitter PA ramp-down time (bitrate dependent)
//for BR-19200: /* 0x3D */ { REG_PACKETCONFIG2, RF_PACKET2_RXRESTARTDELAY_NONE | RF_PACKET2_AUTORXRESTART_ON | RF_PACKET2_AES_OFF }, // RXRESTARTDELAY must match transmitter PA ramp-down time (bitrate dependent)
/* 0x6F */ { REG_TESTDAGC, RF_DAGC_IMPROVED_LOWBETA0 }, // run DAGC continuously in RX mode for Fading Margin Improvement, recommended default for AfcLowBetaOn=0
{255, 0}
};
digitalWrite(_slaveSelectPin, HIGH);
pinMode(_slaveSelectPin, OUTPUT);
SPI.begin();
unsigned long start = millis();
uint8_t timeout = 50;
do writeReg(REG_SYNCVALUE1, 0xAA); while (readReg(REG_SYNCVALUE1) != 0xaa && millis()-start < timeout);
// Test for functional RFM transciever
if (millis()-start >= timeout) return false; // return false if RFM transciever is NOT installed or doesn't function
start = millis();
do writeReg(REG_SYNCVALUE1, 0x55); while (readReg(REG_SYNCVALUE1) != 0x55 && millis()-start < timeout);
for (uint8_t i = 0; CONFIG[i][0] != 255; i++)
writeReg(CONFIG[i][0], CONFIG[i][1]);
// Encryption is persistent between resets and can trip you up during debugging.
// Disable it during initialization so we always start from a known state.
encrypt(0);
setHighPower(_isRFM69HW); // called regardless if it's a RFM69W or RFM69HW
setMode(RF69_MODE_STANDBY);
start = millis();
while (((readReg(REG_IRQFLAGS1) & RF_IRQFLAGS1_MODEREADY) == 0x00) && millis()-start < timeout); // wait for ModeReady
if (millis()-start >= timeout)
return false;
_inISR = false;
attachInterrupt(_interruptNum, RFM69X::isr0, RISING);
selfPointer = this;
_address = nodeID;
return true;
}
// return the frequency (in Hz)
uint32_t RFM69X::getFrequency()
{
return RF69_FSTEP * (((uint32_t) readReg(REG_FRFMSB) << 16) + ((uint16_t) readReg(REG_FRFMID) << 8) + readReg(REG_FRFLSB));
}
// set the frequency (in Hz)
void RFM69X::setFrequency(uint32_t freqHz)
{
uint8_t oldMode = _mode;
if (oldMode == RF69_MODE_TX) {
setMode(RF69_MODE_RX);
}
freqHz /= RF69_FSTEP; // divide down by FSTEP to get FRF
writeReg(REG_FRFMSB, freqHz >> 16);
writeReg(REG_FRFMID, freqHz >> 8);
writeReg(REG_FRFLSB, freqHz);
if (oldMode == RF69_MODE_RX) {
setMode(RF69_MODE_SYNTH);
}
setMode(oldMode);
}
void RFM69X::setMode(uint8_t newMode)
{
if (newMode == _mode)
return;
switch (newMode) {
case RF69_MODE_TX:
writeReg(REG_OPMODE, (readReg(REG_OPMODE) & 0xE3) | RF_OPMODE_TRANSMITTER);
if (_isRFM69HW) setHighPowerRegs(true);
break;
case RF69_MODE_RX:
writeReg(REG_OPMODE, (readReg(REG_OPMODE) & 0xE3) | RF_OPMODE_RECEIVER);
if (_isRFM69HW) setHighPowerRegs(false);
break;
case RF69_MODE_SYNTH:
writeReg(REG_OPMODE, (readReg(REG_OPMODE) & 0xE3) | RF_OPMODE_SYNTHESIZER);
break;
case RF69_MODE_STANDBY:
writeReg(REG_OPMODE, (readReg(REG_OPMODE) & 0xE3) | RF_OPMODE_STANDBY);
break;
case RF69_MODE_SLEEP:
writeReg(REG_OPMODE, (readReg(REG_OPMODE) & 0xE3) | RF_OPMODE_SLEEP);
break;
default:
return;
}
// we are using packet mode, so this check is not really needed
// but waiting for mode ready is necessary when going from sleep because the FIFO may not be immediately available from previous mode
while (_mode == RF69_MODE_SLEEP && (readReg(REG_IRQFLAGS1) & RF_IRQFLAGS1_MODEREADY) == 0x00); // wait for ModeReady
_mode = newMode;
}
//put transceiver in sleep mode to save battery - to wake or resume receiving just call receiveDone()
void RFM69X::sleep() {
setMode(RF69_MODE_SLEEP);
}
//set this node's address
void RFM69X::setAddress(uint8_t addr)
{
_address = addr;
writeReg(REG_NODEADRS, _address);
}
//set this node's network id
void RFM69X::setNetwork(uint8_t networkID)
{
writeReg(REG_SYNCVALUE2, networkID);
}
// set *transmit/TX* output power: 0=min, 31=max
// this results in a "weaker" transmitted signal, and directly results in a lower RSSI at the receiver
// the power configurations are explained in the SX1231H datasheet (Table 10 on p21; RegPaLevel p66): http://www.semtech.com/images/datasheet/sx1231h.pdf
// valid powerLevel parameter values are 0-31 and result in a directly proportional effect on the output/transmission power
// this function implements 2 modes as follows:
// - for RFM69W the range is from 0-31 [-18dBm to 13dBm] (PA0 only on RFIO pin)
// - for RFM69HW the range is from 0-31 [5dBm to 20dBm] (PA1 & PA2 on PA_BOOST pin & high Power PA settings - see section 3.3.7 in datasheet, p22)
void RFM69X::setPowerLevel(uint8_t powerLevel)
{
_powerLevel = (powerLevel > 31 ? 31 : powerLevel);
if (_isRFM69HW) _powerLevel /= 2;
writeReg(REG_PALEVEL, (readReg(REG_PALEVEL) & 0xE0) | _powerLevel);
}
bool RFM69X::canSend()
{
if (_mode == RF69_MODE_RX && PAYLOADLEN == 0 && readRSSI() < CSMA_LIMIT) // if signal stronger than -100dBm is detected assume channel activity
{
setMode(RF69_MODE_STANDBY);
return true;
}
return false;
}
void RFM69X::send(uint8_t toAddress, const void* buffer, uint8_t bufferSize, bool requestACK)
{
writeReg(REG_PACKETCONFIG2, (readReg(REG_PACKETCONFIG2) & 0xFB) | RF_PACKET2_RXRESTART); // avoid RX deadlocks
uint32_t now = millis();
while (!canSend() && millis() - now < RF69_CSMA_LIMIT_MS) receiveDone();
sendFrame(toAddress, buffer, bufferSize, requestACK, false);
}
// to increase the chance of getting a packet across, call this function instead of send
// and it handles all the ACK requesting/retrying for you :)
// The only twist is that you have to manually listen to ACK requests on the other side and send back the ACKs
// The reason for the semi-automaton is that the lib is interrupt driven and
// requires user action to read the received data and decide what to do with it
// replies usually take only 5..8ms at 50kbps@915MHz
bool RFM69X::sendWithRetry(uint8_t toAddress, const void* buffer, uint8_t bufferSize, uint8_t retries, uint8_t retryWaitTime) {
uint32_t sentTime;
for (uint8_t i = 0; i <= retries; i++)
{
send(toAddress, buffer, bufferSize, true);
sentTime = millis();
while (millis() - sentTime < retryWaitTime)
{
if (ACKReceived(toAddress))
{
//Serial.print(" ~ms:"); Serial.print(millis() - sentTime);
return true;
}
}
//Serial.print(" RETRY#"); Serial.println(i + 1);
}
return false;
}
// should be polled immediately after sending a packet with ACK request
bool RFM69X::ACKReceived(uint8_t fromNodeID) {
if (receiveDone())
return (SENDERID == fromNodeID || fromNodeID == RF69_BROADCAST_ADDR) && ACK_RECEIVED;
return false;
}
// check whether an ACK was requested in the last received packet (non-broadcasted packet)
bool RFM69X::ACKRequested() {
return ACK_REQUESTED && (TARGETID != RF69_BROADCAST_ADDR);
}
// should be called immediately after reception in case sender wants ACK
void RFM69X::sendACK(const void* buffer, uint8_t bufferSize) {
ACK_REQUESTED = 0; // TWS added to make sure we don't end up in a timing race and infinite loop sending Acks
uint8_t sender = SENDERID;
int16_t _RSSI = RSSI; // save payload received RSSI value
writeReg(REG_PACKETCONFIG2, (readReg(REG_PACKETCONFIG2) & 0xFB) | RF_PACKET2_RXRESTART); // avoid RX deadlocks
uint32_t now = millis();
while (!canSend() && millis() - now < RF69_CSMA_LIMIT_MS) receiveDone();
SENDERID = sender; // TWS: Restore SenderID after it gets wiped out by receiveDone()
sendFrame(sender, buffer, bufferSize, false, true);
RSSI = _RSSI; // restore payload RSSI
}
// internal function
void RFM69X::sendFrame(uint8_t toAddress, const void* buffer, uint8_t bufferSize, bool requestACK, bool sendACK)
{
_gotISR = false; // Ensure pending received interrupt to be cleared before sending a frame(used for ESP32 compatibility)
setMode(RF69_MODE_STANDBY); // turn off receiver to prevent reception while filling fifo
while ((readReg(REG_IRQFLAGS1) & RF_IRQFLAGS1_MODEREADY) == 0x00); // wait for ModeReady
writeReg(REG_DIOMAPPING1, RF_DIOMAPPING1_DIO0_00); // DIO0 is "Packet Sent"
if (bufferSize > RF69_MAX_DATA_LEN) bufferSize = RF69_MAX_DATA_LEN;
// control byte
uint8_t CTLbyte = 0x00;
if (sendACK)
CTLbyte = RFM69_CTL_SENDACK;
else if (requestACK)
CTLbyte = RFM69_CTL_REQACK;
// write to FIFO
select();
SPI.transfer(REG_FIFO | 0x80);
SPI.transfer(bufferSize + 3);
SPI.transfer(toAddress);
SPI.transfer(_address);
SPI.transfer(CTLbyte);
for (uint8_t i = 0; i < bufferSize; i++)
SPI.transfer(((uint8_t*) buffer)[i]);
unselect();
// no need to wait for transmit mode to be ready since its handled by the radio
setMode(RF69_MODE_TX);
uint32_t txStart = millis();
while (digitalRead(_interruptPin) == 0 && millis() - txStart < RF69_TX_LIMIT_MS); // wait for DIO0 to turn HIGH signalling transmission finish
//while (readReg(REG_IRQFLAGS2) & RF_IRQFLAGS2_PACKETSENT == 0x00); // wait for ModeReady
setMode(RF69_MODE_STANDBY);
}
// internal function - interrupt gets called when a packet is received
// interruptHandler has beeing strip down for ESP32 extended compatibility (SPI transfer now moved to interruptHandling())
void RFM69X::interruptHandler() {
if (_mode == RF69_MODE_RX) // Ensure interrupts occurs when RFM69 is in receive mode
{
// Serial.println ("Interrupt Handler activated");
_gotISR = true; // Indicate a possible data correct data message is recieved (check done in interruptHandling function
}
else _gotISR = false;
}
// This function replaces the inetrruptHandler SPI transcation commands that are not allowed in interrupt routine for ESP32
bool RFM69X::interruptHandling() {
if (_gotISR && (readReg(REG_IRQFLAGS2) & RF_IRQFLAGS2_PAYLOADREADY)) // Ensure data is receieved with a correct payload
{
// Serial.println ("Interrupt Handling validated");
RSSI = readRSSI();
setMode(RF69_MODE_STANDBY); // ensure mode is not RX while collecting the SPI data
select();
SPI.transfer(REG_FIFO & 0x7F); // Set SPI register pointer to FIFO
PAYLOADLEN = SPI.transfer(0); // Get the Payload length
PAYLOADLEN = PAYLOADLEN > 66 ? 66 : PAYLOADLEN; // precaution
TARGETID = SPI.transfer(0); // Get the Target ID
if(!(_promiscuousMode || TARGETID == _address || TARGETID == RF69_BROADCAST_ADDR) // match this node's address, or broadcast address or anything in promiscuous mode
|| PAYLOADLEN < 3) // address situation could receive packets that are malformed and don't fit this libraries extra fields
{
PAYLOADLEN = 0;
unselect();
_gotISR=false;
receiveBegin();
return false;
}
SENDERID = SPI.transfer(0); // Get the Sender ID
uint8_t CTLbyte = SPI.transfer(0); // Get the Control byte
DATALEN = PAYLOADLEN - 3; // Actual data lenght (payload - header)
// Serial.print ("PAYLOADLEN = ");Serial.println (PAYLOADLEN);
interruptHook(CTLbyte); // TWS: hook to derived class interrupt function
for (uint8_t i = 0; i < DATALEN; i++) // Get the payload data
{
DATA[i] = SPI.transfer(0);
}
if (DATALEN < RF69_MAX_DATA_LEN) DATA[DATALEN] = 0; // add null at end of string
ACK_RECEIVED = CTLbyte & RFM69_CTL_SENDACK; // extract ACK-received flag
ACK_REQUESTED = CTLbyte & RFM69_CTL_REQACK; // extract ACK-requested flag
unselect();
setMode(RF69_MODE_RX);
_gotISR=false;
return true;
}
else return false;
return false;
}
// internal function
void RFM69X::isr0() { _inISR = true; selfPointer->interruptHandler(); _inISR = false; }
// internal function
void RFM69X::receiveBegin() {
DATALEN = 0;
SENDERID = 0;
TARGETID = 0;
PAYLOADLEN = 0;
ACK_REQUESTED = 0;
ACK_RECEIVED = 0;
RSSI = 0;
if (readReg(REG_IRQFLAGS2) & RF_IRQFLAGS2_PAYLOADREADY)
writeReg(REG_PACKETCONFIG2, (readReg(REG_PACKETCONFIG2) & 0xFB) | RF_PACKET2_RXRESTART); // avoid RX deadlocks
writeReg(REG_DIOMAPPING1, RF_DIOMAPPING1_DIO0_01); // set DIO0 to "PAYLOADREADY" in receive mode
setMode(RF69_MODE_RX);
}
// checks if a packet was received and/or puts transceiver in receive (ie RX or listen) mode
bool RFM69X::receiveDone() {
//ATOMIC_BLOCK(ATOMIC_FORCEON)
//{
interruptHandling(); // Comptue SPI data if RFM69 SPI interrupts occurs (used for ESP32 compatibility)
if (_mode == RF69_MODE_RX && PAYLOADLEN > 0)
{
setMode(RF69_MODE_STANDBY); // enables interrupts
return true;
}
else if (_mode == RF69_MODE_RX) // already in RX no payload yet
{
return false;
}
receiveBegin();
return false;
//}
}
// To enable encryption: radio.encrypt("ABCDEFGHIJKLMNOP");
// To disable encryption: radio.encrypt(null) or radio.encrypt(0)
// KEY HAS TO BE 16 bytes !!!
void RFM69X::encrypt(const char* key) {
setMode(RF69_MODE_STANDBY);
if (key != 0)
{
select();
SPI.transfer(REG_AESKEY1 | 0x80);
for (uint8_t i = 0; i < 16; i++)
SPI.transfer(key[i]);
unselect();
}
writeReg(REG_PACKETCONFIG2, (readReg(REG_PACKETCONFIG2) & 0xFE) | (key ? 1 : 0));
}
// get the received signal strength indicator (RSSI)
int16_t RFM69X::readRSSI(bool forceTrigger) {
int16_t rssi = 0;
if (forceTrigger)
{
// RSSI trigger not needed if DAGC is in continuous mode
writeReg(REG_RSSICONFIG, RF_RSSI_START);
while ((readReg(REG_RSSICONFIG) & RF_RSSI_DONE) == 0x00); // wait for RSSI_Ready
}
rssi = -readReg(REG_RSSIVALUE);
rssi >>= 1;
return rssi;
}
uint8_t RFM69X::readReg(uint8_t addr)
{
select();
SPI.transfer(addr & 0x7F);
uint8_t regval = SPI.transfer(0);
unselect();
return regval;
}
void RFM69X::writeReg(uint8_t addr, uint8_t value)
{
select();
SPI.transfer(addr | 0x80);
SPI.transfer(value);
unselect();
}
// select the RFM69 transceiver (save SPI settings, set CS low)
void RFM69X::select() {
SPI.beginTransaction(settingsA); // Adapted according current SPI library (SPI_HAS_TRANSACTION)
digitalWrite(_slaveSelectPin, LOW);
}
// unselect the RFM69 transceiver (set CS high, restore SPI settings)
void RFM69X::unselect() {
digitalWrite(_slaveSelectPin, HIGH);
SPI.endTransaction(); // Adapted according current SPI library (SPI_HAS_TRANSACTION)
}
// true = disable filtering to capture all frames on network
// false = enable node/broadcast filtering to capture only frames sent to this/broadcast address
void RFM69X::promiscuous(bool onOff) {
_promiscuousMode = onOff;
//writeReg(REG_PACKETCONFIG1, (readReg(REG_PACKETCONFIG1) & 0xF9) | (onOff ? RF_PACKET1_ADRSFILTERING_OFF : RF_PACKET1_ADRSFILTERING_NODEBROADCAST));
}
// for RFM69HW only: you must call setHighPower(true) after initialize() or else transmission won't work
void RFM69X::setHighPower(bool onOff) {
_isRFM69HW = onOff;
writeReg(REG_OCP, _isRFM69HW ? RF_OCP_OFF : RF_OCP_ON);
if (_isRFM69HW) // turning ON
writeReg(REG_PALEVEL, (readReg(REG_PALEVEL) & 0x1F) | RF_PALEVEL_PA1_ON | RF_PALEVEL_PA2_ON); // enable P1 & P2 amplifier stages
else
writeReg(REG_PALEVEL, RF_PALEVEL_PA0_ON | RF_PALEVEL_PA1_OFF | RF_PALEVEL_PA2_OFF | _powerLevel); // enable P0 only
}
// internal function
void RFM69X::setHighPowerRegs(bool onOff) {
writeReg(REG_TESTPA1, onOff ? 0x5D : 0x55);
writeReg(REG_TESTPA2, onOff ? 0x7C : 0x70);
}
// set the slave select (CS) pin
void RFM69X::setCS(uint8_t newSPISlaveSelect) {
_slaveSelectPin = newSPISlaveSelect;
digitalWrite(_slaveSelectPin, HIGH);
pinMode(_slaveSelectPin, OUTPUT);
}
//for debugging
#define REGISTER_DETAIL 0
#if REGISTER_DETAIL
// SERIAL PRINT
// replace Serial.print("string") with SerialPrint("string")
#define SerialPrint(x) SerialPrint_P(PSTR(x))
void SerialWrite ( uint8_t c ) {
Serial.write ( c );
}
void SerialPrint_P(PGM_P str, void (*f)(uint8_t) = SerialWrite ) {
for (uint8_t c; (c = pgm_read_byte(str)); str++) (*f)(c);
}
#endif
void RFM69X::readAllRegs()
{
uint8_t regVal;
#if REGISTER_DETAIL
int capVal;
//... State Variables for intelligent decoding
uint8_t modeFSK = 0;
int bitRate = 0;
int freqDev = 0;
long freqCenter = 0;
#endif
Serial.println("Address - HEX - BIN");
for (uint8_t regAddr = 1; regAddr <= 0x4F; regAddr++)
{
select();
SPI.transfer(regAddr & 0x7F); // send address + r/w bit
regVal = SPI.transfer(0);
unselect();
Serial.print(regAddr, HEX);
Serial.print(" - ");
Serial.print(regVal,HEX);
Serial.print(" - ");
Serial.println(regVal,BIN);
#if REGISTER_DETAIL
switch ( regAddr )
{
case 0x1 : {
SerialPrint ( "Controls the automatic Sequencer ( see section 4.2 )\nSequencerOff : " );
if ( 0x80 & regVal ) {
SerialPrint ( "1 -> Mode is forced by the user\n" );
} else {
SerialPrint ( "0 -> Operating mode as selected with Mode bits in RegOpMode is automatically reached with the Sequencer\n" );
}
SerialPrint( "\nEnables Listen mode, should be enabled whilst in Standby mode:\nListenOn : " );
if ( 0x40 & regVal ) {
SerialPrint ( "1 -> On\n" );
} else {
SerialPrint ( "0 -> Off ( see section 4.3)\n" );
}
SerialPrint( "\nAborts Listen mode when set together with ListenOn=0 See section 4.3.4 for details (Always reads 0.)\n" );
if ( 0x20 & regVal ) {
SerialPrint ( "ERROR - ListenAbort should NEVER return 1 this is a write only register\n" );
}
SerialPrint("\nTransceiver's operating modes:\nMode : ");
capVal = (regVal >> 2) & 0x7;
if ( capVal == 0b000 ) {
SerialPrint ( "000 -> Sleep mode (SLEEP)\n" );
} else if ( capVal = 0b001 ) {
SerialPrint ( "001 -> Standby mode (STDBY)\n" );
} else if ( capVal = 0b010 ) {
SerialPrint ( "010 -> Frequency Synthesizer mode (FS)\n" );
} else if ( capVal = 0b011 ) {
SerialPrint ( "011 -> Transmitter mode (TX)\n" );
} else if ( capVal = 0b100 ) {
SerialPrint ( "100 -> Receiver Mode (RX)\n" );
} else {
Serial.print( capVal, BIN );
SerialPrint ( " -> RESERVED\n" );
}
SerialPrint ( "\n" );
break;
}
case 0x2 : {
SerialPrint("Data Processing mode:\nDataMode : ");
capVal = (regVal >> 5) & 0x3;
if ( capVal == 0b00 ) {
SerialPrint ( "00 -> Packet mode\n" );
} else if ( capVal == 0b01 ) {
SerialPrint ( "01 -> reserved\n" );
} else if ( capVal == 0b10 ) {
SerialPrint ( "10 -> Continuous mode with bit synchronizer\n" );
} else if ( capVal == 0b11 ) {
SerialPrint ( "11 -> Continuous mode without bit synchronizer\n" );
}
SerialPrint("\nModulation scheme:\nModulation Type : ");
capVal = (regVal >> 3) & 0x3;
if ( capVal == 0b00 ) {
SerialPrint ( "00 -> FSK\n" );
modeFSK = 1;
} else if ( capVal == 0b01 ) {
SerialPrint ( "01 -> OOK\n" );
} else if ( capVal == 0b10 ) {
SerialPrint ( "10 -> reserved\n" );
} else if ( capVal == 0b11 ) {
SerialPrint ( "11 -> reserved\n" );
}
SerialPrint("\nData shaping: ");
if ( modeFSK ) {
SerialPrint( "in FSK:\n" );
} else {
SerialPrint( "in OOK:\n" );
}
SerialPrint ("ModulationShaping : ");
capVal = regVal & 0x3;
if ( modeFSK ) {
if ( capVal == 0b00 ) {
SerialPrint ( "00 -> no shaping\n" );
} else if ( capVal == 0b01 ) {
SerialPrint ( "01 -> Gaussian filter, BT = 1.0\n" );
} else if ( capVal == 0b10 ) {
SerialPrint ( "10 -> Gaussian filter, BT = 0.5\n" );
} else if ( capVal == 0b11 ) {
SerialPrint ( "11 -> Gaussian filter, BT = 0.3\n" );
}
} else {
if ( capVal == 0b00 ) {
SerialPrint ( "00 -> no shaping\n" );
} else if ( capVal == 0b01 ) {
SerialPrint ( "01 -> filtering with f(cutoff) = BR\n" );
} else if ( capVal == 0b10 ) {
SerialPrint ( "10 -> filtering with f(cutoff) = 2*BR\n" );
} else if ( capVal == 0b11 ) {
SerialPrint ( "ERROR - 11 is reserved\n" );
}
}
SerialPrint ( "\n" );
break;
}
case 0x3 : {
bitRate = (regVal << 8);
break;
}
case 0x4 : {
bitRate |= regVal;
SerialPrint ( "Bit Rate (Chip Rate when Manchester encoding is enabled)\nBitRate : ");
unsigned long val = 32UL * 1000UL * 1000UL / bitRate;
Serial.println( val );
SerialPrint( "\n" );
break;
}
case 0x5 : {
freqDev = ( (regVal & 0x3f) << 8 );
break;
}
case 0x6 : {
freqDev |= regVal;
SerialPrint( "Frequency deviation\nFdev : " );
unsigned long val = 61UL * freqDev;
Serial.println( val );
SerialPrint ( "\n" );
break;
}
case 0x7 : {
unsigned long tempVal = regVal;
freqCenter = ( tempVal << 16 );
break;
}
case 0x8 : {
unsigned long tempVal = regVal;
freqCenter = freqCenter | ( tempVal << 8 );
break;
}
case 0x9 : {
freqCenter = freqCenter | regVal;
SerialPrint ( "RF Carrier frequency\nFRF : " );
unsigned long val = 61UL * freqCenter;
Serial.println( val );
SerialPrint( "\n" );
break;
}
case 0xa : {
SerialPrint ( "RC calibration control & status\nRcCalDone : " );
if ( 0x40 & regVal ) {
SerialPrint ( "1 -> RC calibration is over\n" );
} else {
SerialPrint ( "0 -> RC calibration is in progress\n" );
}
SerialPrint ( "\n" );
break;
}
case 0xb : {
SerialPrint ( "Improved AFC routine for signals with modulation index lower than 2. Refer to section 3.4.16 for details\nAfcLowBetaOn : " );
if ( 0x20 & regVal ) {
SerialPrint ( "1 -> Improved AFC routine\n" );
} else {
SerialPrint ( "0 -> Standard AFC routine\n" );
}
SerialPrint ( "\n" );
break;
}
case 0xc : {
SerialPrint ( "Reserved\n\n" );
break;
}
case 0xd : {
byte val;
SerialPrint ( "Resolution of Listen mode Idle time (calibrated RC osc):\nListenResolIdle : " );
val = regVal >> 6;
if ( val == 0b00 ) {
SerialPrint ( "00 -> reserved\n" );
} else if ( val == 0b01 ) {
SerialPrint ( "01 -> 64 us\n" );
} else if ( val == 0b10 ) {
SerialPrint ( "10 -> 4.1 ms\n" );
} else if ( val == 0b11 ) {
SerialPrint ( "11 -> 262 ms\n" );
}
SerialPrint ( "\nResolution of Listen mode Rx time (calibrated RC osc):\nListenResolRx : " );
val = (regVal >> 4) & 0x3;
if ( val == 0b00 ) {
SerialPrint ( "00 -> reserved\n" );
} else if ( val == 0b01 ) {
SerialPrint ( "01 -> 64 us\n" );
} else if ( val == 0b10 ) {
SerialPrint ( "10 -> 4.1 ms\n" );
} else if ( val == 0b11 ) {
SerialPrint ( "11 -> 262 ms\n" );
}
SerialPrint ( "\nCriteria for packet acceptance in Listen mode:\nListenCriteria : " );
if ( 0x8 & regVal ) {
SerialPrint ( "1 -> signal strength is above RssiThreshold and SyncAddress matched\n" );
} else {
SerialPrint ( "0 -> signal strength is above RssiThreshold\n" );
}
SerialPrint ( "\nAction taken after acceptance of a packet in Listen mode:\nListenEnd : " );
val = (regVal >> 1 ) & 0x3;
if ( val == 0b00 ) {
SerialPrint ( "00 -> chip stays in Rx mode. Listen mode stops and must be disabled (see section 4.3)\n" );
} else if ( val == 0b01 ) {
SerialPrint ( "01 -> chip stays in Rx mode until PayloadReady or Timeout interrupt occurs. It then goes to the mode defined by Mode. Listen mode stops and must be disabled (see section 4.3)\n" );
} else if ( val == 0b10 ) {
SerialPrint ( "10 -> chip stays in Rx mode until PayloadReady or Timeout occurs. Listen mode then resumes in Idle state. FIFO content is lost at next Rx wakeup.\n" );
} else if ( val == 0b11 ) {
SerialPrint ( "11 -> Reserved\n" );
}
SerialPrint ( "\n" );
break;
}
default : {
}
}
#endif
}
unselect();
}
void RFM69X::readAllRegsCompact() {
// Print the header row and first register entry
Serial.println();Serial.print(" ");
for ( uint8_t reg = 0x00; reg<0x10; reg++ ) {
Serial.print(reg, HEX);
Serial.print(" ");
}
Serial.println();
Serial.print("00: -- ");
// Loop over the registers from 0x01 to 0x7F and print their values
for ( uint8_t reg = 0x01; reg<0x80; reg++ ) {
if ( reg % 16 == 0 ) { // Print the header column entries
Serial.println();
Serial.print( reg, HEX );
Serial.print(": ");
}
// Print the actual register values
uint8_t ret = readReg( reg );
if ( ret < 0x10 ) Serial.print("0"); // Handle values less than 10
Serial.print( ret, HEX);
Serial.print(" ");
}
}
uint8_t RFM69X::readTemperature(uint8_t calFactor) // returns centigrade
{
setMode(RF69_MODE_STANDBY);
writeReg(REG_TEMP1, RF_TEMP1_MEAS_START);
while ((readReg(REG_TEMP1) & RF_TEMP1_MEAS_RUNNING));
return ~readReg(REG_TEMP2) + COURSE_TEMP_COEF + calFactor; // 'complement' corrects the slope, rising temp = rising val
} // COURSE_TEMP_COEF puts reading in the ballpark, user can add additional correction
void RFM69X::rcCalibration()
{
writeReg(REG_OSC1, RF_OSC1_RCCAL_START);
while ((readReg(REG_OSC1) & RF_OSC1_RCCAL_DONE) == 0x00);
}
inline void RFM69X::maybeInterrupts()
{
// Only reenable interrupts if we're not being called from the ISR
if (!_inISR) interrupts();
}