summaryrefslogtreecommitdiff
path: root/.pio/libdeps/esp32-s3-n16r8/RF24/RF24.cpp
blob: 3b923b25b64de295f82c44f8bc7d04a4e747b840 (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
/*
 Copyright (C) 2011 J. Coliz <maniacbug@ymail.com>

 This program is free software; you can redistribute it and/or
 modify it under the terms of the GNU General Public License
 version 2 as published by the Free Software Foundation.
 */

#include "nRF24L01.h"
#include "RF24_config.h"
#include "RF24.h"

/****************************************************************************/

void RF24::csn(bool mode)
{
#if defined(RF24_TINY)
    if (ce_pin != csn_pin) {
        digitalWrite(csn_pin, mode);
    }
    else {
        if (mode == HIGH) {
            PORTB |= (1 << PINB2);                         // SCK->CSN HIGH
            delayMicroseconds(RF24_CSN_SETTLE_HIGH_DELAY); // allow csn to settle.
        }
        else {
            PORTB &= ~(1 << PINB2);                       // SCK->CSN LOW
            delayMicroseconds(RF24_CSN_SETTLE_LOW_DELAY); // allow csn to settle
        }
    }
    // Return, CSN toggle complete
    return;

#elif defined(ARDUINO) && !defined(RF24_SPI_TRANSACTIONS)
    // Minimum ideal SPI bus speed is 2x data rate
    // If we assume 2Mbs data rate and 16Mhz clock, a
    // divider of 4 is the minimum we want.
    // CLK:BUS 8Mhz:2Mhz, 16Mhz:4Mhz, or 20Mhz:5Mhz

    #if !defined(SOFTSPI)
        // applies to SPI_UART and inherent hardware SPI
        #if defined(RF24_SPI_PTR)
    _spi->setBitOrder(MSBFIRST);
    _spi->setDataMode(SPI_MODE0);

            #if !defined(F_CPU) || F_CPU < 20000000
    _spi->setClockDivider(SPI_CLOCK_DIV2);
            #elif F_CPU < 40000000
    _spi->setClockDivider(SPI_CLOCK_DIV4);
            #elif F_CPU < 80000000
    _spi->setClockDivider(SPI_CLOCK_DIV8);
            #elif F_CPU < 160000000
    _spi->setClockDivider(SPI_CLOCK_DIV16);
            #elif F_CPU < 320000000
    _spi->setClockDivider(SPI_CLOCK_DIV32);
            #elif F_CPU < 640000000
    _spi->setClockDivider(SPI_CLOCK_DIV64);
            #elif F_CPU < 1280000000
    _spi->setClockDivider(SPI_CLOCK_DIV128);
            #else // F_CPU >= 1280000000
                #error "Unsupported CPU frequency. Please set correct SPI divider."
            #endif // F_CPU to SPI_CLOCK_DIV translation

        #else // !defined(RF24_SPI_PTR)
    _SPI.setBitOrder(MSBFIRST);
    _SPI.setDataMode(SPI_MODE0);

            #if !defined(F_CPU) || F_CPU < 20000000
    _SPI.setClockDivider(SPI_CLOCK_DIV2);
            #elif F_CPU < 40000000
    _SPI.setClockDivider(SPI_CLOCK_DIV4);
            #elif F_CPU < 80000000
    _SPI.setClockDivider(SPI_CLOCK_DIV8);
            #elif F_CPU < 160000000
    _SPI.setClockDivider(SPI_CLOCK_DIV16);
            #elif F_CPU < 320000000
    _SPI.setClockDivider(SPI_CLOCK_DIV32);
            #elif F_CPU < 640000000
    _SPI.setClockDivider(SPI_CLOCK_DIV64);
            #elif F_CPU < 1280000000
    _SPI.setClockDivider(SPI_CLOCK_DIV128);
            #else // F_CPU >= 1280000000
                #error "Unsupported CPU frequency. Please set correct SPI divider."
            #endif // F_CPU to SPI_CLOCK_DIV translation
        #endif     // !defined(RF24_SPI_PTR)
    #endif         // !defined(SOFTSPI)

#elif defined(RF24_RPi)
    if (!mode)
        _SPI.chipSelect(csn_pin);
#endif // defined(RF24_RPi)

#if !defined(RF24_LINUX)
    digitalWrite(csn_pin, mode);
    delayMicroseconds(csDelay);
#else
    static_cast<void>(mode); // ignore -Wunused-parameter
#endif // !defined(RF24_LINUX)
}

/****************************************************************************/

void RF24::ce(bool level)
{
#ifndef RF24_LINUX
    //Allow for 3-pin use on ATTiny
    if (ce_pin != csn_pin) {
#endif
        digitalWrite(ce_pin, level);
#ifndef RF24_LINUX
    }
#endif
}

/****************************************************************************/

inline void RF24::beginTransaction()
{
#if defined(RF24_SPI_TRANSACTIONS)
    #if defined(RF24_SPI_PTR)
        #if defined(RF24_RP2)
    _spi->beginTransaction(spi_speed);
        #else  // ! defined (RF24_RP2)
    _spi->beginTransaction(SPISettings(spi_speed, MSBFIRST, SPI_MODE0));
        #endif // ! defined (RF24_RP2)
    #else      // !defined(RF24_SPI_PTR)
    _SPI.beginTransaction(SPISettings(spi_speed, MSBFIRST, SPI_MODE0));
    #endif     // !defined(RF24_SPI_PTR)
#endif         // defined (RF24_SPI_TRANSACTIONS)
    csn(LOW);
}

/****************************************************************************/

inline void RF24::endTransaction()
{
    csn(HIGH);
#if defined(RF24_SPI_TRANSACTIONS)
    #if defined(RF24_SPI_PTR)
    _spi->endTransaction();
    #else  // !defined(RF24_SPI_PTR)
    _SPI.endTransaction();
    #endif // !defined(RF24_SPI_PTR)
#endif     // defined (RF24_SPI_TRANSACTIONS)
}

/****************************************************************************/

void RF24::read_register(uint8_t reg, uint8_t* buf, uint8_t len)
{
#if defined(RF24_LINUX) || defined(RF24_RP2)
    beginTransaction(); //configures the spi settings for RPi, locks mutex and setting csn low
    uint8_t* prx = spi_rxbuff;
    uint8_t* ptx = spi_txbuff;
    uint8_t size = static_cast<uint8_t>(len + 1); // Add register value to transmit buffer

    *ptx++ = reg;

    while (len--) {
        *ptx++ = nRF24L01::NOP; // Dummy operation, just for reading
    }

    #if defined(RF24_RP2)
    _spi->transfernb((const uint8_t*)spi_txbuff, spi_rxbuff, size);
    #else  // !defined (RF24_RP2)
    _SPI.transfernb(reinterpret_cast<char*>(spi_txbuff), reinterpret_cast<char*>(spi_rxbuff), size);
    #endif // !defined (RF24_RP2)

    status = *prx++; // status is 1st byte of receive buffer

    // decrement before to skip status byte
    while (--size) {
        *buf++ = *prx++;
    }

    endTransaction(); // unlocks mutex and setting csn high

#else // !defined(RF24_LINUX) && !defined(RF24_RP2)

    beginTransaction();
    #if defined(RF24_SPI_PTR)
    status = _spi->transfer(reg);
    while (len--) {
        *buf++ = _spi->transfer(0xFF);
    }

    #else // !defined(RF24_SPI_PTR)
    status = _SPI.transfer(reg);
    while (len--) {
        *buf++ = _SPI.transfer(0xFF);
    }

    #endif // !defined(RF24_SPI_PTR)
    endTransaction();
#endif     // !defined(RF24_LINUX) && !defined(RF24_RP2)
}

/****************************************************************************/

uint8_t RF24::read_register(uint8_t reg)
{
    uint8_t result;

#if defined(RF24_LINUX) || defined(RF24_RP2)
    beginTransaction();

    uint8_t* prx = spi_rxbuff;
    uint8_t* ptx = spi_txbuff;
    *ptx++ = reg;
    *ptx++ = nRF24L01::NOP; // Dummy operation, just for reading

    #if defined(RF24_RP2)
    _spi->transfernb((const uint8_t*)spi_txbuff, spi_rxbuff, 2);
    #else  // !defined(RF24_RP2)
    _SPI.transfernb(reinterpret_cast<char*>(spi_txbuff), reinterpret_cast<char*>(spi_rxbuff), 2);
    #endif // !defined(RF24_RP2)

    status = *prx;   // status is 1st byte of receive buffer
    result = *++prx; // result is 2nd byte of receive buffer

    endTransaction();
#else // !defined(RF24_LINUX) && !defined(RF24_RP2)

    beginTransaction();
    #if defined(RF24_SPI_PTR)
    status = _spi->transfer(reg);
    result = _spi->transfer(0xff);

    #else // !defined(RF24_SPI_PTR)
    status = _SPI.transfer(reg);
    result = _SPI.transfer(0xff);

    #endif // !defined(RF24_SPI_PTR)
    endTransaction();
#endif     // !defined(RF24_LINUX) && !defined(RF24_RP2)

    return result;
}

/****************************************************************************/

void RF24::write_register(uint8_t reg, const uint8_t* buf, uint8_t len)
{
#if defined(RF24_LINUX) || defined(RF24_RP2)
    beginTransaction();
    uint8_t* prx = spi_rxbuff;
    uint8_t* ptx = spi_txbuff;
    uint8_t size = static_cast<uint8_t>(len + 1); // Add register value to transmit buffer

    *ptx++ = (nRF24L01::W_REGISTER | reg);
    while (len--) {
        *ptx++ = *buf++;
    }

    #if defined(RF24_RP2)
    _spi->transfernb((const uint8_t*)spi_txbuff, spi_rxbuff, size);
    #else  // !defined(RF24_RP2)
    _SPI.transfernb(reinterpret_cast<char*>(spi_txbuff), reinterpret_cast<char*>(spi_rxbuff), size);
    #endif // !defined(RF24_RP2)

    status = *prx; // status is 1st byte of receive buffer
    endTransaction();
#else // !defined(RF24_LINUX) && !defined(RF24_RP2)

    beginTransaction();
    #if defined(RF24_SPI_PTR)
    status = _spi->transfer(nRF24L01::W_REGISTER | reg);
    while (len--) {
        _spi->transfer(*buf++);
    }

    #else // !defined(RF24_SPI_PTR)
    status = _SPI.transfer(nRF24L01::W_REGISTER | reg);
    while (len--) {
        _SPI.transfer(*buf++);
    }

    #endif // !defined(RF24_SPI_PTR)
    endTransaction();
#endif     // !defined(RF24_LINUX) && !defined(RF24_RP2)
}

/****************************************************************************/

void RF24::write_register(uint8_t reg, uint8_t value)
{
    IF_RF24_DEBUG(printf_P(PSTR("write_register(%02x,%02x)\r\n"), reg, value));
#if defined(RF24_LINUX) || defined(RF24_RP2)
    beginTransaction();
    uint8_t* prx = spi_rxbuff;
    uint8_t* ptx = spi_txbuff;
    *ptx++ = (nRF24L01::W_REGISTER | reg);
    *ptx = value;

    #if defined(RF24_RP2)
    _spi->transfernb((const uint8_t*)spi_txbuff, spi_rxbuff, 2);
    #else  // !defined(RF24_RP2)
    _SPI.transfernb(reinterpret_cast<char*>(spi_txbuff), reinterpret_cast<char*>(spi_rxbuff), 2);
    #endif // !defined(RF24_RP2)

    status = *prx++; // status is 1st byte of receive buffer
    endTransaction();
#else // !defined(RF24_LINUX) && !defined(RF24_RP2)

    beginTransaction();
    #if defined(RF24_SPI_PTR)
    status = _spi->transfer(nRF24L01::W_REGISTER | reg);
    _spi->transfer(value);
    #else  // !defined(RF24_SPI_PTR)
    status = _SPI.transfer(nRF24L01::W_REGISTER | reg);
    _SPI.transfer(value);
    #endif // !defined(RF24_SPI_PTR)
    endTransaction();
#endif     // !defined(RF24_LINUX) && !defined(RF24_RP2)
}

/****************************************************************************/

void RF24::write_payload(const void* buf, uint8_t data_len, const uint8_t writeType)
{
    const uint8_t* current = reinterpret_cast<const uint8_t*>(buf);

    uint8_t blank_len = !data_len ? 1 : 0;
    if (!dynamic_payloads_enabled) {
        data_len = rf24_min(data_len, payload_size);
        blank_len = static_cast<uint8_t>(payload_size - data_len);
    }
    else {
        data_len = rf24_min(data_len, static_cast<uint8_t>(32));
    }

    //printf("[Writing %u bytes %u blanks]",data_len,blank_len);
    IF_RF24_DEBUG(printf_P("[Writing %u bytes %u blanks]\n", data_len, blank_len););

#if defined(RF24_LINUX) || defined(RF24_RP2)
    beginTransaction();
    uint8_t* prx = spi_rxbuff;
    uint8_t* ptx = spi_txbuff;
    uint8_t size;
    size = static_cast<uint8_t>(data_len + blank_len + 1); // Add register value to transmit buffer

    *ptx++ = writeType;
    while (data_len--) {
        *ptx++ = *current++;
    }

    while (blank_len--) {
        *ptx++ = 0;
    }

    #if defined(RF24_RP2)
    _spi->transfernb((const uint8_t*)spi_txbuff, spi_rxbuff, size);
    #else  // !defined(RF24_RP2)
    _SPI.transfernb(reinterpret_cast<char*>(spi_txbuff), reinterpret_cast<char*>(spi_rxbuff), size);
    #endif // !defined(RF24_RP2)

    status = *prx; // status is 1st byte of receive buffer
    endTransaction();

#else // !defined(RF24_LINUX) && !defined(RF24_RP2)

    beginTransaction();
    #if defined(RF24_SPI_PTR)
    status = _spi->transfer(writeType);
    while (data_len--) {
        _spi->transfer(*current++);
    }

    while (blank_len--) {
        _spi->transfer(0);
    }

    #else // !defined(RF24_SPI_PTR)
    status = _SPI.transfer(writeType);
    while (data_len--) {
        _SPI.transfer(*current++);
    }

    while (blank_len--) {
        _SPI.transfer(0);
    }

    #endif // !defined(RF24_SPI_PTR)
    endTransaction();
#endif     // !defined(RF24_LINUX) && !defined(RF24_RP2)
}

/****************************************************************************/

void RF24::read_payload(void* buf, uint8_t data_len)
{
    uint8_t* current = reinterpret_cast<uint8_t*>(buf);

    uint8_t blank_len = 0;
    if (!dynamic_payloads_enabled) {
        data_len = rf24_min(data_len, payload_size);
        blank_len = static_cast<uint8_t>(payload_size - data_len);
    }
    else {
        data_len = rf24_min(data_len, static_cast<uint8_t>(32));
    }

    //printf("[Reading %u bytes %u blanks]",data_len,blank_len);

    IF_RF24_DEBUG(printf_P("[Reading %u bytes %u blanks]\n", data_len, blank_len););

#if defined(RF24_LINUX) || defined(RF24_RP2)
    beginTransaction();
    uint8_t* prx = spi_rxbuff;
    uint8_t* ptx = spi_txbuff;
    uint8_t size;
    size = static_cast<uint8_t>(data_len + blank_len + 1); // Add register value to transmit buffer

    *ptx++ = nRF24L01::R_RX_PAYLOAD;
    while (--size) {
        *ptx++ = nRF24L01::NOP;
    }

    size = static_cast<uint8_t>(data_len + blank_len + 1); // Size has been lost during while, re affect

    #if defined(RF24_RP2)
    _spi->transfernb((const uint8_t*)spi_txbuff, spi_rxbuff, size);
    #else  // !defined(RF24_RP2)
    _SPI.transfernb(reinterpret_cast<char*>(spi_txbuff), reinterpret_cast<char*>(spi_rxbuff), size);
    #endif // !defined(RF24_RP2)

    status = *prx++; // 1st byte is status

    if (data_len > 0) {
        // Decrement before to skip 1st status byte
        while (--data_len) {
            *current++ = *prx++;
        }

        *current = *prx;
    }
    endTransaction();
#else // !defined(RF24_LINUX) && !defined(RF24_RP2)

    beginTransaction();
    #if defined(RF24_SPI_PTR)
    status = _spi->transfer(nRF24L01::R_RX_PAYLOAD);
    while (data_len--) {
        *current++ = _spi->transfer(0xFF);
    }

    while (blank_len--) {
        _spi->transfer(0xFF);
    }

    #else // !defined(RF24_SPI_PTR)
    status = _SPI.transfer(nRF24L01::R_RX_PAYLOAD);
    while (data_len--) {
        *current++ = _SPI.transfer(0xFF);
    }

    while (blank_len--) {
        _SPI.transfer(0xff);
    }

    #endif // !defined(RF24_SPI_PTR)
    endTransaction();

#endif // !defined(RF24_LINUX) && !defined(RF24_RP2)
}

/****************************************************************************/

uint8_t RF24::flush_rx(void)
{
    read_register(nRF24L01::FLUSH_RX, (uint8_t*)nullptr, 0);
    IF_RF24_DEBUG(printf_P("[Flushing RX FIFO]"););
    return status;
}

/****************************************************************************/

uint8_t RF24::flush_tx(void)
{
    read_register(nRF24L01::FLUSH_TX, (uint8_t*)nullptr, 0);
    IF_RF24_DEBUG(printf_P("[Flushing RX FIFO]"););
    return status;
}

/****************************************************************************/
#if !defined(MINIMAL)

void RF24::printStatus(uint8_t flags)
{
    printf_P(PSTR("RX_DR=%x TX_DS=%x TX_DF=%x RX_PIPE=%x TX_FULL=%x\r\n"),
             (flags & RF24_RX_DR) ? 1 : 0,
             (flags & RF24_TX_DS) ? 1 : 0,
             (flags & RF24_TX_DF) ? 1 : 0,
             (flags >> nRF24L01::RX_P_NO) & 0x07,
             (flags & _BV(nRF24L01::TX_FULL)) ? 1 : 0);
}

/****************************************************************************/

void RF24::print_observe_tx(uint8_t value)
{
    printf_P(PSTR("OBSERVE_TX=%02x: PLOS_CNT=%x ARC_CNT=%x\r\n"), value, (value >> nRF24L01::PLOS_CNT) & 0x0F, (value >> nRF24L01::ARC_CNT) & 0x0F);
}

/****************************************************************************/

void RF24::print_byte_register(const char* name, uint8_t reg, uint8_t qty)
{
    printf_P(PSTR(PRIPSTR
                  "\t="),
             name);
    while (qty--) {
        printf_P(PSTR(" 0x%02x"), read_register(reg++));
    }
    printf_P(PSTR("\r\n"));
}

/****************************************************************************/

void RF24::print_address_register(const char* name, uint8_t reg, uint8_t qty)
{

    printf_P(PSTR(PRIPSTR
                  "\t="),
             name);
    while (qty--) {
        uint8_t* buffer = new uint8_t[addr_width];
        read_register(reg++, buffer, addr_width);

        printf_P(PSTR(" 0x"));
        uint8_t* bufptr = buffer + addr_width;
        while (--bufptr >= buffer) {
            printf_P(PSTR("%02x"), *bufptr); // NOLINT: clang-tidy seems to emit a false positive about zero-allocated memory here (*bufptr)
        }
        delete[] buffer;
    }
    printf_P(PSTR("\r\n"));
}

/****************************************************************************/

uint8_t RF24::sprintf_address_register(char* out_buffer, uint8_t reg, uint8_t qty)
{
    uint8_t offset = 0;
    uint8_t* read_buffer = new uint8_t[addr_width];
    while (qty--) {
        read_register(reg++, read_buffer, addr_width);
        uint8_t* bufptr = read_buffer + addr_width;
        while (--bufptr >= read_buffer) {
            offset += sprintf_P(out_buffer + offset, PSTR("%02X"), *bufptr); // NOLINT(clang-analyzer-cplusplus.NewDelete)
        }
    }
    delete[] read_buffer;
    return offset;
}
#endif // !defined(MINIMAL)

/****************************************************************************/

RF24::RF24(rf24_gpio_pin_t _cepin, rf24_gpio_pin_t _cspin, uint32_t _spi_speed)
    : ce_pin(_cepin),
      csn_pin(_cspin),
      spi_speed(_spi_speed),
      payload_size(32),
      _is_p_variant(false),
      _is_p0_rx(false),
      addr_width(5),
      dynamic_payloads_enabled(true),
#if defined FAILURE_HANDLING
      failureDetected(0),
#endif
      csDelay(5)
{
    _init_obj();
}

/****************************************************************************/

RF24::RF24(uint32_t _spi_speed)
    : ce_pin(RF24_PIN_INVALID),
      csn_pin(RF24_PIN_INVALID),
      spi_speed(_spi_speed),
      payload_size(32),
      _is_p_variant(false),
      _is_p0_rx(false),
      addr_width(5),
      dynamic_payloads_enabled(true),
#if defined FAILURE_HANDLING
      failureDetected(0),
#endif
      csDelay(5)
{
    _init_obj();
}

/****************************************************************************/

void RF24::_init_obj()
{
    // Use a pointer on the Arduino platform

#if defined(RF24_SPI_PTR) && !defined(RF24_RP2)
    _spi = &SPI;
#endif // defined (RF24_SPI_PTR)

    if (spi_speed <= 35000) { //Handle old BCM2835 speed constants, default to RF24_SPI_SPEED
        spi_speed = RF24_SPI_SPEED;
    }
}

/****************************************************************************/

void RF24::setChannel(uint8_t channel)
{
    const uint8_t max_channel = 125;
    write_register(nRF24L01::RF_CH, rf24_min(channel, max_channel));
}

uint8_t RF24::getChannel()
{
    return read_register(nRF24L01::RF_CH);
}

/****************************************************************************/

void RF24::setPayloadSize(uint8_t size)
{
    // payload size must be in range [1, 32]
    payload_size = static_cast<uint8_t>(rf24_max(1, rf24_min(32, size)));

    // write static payload size setting for all pipes
    for (uint8_t i = 0; i < 6; ++i) {
        write_register(static_cast<uint8_t>(nRF24L01::RX_PW_P0 + i), payload_size);
    }
}

/****************************************************************************/

uint8_t RF24::getPayloadSize(void)
{
    return payload_size;
}

/****************************************************************************/

#if !defined(MINIMAL)

static const PROGMEM char rf24_datarate_e_str_0[] = "= 1 MBPS";
static const PROGMEM char rf24_datarate_e_str_1[] = "= 2 MBPS";
static const PROGMEM char rf24_datarate_e_str_2[] = "= 250 KBPS";
static const PROGMEM char* const rf24_datarate_e_str_P[] = {
    rf24_datarate_e_str_0,
    rf24_datarate_e_str_1,
    rf24_datarate_e_str_2,
};
static const PROGMEM char rf24_model_e_str_0[] = "nRF24L01";
static const PROGMEM char rf24_model_e_str_1[] = "nRF24L01+";
static const PROGMEM char* const rf24_model_e_str_P[] = {
    rf24_model_e_str_0,
    rf24_model_e_str_1,
};
static const PROGMEM char rf24_crclength_e_str_0[] = "= Disabled";
static const PROGMEM char rf24_crclength_e_str_1[] = "= 8 bits";
static const PROGMEM char rf24_crclength_e_str_2[] = "= 16 bits";
static const PROGMEM char* const rf24_crclength_e_str_P[] = {
    rf24_crclength_e_str_0,
    rf24_crclength_e_str_1,
    rf24_crclength_e_str_2,
};
static const PROGMEM char rf24_pa_dbm_e_str_0[] = "= PA_MIN";
static const PROGMEM char rf24_pa_dbm_e_str_1[] = "= PA_LOW";
static const PROGMEM char rf24_pa_dbm_e_str_2[] = "= PA_HIGH";
static const PROGMEM char rf24_pa_dbm_e_str_3[] = "= PA_MAX";
static const PROGMEM char* const rf24_pa_dbm_e_str_P[] = {
    rf24_pa_dbm_e_str_0,
    rf24_pa_dbm_e_str_1,
    rf24_pa_dbm_e_str_2,
    rf24_pa_dbm_e_str_3,
};

static const PROGMEM char rf24_feature_e_str_on[] = "= Enabled";
static const PROGMEM char rf24_feature_e_str_allowed[] = "= Allowed";
static const PROGMEM char rf24_feature_e_str_open[] = " open ";
static const PROGMEM char rf24_feature_e_str_closed[] = "closed";
static const PROGMEM char* const rf24_feature_e_str_P[] = {
    rf24_crclength_e_str_0,
    rf24_feature_e_str_on,
    rf24_feature_e_str_allowed,
    rf24_feature_e_str_closed,
    rf24_feature_e_str_open,
};

void RF24::printDetails(void)
{

    #if defined(RF24_LINUX)
    printf("================ SPI Configuration ================\n");
    uint8_t bus_ce = static_cast<uint8_t>(csn_pin % 10);
    uint8_t bus_numb = static_cast<uint8_t>((csn_pin - bus_ce) / 10);
    printf("CSN Pin\t\t= /dev/spidev%d.%d\n", bus_numb, bus_ce);
    printf("CE Pin\t\t= Custom GPIO%d\n", ce_pin);
    #endif
    printf_P(PSTR("SPI Speedz\t= %d Mhz\n"), static_cast<uint8_t>(spi_speed / 1000000)); //Print the SPI speed on non-Linux devices
    #if defined(RF24_LINUX)
    printf("================ NRF Configuration ================\n");
    #endif // defined(RF24_LINUX)

    uint8_t status = update();
    printf_P(PSTR("STATUS\t\t= 0x%02x "), status);
    printStatus(status);

    print_address_register(PSTR("RX_ADDR_P0-1"), nRF24L01::RX_ADDR_P0, 2);
    print_byte_register(PSTR("RX_ADDR_P2-5"), nRF24L01::RX_ADDR_P2, 4);
    print_address_register(PSTR("TX_ADDR\t"), nRF24L01::TX_ADDR);

    print_byte_register(PSTR("RX_PW_P0-6"), nRF24L01::RX_PW_P0, 6);
    print_byte_register(PSTR("EN_AA\t"), nRF24L01::EN_AA);
    print_byte_register(PSTR("EN_RXADDR"), nRF24L01::EN_RXADDR);
    print_byte_register(PSTR("RF_CH\t"), nRF24L01::RF_CH);
    print_byte_register(PSTR("RF_SETUP"), nRF24L01::RF_SETUP);
    print_byte_register(PSTR("CONFIG\t"), nRF24L01::CONFIG);
    print_byte_register(PSTR("DYNPD/FEATURE"), nRF24L01::DYNPD, 2);

    printf_P(PSTR("Data Rate\t" PRIPSTR
                  "\r\n"),
             (char*)(pgm_read_ptr(&rf24_datarate_e_str_P[getDataRate()])));
    printf_P(PSTR("Model\t\t= " PRIPSTR
                  "\r\n"),
             (char*)(pgm_read_ptr(&rf24_model_e_str_P[isPVariant()])));
    printf_P(PSTR("CRC Length\t" PRIPSTR
                  "\r\n"),
             (char*)(pgm_read_ptr(&rf24_crclength_e_str_P[getCRCLength()])));
    printf_P(PSTR("PA Power\t" PRIPSTR
                  "\r\n"),
             (char*)(pgm_read_ptr(&rf24_pa_dbm_e_str_P[getPALevel()])));
    printf_P(PSTR("ARC\t\t= %d\r\n"), getARC());
}

void RF24::printPrettyDetails(void)
{

    #if defined(RF24_LINUX)
    printf("================ SPI Configuration ================\n");
    uint8_t bus_ce = static_cast<uint8_t>(csn_pin % 10);
    uint8_t bus_numb = static_cast<uint8_t>((csn_pin - bus_ce) / 10);
    printf("CSN Pin\t\t\t= /dev/spidev%d.%d\n", bus_numb, bus_ce);
    printf("CE Pin\t\t\t= Custom GPIO%d\n", ce_pin);
    #endif
    printf_P(PSTR("SPI Frequency\t\t= %d Mhz\n"), static_cast<uint8_t>(spi_speed / 1000000)); //Print the SPI speed on non-Linux devices
    #if defined(RF24_LINUX)
    printf("================ NRF Configuration ================\n");
    #endif // defined(RF24_LINUX)

    uint8_t channel = getChannel();
    uint16_t frequency = static_cast<uint16_t>(channel + 2400);
    printf_P(PSTR("Channel\t\t\t= %u (~ %u MHz)\r\n"), channel, frequency);
    printf_P(PSTR("Model\t\t\t= " PRIPSTR
                  "\r\n"),
             (char*)(pgm_read_ptr(&rf24_model_e_str_P[isPVariant()])));

    printf_P(PSTR("RF Data Rate\t\t" PRIPSTR
                  "\r\n"),
             (char*)(pgm_read_ptr(&rf24_datarate_e_str_P[getDataRate()])));
    printf_P(PSTR("RF Power Amplifier\t" PRIPSTR
                  "\r\n"),
             (char*)(pgm_read_ptr(&rf24_pa_dbm_e_str_P[getPALevel()])));
    printf_P(PSTR("RF Low Noise Amplifier\t" PRIPSTR
                  "\r\n"),
             (char*)(pgm_read_ptr(&rf24_feature_e_str_P[static_cast<uint8_t>((read_register(nRF24L01::RF_SETUP) & 1) * 1)])));
    printf_P(PSTR("CRC Length\t\t" PRIPSTR
                  "\r\n"),
             (char*)(pgm_read_ptr(&rf24_crclength_e_str_P[getCRCLength()])));
    printf_P(PSTR("Address Length\t\t= %d bytes\r\n"), (read_register(nRF24L01::SETUP_AW) & 3) + 2);
    printf_P(PSTR("Static Payload Length\t= %d bytes\r\n"), getPayloadSize());

    uint8_t setupRetry = read_register(nRF24L01::SETUP_RETR);
    printf_P(PSTR("Auto Retry Delay\t= %d microseconds\r\n"), (setupRetry >> nRF24L01::ARD) * 250 + 250);
    printf_P(PSTR("Auto Retry Attempts\t= %d maximum\r\n"), setupRetry & 0x0F);

    uint8_t observeTx = read_register(nRF24L01::OBSERVE_TX);
    printf_P(PSTR("Packets lost on\n    current channel\t= %d\r\n"), observeTx >> 4);
    printf_P(PSTR("Retry attempts made for\n    last transmission\t= %d\r\n"), observeTx & 0x0F);

    uint8_t features = read_register(nRF24L01::FEATURE);
    printf_P(PSTR("Multicast\t\t" PRIPSTR
                  "\r\n"),
             (char*)(pgm_read_ptr(&rf24_feature_e_str_P[static_cast<uint8_t>(static_cast<bool>(features & _BV(nRF24L01::EN_DYN_ACK)) * 2)])));
    printf_P(PSTR("Custom ACK Payload\t" PRIPSTR
                  "\r\n"),
             (char*)(pgm_read_ptr(&rf24_feature_e_str_P[static_cast<uint8_t>(static_cast<bool>(features & _BV(nRF24L01::EN_ACK_PAY)) * 1)])));

    uint8_t dynPl = read_register(nRF24L01::DYNPD);
    printf_P(PSTR("Dynamic Payloads\t" PRIPSTR
                  "\r\n"),
             (char*)(pgm_read_ptr(&rf24_feature_e_str_P[static_cast<uint8_t>((dynPl && (features & _BV(nRF24L01::EN_DPL))) * 1)])));

    uint8_t autoAck = read_register(nRF24L01::EN_AA);
    if (autoAck == 0x3F || autoAck == 0) {
        // all pipes have the same configuration about auto-ack feature
        printf_P(PSTR("Auto Acknowledgment\t" PRIPSTR
                      "\r\n"),
                 (char*)(pgm_read_ptr(&rf24_feature_e_str_P[static_cast<uint8_t>(static_cast<bool>(autoAck) * 1)])));
    }
    else {
        // representation per pipe
        printf_P(PSTR("Auto Acknowledgment\t= 0b%c%c%c%c%c%c\r\n"),
                 static_cast<char>(static_cast<bool>(autoAck & _BV(nRF24L01::ENAA_P5)) + 48),
                 static_cast<char>(static_cast<bool>(autoAck & _BV(nRF24L01::ENAA_P4)) + 48),
                 static_cast<char>(static_cast<bool>(autoAck & _BV(nRF24L01::ENAA_P3)) + 48),
                 static_cast<char>(static_cast<bool>(autoAck & _BV(nRF24L01::ENAA_P2)) + 48),
                 static_cast<char>(static_cast<bool>(autoAck & _BV(nRF24L01::ENAA_P1)) + 48),
                 static_cast<char>(static_cast<bool>(autoAck & _BV(nRF24L01::ENAA_P0)) + 48));
    }

    config_reg = read_register(nRF24L01::CONFIG);
    printf_P(PSTR("Primary Mode\t\t= %cX\r\n"), config_reg & _BV(nRF24L01::PRIM_RX) ? 'R' : 'T');
    print_address_register(PSTR("TX address\t"), nRF24L01::TX_ADDR);

    uint8_t openPipes = read_register(nRF24L01::EN_RXADDR);
    for (uint8_t i = 0; i < 6; ++i) {
        bool isOpen = openPipes & _BV(i);
        printf_P(PSTR("pipe %u (" PRIPSTR
                      ") bound"),
                 i, (char*)(pgm_read_ptr(&rf24_feature_e_str_P[isOpen + 3])));
        if (i < 2) {
            print_address_register(PSTR(""), static_cast<uint8_t>(nRF24L01::RX_ADDR_P0 + i));
        }
        else {
            print_byte_register(PSTR(""), static_cast<uint8_t>(nRF24L01::RX_ADDR_P0 + i));
        }
    }
}

/****************************************************************************/

uint16_t RF24::sprintfPrettyDetails(char* debugging_information)
{
    const char* format_string = PSTR(
        "================ SPI Configuration ================\n"
        "CSN Pin\t\t\t= %d\n"
        "CE Pin\t\t\t= %d\n"
        "SPI Frequency\t\t= %d Mhz\n"
        "================ NRF Configuration ================\n"
        "Channel\t\t\t= %u (~ %u MHz)\n"
        "RF Data Rate\t\t" PRIPSTR "\n"
        "RF Power Amplifier\t" PRIPSTR "\n"
        "RF Low Noise Amplifier\t" PRIPSTR "\n"
        "CRC Length\t\t" PRIPSTR "\n"
        "Address Length\t\t= %d bytes\n"
        "Static Payload Length\t= %d bytes\n"
        "Auto Retry Delay\t= %d microseconds\n"
        "Auto Retry Attempts\t= %d maximum\n"
        "Packets lost on\n    current channel\t= %d\r\n"
        "Retry attempts made for\n    last transmission\t= %d\r\n"
        "Multicast\t\t" PRIPSTR "\n"
        "Custom ACK Payload\t" PRIPSTR "\n"
        "Dynamic Payloads\t" PRIPSTR "\n"
        "Auto Acknowledgment\t");
    const char* format_str2 = PSTR("\nPrimary Mode\t\t= %cX\nTX address\t\t= 0x");
    const char* format_str3 = PSTR("\nPipe %d (" PRIPSTR ") bound\t= 0x");

    uint16_t offset = sprintf_P(
        debugging_information, format_string, csn_pin, ce_pin,
        static_cast<uint8_t>(spi_speed / 1000000), getChannel(),
        static_cast<uint16_t>(getChannel() + 2400),
        (char*)(pgm_read_ptr(&rf24_datarate_e_str_P[getDataRate()])),
        (char*)(pgm_read_ptr(&rf24_pa_dbm_e_str_P[getPALevel()])),
        (char*)(pgm_read_ptr(&rf24_feature_e_str_P[static_cast<uint8_t>((read_register(nRF24L01::RF_SETUP) & 1) * 1)])),
        (char*)(pgm_read_ptr(&rf24_crclength_e_str_P[getCRCLength()])),
        ((read_register(nRF24L01::SETUP_AW) & 3) + 2), getPayloadSize(),
        ((read_register(nRF24L01::SETUP_RETR) >> nRF24L01::ARD) * 250 + 250),
        (read_register(nRF24L01::SETUP_RETR) & 0x0F), (read_register(nRF24L01::OBSERVE_TX) >> 4),
        (read_register(nRF24L01::OBSERVE_TX) & 0x0F),
        (char*)(pgm_read_ptr(&rf24_feature_e_str_P[static_cast<uint8_t>(static_cast<bool>(read_register(nRF24L01::FEATURE) & _BV(nRF24L01::EN_DYN_ACK)) * 2)])),
        (char*)(pgm_read_ptr(&rf24_feature_e_str_P[static_cast<uint8_t>(static_cast<bool>(read_register(nRF24L01::FEATURE) & _BV(nRF24L01::EN_ACK_PAY)) * 1)])),
        (char*)(pgm_read_ptr(&rf24_feature_e_str_P[static_cast<uint8_t>((read_register(nRF24L01::DYNPD) && (read_register(nRF24L01::FEATURE) & _BV(nRF24L01::EN_DPL))) * 1)])));
    uint8_t autoAck = read_register(nRF24L01::EN_AA);
    if (autoAck == 0x3F || autoAck == 0) {
        // all pipes have the same configuration about auto-ack feature
        offset += sprintf_P(
            debugging_information + offset, PSTR("" PRIPSTR ""),
            (char*)(pgm_read_ptr(&rf24_feature_e_str_P[static_cast<uint8_t>(static_cast<bool>(autoAck) * 1)])));
    }
    else {
        // representation per pipe
        offset += sprintf_P(
            debugging_information + offset, PSTR("= 0b%c%c%c%c%c%c"),
            static_cast<char>(static_cast<bool>(autoAck & _BV(nRF24L01::ENAA_P5)) + 48),
            static_cast<char>(static_cast<bool>(autoAck & _BV(nRF24L01::ENAA_P4)) + 48),
            static_cast<char>(static_cast<bool>(autoAck & _BV(nRF24L01::ENAA_P3)) + 48),
            static_cast<char>(static_cast<bool>(autoAck & _BV(nRF24L01::ENAA_P2)) + 48),
            static_cast<char>(static_cast<bool>(autoAck & _BV(nRF24L01::ENAA_P1)) + 48),
            static_cast<char>(static_cast<bool>(autoAck & _BV(nRF24L01::ENAA_P0)) + 48));
    }
    offset += sprintf_P(
        debugging_information + offset, format_str2,
        (read_register(nRF24L01::CONFIG) & _BV(nRF24L01::PRIM_RX) ? 'R' : 'T'));
    offset += sprintf_address_register(debugging_information + offset, nRF24L01::TX_ADDR);
    uint8_t openPipes = read_register(nRF24L01::EN_RXADDR);
    for (uint8_t i = 0; i < 6; ++i) {
        offset += sprintf_P(
            debugging_information + offset, format_str3,
            i, ((char*)(pgm_read_ptr(&rf24_feature_e_str_P[static_cast<bool>(openPipes & _BV(i)) + 3]))));
        if (i < 2) {
            offset += sprintf_address_register(
                debugging_information + offset, static_cast<uint8_t>(nRF24L01::RX_ADDR_P0 + i));
        }
        else {
            offset += sprintf_P(
                debugging_information + offset, PSTR("%02X"),
                read_register(static_cast<uint8_t>(nRF24L01::RX_ADDR_P0 + i)));
        }
    }
    return offset;
}

/****************************************************************************/

void RF24::encodeRadioDetails(uint8_t* encoded_details)
{
    uint8_t end = nRF24L01::FEATURE + 1;
    for (uint8_t i = nRF24L01::CONFIG; i < end; ++i) {
        if (i == nRF24L01::RX_ADDR_P0 || i == nRF24L01::RX_ADDR_P1 || i == nRF24L01::TX_ADDR) {
            // get 40-bit registers
            read_register(i, encoded_details, 5);
            encoded_details += 5;
        }
        else if (i != 0x18 && i != 0x19 && i != 0x1a && i != 0x1b) { // skip undocumented registers
            // get single byte registers
            *encoded_details++ = read_register(i);
        }
    }
    *encoded_details++ = ce_pin >> 4;
    *encoded_details++ = ce_pin & 0xFF;
    *encoded_details++ = csn_pin >> 4;
    *encoded_details++ = csn_pin & 0xFF;
    *encoded_details = static_cast<uint8_t>((spi_speed / 1000000) | _BV(_is_p_variant * 4));
}
#endif // !defined(MINIMAL)

/****************************************************************************/
#if defined(RF24_SPI_PTR) || defined(DOXYGEN_FORCED)
// does not apply to RF24_LINUX

bool RF24::begin(_SPI* spiBus)
{
    _spi = spiBus;
    return _init_pins() && _init_radio();
}

/****************************************************************************/

bool RF24::begin(_SPI* spiBus, rf24_gpio_pin_t _cepin, rf24_gpio_pin_t _cspin)
{
    ce_pin = _cepin;
    csn_pin = _cspin;
    return begin(spiBus);
}

#endif // defined (RF24_SPI_PTR) || defined (DOXYGEN_FORCED)

/****************************************************************************/

bool RF24::begin(rf24_gpio_pin_t _cepin, rf24_gpio_pin_t _cspin)
{
    ce_pin = _cepin;
    csn_pin = _cspin;
    return begin();
}

/****************************************************************************/

bool RF24::begin(void)
{
#if defined(RF24_LINUX)
    #if defined(RF24_RPi)
    switch (csn_pin) { // Ensure valid hardware CS pin
        case 0: break;
        case 1: break;
        // Allow BCM2835 enums for RPi
        case 8: csn_pin = 0; break;
        case 7: csn_pin = 1; break;
        case 18: csn_pin = 10; break; // to make it work on SPI1
        case 17: csn_pin = 11; break;
        case 16: csn_pin = 12; break;
        default: csn_pin = 0; break;
    }
    #endif // RF24_RPi

    _SPI.begin(csn_pin, spi_speed);

#elif defined(XMEGA_D3)
    _spi->begin(csn_pin);

#elif defined(RF24_RP2)
    _spi = new SPI();
    _spi->begin(PICO_DEFAULT_SPI ? spi1 : spi0);

#else // using an Arduino platform || defined (LITTLEWIRE)

    #if defined(RF24_SPI_PTR)
    _spi->begin();
    #else  // !defined(RF24_SPI_PTR)
    _SPI.begin();
    #endif // !defined(RF24_SPI_PTR)

#endif // !defined(XMEGA_D3) && !defined(RF24_LINUX)

    return _init_pins() && _init_radio();
}

/****************************************************************************/

bool RF24::_init_pins()
{
    if (!isValid()) {
        // didn't specify the CSN & CE pins to c'tor nor begin()
        return false;
    }

#if defined(RF24_LINUX)

    pinMode(ce_pin, OUTPUT);
    ce(LOW);
    delay(100);

#elif defined(LITTLEWIRE)
    pinMode(csn_pin, OUTPUT);
    csn(HIGH);

#elif defined(XMEGA_D3)
    if (ce_pin != csn_pin) {
        pinMode(ce_pin, OUTPUT);
    };
    ce(LOW);
    csn(HIGH);
    delay(200);

#else // using an Arduino platform

    // Initialize pins
    if (ce_pin != csn_pin) {
        pinMode(ce_pin, OUTPUT);
        pinMode(csn_pin, OUTPUT);
    }

    ce(LOW);
    csn(HIGH);

    #if defined(__ARDUINO_X86__)
    delay(100);
    #endif
#endif // !defined(XMEGA_D3) && !defined(LITTLEWIRE) && !defined(RF24_LINUX)

    return true; // assuming pins are connected properly
}

/****************************************************************************/

bool RF24::_init_radio()
{
    // Must allow the radio time to settle else configuration bits will not necessarily stick.
    // This is actually only required following power up but some settling time also appears to
    // be required after resets too. For full coverage, we'll always assume the worst.
    // Enabling 16b CRC is by far the most obvious case if the wrong timing is used - or skipped.
    // Technically we require 4.5ms + 14us as a worst case. We'll just call it 5ms for good measure.
    // WARNING: Delay is based on P-variant whereby non-P *may* require different timing.
    delay(5);

    // Set 1500uS (minimum for 32B payload in ESB@250KBPS) timeouts, to make testing a little easier
    // WARNING: If this is ever lowered, either 250KBS mode with AA is broken or maximum packet
    // sizes must never be used. See datasheet for a more complete explanation.
    setRetries(5, 15);

    // Then set the data rate to the slowest (and most reliable) speed supported by all hardware.
    setDataRate(RF24_1MBPS);

    // detect if is a plus variant & use old toggle features command accordingly
    uint8_t before_toggle = read_register(nRF24L01::FEATURE);
    toggle_features();
    uint8_t after_toggle = read_register(nRF24L01::FEATURE);
    _is_p_variant = before_toggle == after_toggle;
    if (after_toggle) {
        if (_is_p_variant) {
            // module did not experience power-on-reset (#401)
            toggle_features();
        }
        // allow use of multicast parameter and dynamic payloads by default
        write_register(nRF24L01::FEATURE, 0);
    }
    ack_payloads_enabled = false;       // ack payloads disabled by default
    write_register(nRF24L01::DYNPD, 0); // disable dynamic payloads by default (for all pipes)
    dynamic_payloads_enabled = false;
    write_register(nRF24L01::EN_AA, 0x3F);  // enable auto-ack on all pipes
    write_register(nRF24L01::EN_RXADDR, 3); // only open RX pipes 0 & 1
    setPayloadSize(32);                     // set static payload size to 32 (max) bytes by default
    setAddressWidth(5);                     // set default address length to (max) 5 bytes

    // Set up default configuration.  Callers can always change it later.
    // This channel should be universally safe and not bleed over into adjacent
    // spectrum.
    setChannel(76);

    // Reset current status
    // Notice reset and flush is the last thing we do
    write_register(nRF24L01::STATUS, RF24_IRQ_ALL);

    // Flush buffers
    flush_rx();
    flush_tx();

    // Clear CONFIG register:
    //      Reflect NO IRQ events on IRQ pin
    //      Enable PTX
    //      Power Up
    //      16-bit CRC (CRC required by auto-ack)
    // Do not write CE high so radio will remain in standby I mode
    // PTX should use only 22uA of power
    write_register(nRF24L01::CONFIG, (_BV(nRF24L01::EN_CRC) | _BV(nRF24L01::CRCO) | _BV(nRF24L01::MASK_RX_DR) | _BV(nRF24L01::MASK_TX_DS) | _BV(nRF24L01::MASK_MAX_RT)));
    config_reg = read_register(nRF24L01::CONFIG);

    powerUp();

    // if config is not set correctly then there was a bad response from module
    return config_reg == (_BV(nRF24L01::EN_CRC) | _BV(nRF24L01::CRCO) | _BV(nRF24L01::PWR_UP) | _BV(nRF24L01::MASK_RX_DR) | _BV(nRF24L01::MASK_TX_DS) | _BV(nRF24L01::MASK_MAX_RT)) ? true : false;
}

/****************************************************************************/

bool RF24::isChipConnected()
{
    return read_register(nRF24L01::SETUP_AW) == (addr_width - static_cast<uint8_t>(2));
}

/****************************************************************************/

bool RF24::isValid()
{
    return ce_pin != RF24_PIN_INVALID && csn_pin != RF24_PIN_INVALID;
}

/****************************************************************************/

void RF24::startListening(void)
{
#if !defined(RF24_TINY) && !defined(LITTLEWIRE)
    powerUp();
#endif
    config_reg |= _BV(nRF24L01::PRIM_RX);
    write_register(nRF24L01::CONFIG, config_reg);
    write_register(nRF24L01::STATUS, RF24_IRQ_ALL);
    ce(HIGH);

    // Restore the pipe0 address, if exists
    if (_is_p0_rx) {
        write_register(nRF24L01::RX_ADDR_P0, pipe0_reading_address, addr_width);
    }
    else {
        closeReadingPipe(0);
    }
}

/****************************************************************************/

static const PROGMEM uint8_t child_pipe_enable[] = {nRF24L01::ERX_P0, nRF24L01::ERX_P1, nRF24L01::ERX_P2,
                                                    nRF24L01::ERX_P3, nRF24L01::ERX_P4, nRF24L01::ERX_P5};

void RF24::stopListening(void)
{
    ce(LOW);

    //delayMicroseconds(100);
    delayMicroseconds(static_cast<int>(txDelay));
    if (ack_payloads_enabled) {
        flush_tx();
    }

    config_reg = static_cast<uint8_t>(config_reg & ~_BV(nRF24L01::PRIM_RX));
    write_register(nRF24L01::CONFIG, config_reg);

#if defined(RF24_TINY) || defined(LITTLEWIRE)
    // for 3 pins solution TX mode is only left with additional powerDown/powerUp cycle
    if (ce_pin == csn_pin) {
        powerDown();
        powerUp();
    }
#endif
    write_register(nRF24L01::RX_ADDR_P0, pipe0_writing_address, addr_width);
    write_register(nRF24L01::EN_RXADDR, static_cast<uint8_t>(read_register(nRF24L01::EN_RXADDR) | _BV(pgm_read_byte(&child_pipe_enable[0])))); // Enable RX on pipe0
}

/****************************************************************************/

void RF24::stopListening(const uint64_t txAddress)
{
    memcpy(pipe0_writing_address, &txAddress, addr_width);
    stopListening();
    write_register(nRF24L01::TX_ADDR, pipe0_writing_address, addr_width);
}

/****************************************************************************/

void RF24::stopListening(const uint8_t* txAddress)
{
    memcpy(pipe0_writing_address, txAddress, addr_width);
    stopListening();
    write_register(nRF24L01::TX_ADDR, pipe0_writing_address, addr_width);
}

/****************************************************************************/

void RF24::powerDown(void)
{
    ce(LOW); // Guarantee CE is low on powerDown
    config_reg = static_cast<uint8_t>(config_reg & ~_BV(nRF24L01::PWR_UP));
    write_register(nRF24L01::CONFIG, config_reg);
}

/****************************************************************************/

//Power up now. Radio will not power down unless instructed by MCU for config changes etc.
void RF24::powerUp(void)
{
    // if not powered up then power up and wait for the radio to initialize
    if (!(config_reg & _BV(nRF24L01::PWR_UP))) {
        config_reg |= _BV(nRF24L01::PWR_UP);
        write_register(nRF24L01::CONFIG, config_reg);

        // For nRF24L01+ to go from power down mode to TX or RX mode it must first pass through stand-by mode.
        // There must be a delay of Tpd2stby (see Table 16.) after the nRF24L01+ leaves power down mode before
        // the CEis set high. - Tpd2stby can be up to 5ms per the 1.0 datasheet
        delayMicroseconds(RF24_POWERUP_DELAY);
    }
}

/******************************************************************/
#if defined(FAILURE_HANDLING) || defined(RF24_LINUX)

void RF24::errNotify()
{
    #if defined(RF24_DEBUG) || defined(RF24_LINUX)
    printf_P(PSTR("RF24 HARDWARE FAIL: Radio not responding, verify pin connections, wiring, etc.\r\n"));
    #endif
    #if defined(FAILURE_HANDLING)
    failureDetected = 1;
    #else
    delay(5000);
    #endif
}

/******************************************************************/

int8_t RF24::errHandler(bool* doRecovery)
{

    //Wait until complete or failed
    uint32_t timer = millis();

    while (!(update() & (RF24_TX_DS | RF24_TX_DF))) {
        if (millis() - timer > 95) {
    #if defined(FAILURE_HANDLING)
            flush_rx();
            flush_tx();
            if (doRecovery) {
                *doRecovery = false;
                failureRecoveryAttempts++;
                ce(LOW);
                return -1;
            }
            else {
    #endif
                errNotify();
    #if defined(FAILURE_HANDLING)
            }
            return 0;
    #else
            delay(100);
    #endif
        }
    }
    return 0;
}

/******************************************************************/

void RF24::errHandler()
{

    #if defined(FAILURE_HANDLING)
    flush_tx();
    flush_rx();
    if (!failureFlushed) {
        failureFlushed = true;
        failureRecoveryAttempts++;
    }
    else {
    #endif
        errNotify();
    #if defined(FAILURE_HANDLING)
        failureFlushed = false;
    }
    ce(LOW);
    #endif
}

#endif

/******************************************************************/

//Similar to the previous write, clears the interrupt flags
bool RF24::write(const void* buf, uint8_t len, const bool multicast)
{

    //Start Writing
#if defined(FAILURE_HANDLING) || defined(RF24_LINUX)
    bool doRecovery = true;
    do {
#endif
        startFastWrite(buf, len, multicast);
#if defined(FAILURE_HANDLING) || defined(RF24_LINUX)
    } while (errHandler(&doRecovery) < 0);
#endif

    ce(LOW);

    write_register(nRF24L01::STATUS, RF24_IRQ_ALL);

    //Max retries exceeded
    if (status & RF24_TX_DF) {
        flush_tx(); // Only going to be 1 packet in the FIFO at a time using this method, so just flush
        return 0;
    }
    //TX OK 1 or 0
    return 1;
}

/****************************************************************************/

bool RF24::write(const void* buf, uint8_t len)
{
    return write(buf, len, 0);
}

/****************************************************************************/

//For general use, the interrupt flags are not important to clear
bool RF24::writeBlocking(const void* buf, uint8_t len, uint32_t timeout)
{
    //Block until the FIFO is NOT full.
    //Keep track of the MAX retries and set auto-retry if seeing failures
    //This way the FIFO will fill up and allow blocking until packets go through
    //The radio will auto-clear everything in the FIFO as long as CE remains high
#if defined(FAILURE_HANDLING)
    bool timeoutInvoked = false;
#endif

    uint32_t timer = millis(); // Get the time that the payload transmission started

    while (update() & _BV(nRF24L01::TX_FULL)) { // Blocking only if FIFO is full. This will loop and block until TX is successful or timeout

        if (status & RF24_TX_DF) { // If MAX Retries have been reached
            reUseTX();             // Set re-transmit and clear the MAX_RT interrupt flag
            if (millis() - timer > timeout) {
#if defined(FAILURE_HANDLING)
                failureFlushed = false;
#endif
                return 0; // If this payload has exceeded the user-defined timeout, exit and return 0
            }
        }
#if defined(FAILURE_HANDLING) || defined(RF24_LINUX)
        if (millis() - timer > (timeout + 95)) {
            errHandler();
    #if defined(FAILURE_HANDLING)
            timeoutInvoked = true;
            if (!failureFlushed) {
    #endif
                return 0;
    #if defined(FAILURE_HANDLING)
            }
    #endif
        }
#endif
    }

    //Start Writing
    startFastWrite(buf, len, 0); // Write the payload if a buffer is clear
#if defined(FAILURE_HANDLING)
    if (!timeoutInvoked) {
        failureFlushed = false;
    }
#endif
    return 1; // Return 1 to indicate successful transmission
}

/****************************************************************************/

void RF24::reUseTX()
{
    ce(LOW);
    write_register(nRF24L01::STATUS, RF24_TX_DF); //Clear max retry flag
    read_register(nRF24L01::REUSE_TX_PL, (uint8_t*)nullptr, 0);
    IF_RF24_DEBUG(printf_P("[Reusing payload in TX FIFO]"););
    ce(HIGH); //Re-Transfer packet
}

/****************************************************************************/

bool RF24::writeFast(const void* buf, uint8_t len, const bool multicast)
{
    //Block until the FIFO is NOT full.
    //Keep track of the MAX retries and set auto-retry if seeing failures
    //Return 0 so the user can control the retries and set a timer or failure counter if required
    //The radio will auto-clear everything in the FIFO as long as CE remains high

#if defined(FAILURE_HANDLING) || defined(RF24_LINUX)
    uint32_t timer = millis();
    bool timeoutInvoked = false;
#endif

    //Blocking only if FIFO is full. This will loop and block until TX is successful or fail
    while (update() & _BV(nRF24L01::TX_FULL)) {
        if (status & RF24_TX_DF) {
#if defined(FAILURE_HANDLING)
            failureFlushed = false;
#endif
            return 0; //Return 0. The previous payload has not been retransmitted
            // From the user perspective, if you get a 0, call txStandBy()
        }
#if defined(FAILURE_HANDLING) || defined(RF24_LINUX)
        if (millis() - timer > 95) {
            timeoutInvoked = true;
            errHandler();
    #if defined(FAILURE_HANDLING)
            if (!failureFlushed) {
    #endif
                return 0;
    #if defined(FAILURE_HANDLING)
            }
    #endif
        }
#endif
    }
    startFastWrite(buf, len, multicast); // Start Writing
#if defined(FAILURE_HANDLING)
    if (!timeoutInvoked) {
        failureFlushed = false;
    }
#endif
    return 1;
}

bool RF24::writeFast(const void* buf, uint8_t len)
{
    return writeFast(buf, len, 0);
}

/****************************************************************************/

//Per the documentation, we want to set PTX Mode when not listening. Then all we do is write data and set CE high
//In this mode, if we can keep the FIFO buffers loaded, packets will transmit immediately (no 130us delay)
//Otherwise we enter Standby-II mode, which is still faster than standby mode
//Also, we remove the need to keep writing the config register over and over and delaying for 150 us each time if sending a stream of data

void RF24::startFastWrite(const void* buf, uint8_t len, const bool multicast, bool startTx)
{ //TMRh20

    write_payload(buf, len, multicast ? nRF24L01::W_TX_PAYLOAD_NO_ACK : nRF24L01::W_TX_PAYLOAD);
    if (startTx) {
        ce(HIGH);
    }
}

/****************************************************************************/

//Added the original startWrite back in so users can still use interrupts, ack payloads, etc
//Allows the library to pass all tests
bool RF24::startWrite(const void* buf, uint8_t len, const bool multicast)
{

    // Send the payload
    write_payload(buf, len, multicast ? nRF24L01::W_TX_PAYLOAD_NO_ACK : nRF24L01::W_TX_PAYLOAD);
    ce(HIGH);
#if !defined(F_CPU) || F_CPU > 20000000
    delayMicroseconds(10);
#endif
#ifdef ARDUINO_ARCH_STM32
    if (F_CPU > 20000000) {
        delayMicroseconds(10);
    }
#endif
    ce(LOW);
    return !(status & _BV(nRF24L01::TX_FULL));
}

/****************************************************************************/

bool RF24::rxFifoFull()
{
    return read_register(nRF24L01::FIFO_STATUS) & _BV(nRF24L01::RX_FULL);
}

/****************************************************************************/

rf24_fifo_state_e RF24::isFifo(bool about_tx)
{
    uint8_t state = (read_register(nRF24L01::FIFO_STATUS) >> (4 * about_tx)) & 3;
    return static_cast<rf24_fifo_state_e>(state);
}

/****************************************************************************/

bool RF24::isFifo(bool about_tx, bool check_empty)
{
    return static_cast<bool>(static_cast<uint8_t>(isFifo(about_tx)) & _BV(!check_empty));
}

/****************************************************************************/

bool RF24::txStandBy()
{

#if defined(FAILURE_HANDLING) || defined(RF24_LINUX)
    uint32_t timeout = millis();
#endif
    while (!(read_register(nRF24L01::FIFO_STATUS) & _BV(nRF24L01::TX_EMPTY))) {
        if (status & RF24_TX_DF) {
            write_register(nRF24L01::STATUS, RF24_TX_DF);
            ce(LOW);
            flush_tx(); //Non blocking, flush the data
#if defined(FAILURE_HANDLING)
            failureFlushed = false;
#endif
            return 0;
        }
#if defined(FAILURE_HANDLING) || defined(RF24_LINUX)
        if (millis() - timeout > 95) {
            errHandler();
            return 0;
        }
#endif
    }

    ce(LOW); //Set STANDBY-I mode
#if defined(FAILURE_HANDLING)
    failureFlushed = false;
#endif
    return 1;
}

/****************************************************************************/

bool RF24::txStandBy(uint32_t timeout, bool startTx)
{

    if (startTx) {
        stopListening();
        ce(HIGH);
    }
    uint32_t start = millis();

    while (!(read_register(nRF24L01::FIFO_STATUS) & _BV(nRF24L01::TX_EMPTY))) {
        if (status & RF24_TX_DF) {
            write_register(nRF24L01::STATUS, RF24_TX_DF);
            ce(LOW); // Set re-transmit
            ce(HIGH);
            if (millis() - start >= timeout) {
                ce(LOW);
                flush_tx();
#if defined(FAILURE_HANDLING)
                failureFlushed = false;
#endif
                return 0;
            }
        }
#if defined(FAILURE_HANDLING) || defined(RF24_LINUX)
        if (millis() - start > timeout + 95) {
            errHandler();
            return 0;
        }
#endif
    }

    ce(LOW); //Set STANDBY-I mode
#if defined(FAILURE_HANDLING)
    failureFlushed = false;
#endif
    return 1;
}

/****************************************************************************/

void RF24::maskIRQ(bool tx, bool fail, bool rx)
{
    /* clear the interrupt flags */
    config_reg = static_cast<uint8_t>(config_reg & ~(1 << nRF24L01::MASK_MAX_RT | 1 << nRF24L01::MASK_TX_DS | 1 << nRF24L01::MASK_RX_DR));
    /* set the specified interrupt flags */
    config_reg = static_cast<uint8_t>(config_reg | fail << nRF24L01::MASK_MAX_RT | tx << nRF24L01::MASK_TX_DS | rx << nRF24L01::MASK_RX_DR);
    write_register(nRF24L01::CONFIG, config_reg);
}

/****************************************************************************/

uint8_t RF24::getDynamicPayloadSize(void)
{
    uint8_t result = read_register(nRF24L01::R_RX_PL_WID);

    if (result > 32 || !result) {
        flush_rx();
        return 0;
    }
    return result;
}

/****************************************************************************/

bool RF24::available(void)
{
    return (read_register(nRF24L01::FIFO_STATUS) & 1) == 0;
}

/****************************************************************************/

bool RF24::available(uint8_t* pipe_num)
{
    if (available()) { // if RX FIFO is not empty
        *pipe_num = (update() >> nRF24L01::RX_P_NO) & 0x07;
        return 1;
    }
    return 0;
}

/****************************************************************************/

void RF24::read(void* buf, uint8_t len)
{

    // Fetch the payload
    read_payload(buf, len);

    //Clear the only applicable interrupt flags
    write_register(nRF24L01::STATUS, RF24_RX_DR);
}

/****************************************************************************/

void RF24::whatHappened(bool& tx_ok, bool& tx_fail, bool& rx_ready)
{
    // Read the status & reset the status in one easy call
    // Or is that such a good idea?
    write_register(nRF24L01::STATUS, RF24_IRQ_ALL);

    // Report to the user what happened
    tx_ok = status & RF24_TX_DS;
    tx_fail = status & RF24_TX_DF;
    rx_ready = status & RF24_RX_DR;
}

/****************************************************************************/

uint8_t RF24::clearStatusFlags(uint8_t flags)
{
    write_register(nRF24L01::STATUS, flags & RF24_IRQ_ALL);
    return status;
}

/****************************************************************************/

void RF24::setStatusFlags(uint8_t flags)
{
    // flip the `flags` to translate from "human understanding"
    config_reg = (config_reg & ~RF24_IRQ_ALL) | (~flags & RF24_IRQ_ALL);
    write_register(nRF24L01::CONFIG, config_reg);
}

/****************************************************************************/

uint8_t RF24::getStatusFlags()
{
    return status;
}

/****************************************************************************/

uint8_t RF24::update()
{
    read_register(nRF24L01::NOP, (uint8_t*)nullptr, 0);
    return status;
}

/****************************************************************************/

void RF24::openWritingPipe(uint64_t value)
{
    // Note that AVR 8-bit uC's store this LSB first, and the NRF24L01(+)
    // expects it LSB first too, so we're good.

    write_register(nRF24L01::RX_ADDR_P0, reinterpret_cast<uint8_t*>(&value), addr_width);
    write_register(nRF24L01::TX_ADDR, reinterpret_cast<uint8_t*>(&value), addr_width);
    memcpy(pipe0_writing_address, &value, addr_width);
}

/****************************************************************************/

void RF24::openWritingPipe(const uint8_t* address)
{
    // Note that AVR 8-bit uC's store this LSB first, and the NRF24L01(+)
    // expects it LSB first too, so we're good.
    write_register(nRF24L01::RX_ADDR_P0, address, addr_width);
    write_register(nRF24L01::TX_ADDR, address, addr_width);
    memcpy(pipe0_writing_address, address, addr_width);
}

/****************************************************************************/

static const PROGMEM uint8_t child_pipe[] = {nRF24L01::RX_ADDR_P0, nRF24L01::RX_ADDR_P1, nRF24L01::RX_ADDR_P2,
                                             nRF24L01::RX_ADDR_P3, nRF24L01::RX_ADDR_P4, nRF24L01::RX_ADDR_P5};

void RF24::openReadingPipe(uint8_t child, uint64_t address)
{
    // If this is pipe 0, cache the address.  This is needed because
    // openWritingPipe() will overwrite the pipe 0 address, so
    // startListening() will have to restore it.
    if (child == 0) {
        memcpy(pipe0_reading_address, &address, addr_width);
        _is_p0_rx = true;
    }

    if (child <= 5) {
        // For pipes 2-5, only write the LSB
        if (child > 1) {
            write_register(pgm_read_byte(&child_pipe[child]), reinterpret_cast<const uint8_t*>(&address), 1);
        }
        // avoid overwriting the TX address on pipe 0 while still in TX mode.
        // NOTE, the cached RX address on pipe 0 is written when startListening() is called.
        else if (static_cast<bool>(config_reg & _BV(nRF24L01::PRIM_RX)) || child != 0) {
            write_register(pgm_read_byte(&child_pipe[child]), reinterpret_cast<const uint8_t*>(&address), addr_width);
        }

        // Note it would be more efficient to set all of the bits for all open
        // pipes at once.  However, I thought it would make the calling code
        // more simple to do it this way.
        write_register(nRF24L01::EN_RXADDR, static_cast<uint8_t>(read_register(nRF24L01::EN_RXADDR) | _BV(pgm_read_byte(&child_pipe_enable[child]))));
    }
}

/****************************************************************************/

void RF24::setAddressWidth(uint8_t a_width)
{
    a_width = static_cast<uint8_t>(a_width - 2);
    if (a_width) {
        write_register(nRF24L01::SETUP_AW, static_cast<uint8_t>(a_width % 4));
        addr_width = static_cast<uint8_t>((a_width % 4) + 2);
    }
    else {
        write_register(nRF24L01::SETUP_AW, static_cast<uint8_t>(0));
        addr_width = static_cast<uint8_t>(2);
    }
}

/****************************************************************************/

void RF24::openReadingPipe(uint8_t child, const uint8_t* address)
{
    // If this is pipe 0, cache the address.  This is needed because
    // openWritingPipe() will overwrite the pipe 0 address, so
    // startListening() will have to restore it.
    if (child == 0) {
        memcpy(pipe0_reading_address, address, addr_width);
        _is_p0_rx = true;
    }
    if (child <= 5) {
        // For pipes 2-5, only write the LSB
        if (child > 1) {
            write_register(pgm_read_byte(&child_pipe[child]), address, 1);
        }
        // avoid overwriting the TX address on pipe 0 while still in TX mode.
        // NOTE, the cached RX address on pipe 0 is written when startListening() is called.
        else if (static_cast<bool>(config_reg & _BV(nRF24L01::PRIM_RX)) || child != 0) {
            write_register(pgm_read_byte(&child_pipe[child]), address, addr_width);
        }

        // Note it would be more efficient to set all of the bits for all open
        // pipes at once.  However, I thought it would make the calling code
        // more simple to do it this way.
        write_register(nRF24L01::EN_RXADDR, static_cast<uint8_t>(read_register(nRF24L01::EN_RXADDR) | _BV(pgm_read_byte(&child_pipe_enable[child]))));
    }
}

/****************************************************************************/

void RF24::closeReadingPipe(uint8_t pipe)
{
    write_register(nRF24L01::EN_RXADDR, static_cast<uint8_t>(read_register(nRF24L01::EN_RXADDR) & ~_BV(pgm_read_byte(&child_pipe_enable[pipe]))));
    if (!pipe) {
        // keep track of pipe 0's RX state to avoid null vs 0 in addr cache
        _is_p0_rx = false;
    }
}

/****************************************************************************/

void RF24::toggle_features(void)
{
    beginTransaction();
#if defined(RF24_SPI_PTR)
    status = _spi->transfer(nRF24L01::ACTIVATE);
    _spi->transfer(0x73);
#else
    status = _SPI.transfer(nRF24L01::ACTIVATE);
    _SPI.transfer(0x73);
#endif
    endTransaction();
}

/****************************************************************************/

void RF24::enableDynamicPayloads(void)
{
    // Enable dynamic payload throughout the system

    //toggle_features();
    write_register(nRF24L01::FEATURE, read_register(nRF24L01::FEATURE) | _BV(nRF24L01::EN_DPL));

    IF_RF24_DEBUG(printf_P("FEATURE=%i\r\n", read_register(nRF24L01::FEATURE)));

    // Enable dynamic payload on all pipes
    //
    // Not sure the use case of only having dynamic payload on certain
    // pipes, so the library does not support it.
    write_register(nRF24L01::DYNPD, read_register(nRF24L01::DYNPD) | _BV(nRF24L01::DPL_P5) | _BV(nRF24L01::DPL_P4) | _BV(nRF24L01::DPL_P3) | _BV(nRF24L01::DPL_P2) | _BV(nRF24L01::DPL_P1) | _BV(nRF24L01::DPL_P0));

    dynamic_payloads_enabled = true;
}

/****************************************************************************/

void RF24::disableDynamicPayloads(void)
{
    // Disables dynamic payload throughout the system.  Also disables Ack Payloads

    //toggle_features();
    write_register(nRF24L01::FEATURE, 0);

    IF_RF24_DEBUG(printf_P("FEATURE=%i\r\n", read_register(nRF24L01::FEATURE)));

    // Disable dynamic payload on all pipes
    //
    // Not sure the use case of only having dynamic payload on certain
    // pipes, so the library does not support it.
    write_register(nRF24L01::DYNPD, 0);

    dynamic_payloads_enabled = false;
    ack_payloads_enabled = false;
}

/****************************************************************************/

void RF24::enableAckPayload(void)
{
    // enable ack payloads and dynamic payload features

    if (!ack_payloads_enabled) {
        write_register(nRF24L01::FEATURE, read_register(nRF24L01::FEATURE) | _BV(nRF24L01::EN_ACK_PAY) | _BV(nRF24L01::EN_DPL));

        IF_RF24_DEBUG(printf_P("FEATURE=%i\r\n", read_register(nRF24L01::FEATURE)));

        // Enable dynamic payload on pipes 0 & 1
        write_register(nRF24L01::DYNPD, read_register(nRF24L01::DYNPD) | _BV(nRF24L01::DPL_P1) | _BV(nRF24L01::DPL_P0));
        dynamic_payloads_enabled = true;
        ack_payloads_enabled = true;
    }
}

/****************************************************************************/

void RF24::disableAckPayload(void)
{
    // disable ack payloads (leave dynamic payload features as is)
    if (ack_payloads_enabled) {
        write_register(nRF24L01::FEATURE, static_cast<uint8_t>(read_register(nRF24L01::FEATURE) & ~_BV(nRF24L01::EN_ACK_PAY)));

        IF_RF24_DEBUG(printf_P("FEATURE=%i\r\n", read_register(nRF24L01::FEATURE)));

        ack_payloads_enabled = false;
    }
}

/****************************************************************************/

void RF24::enableDynamicAck(void)
{
    //
    // enable dynamic ack features
    //
    //toggle_features();
    write_register(nRF24L01::FEATURE, read_register(nRF24L01::FEATURE) | _BV(nRF24L01::EN_DYN_ACK));

    IF_RF24_DEBUG(printf_P("FEATURE=%i\r\n", read_register(nRF24L01::FEATURE)));
}

/****************************************************************************/

bool RF24::writeAckPayload(uint8_t pipe, const void* buf, uint8_t len)
{
    if (ack_payloads_enabled) {
        const uint8_t* current = reinterpret_cast<const uint8_t*>(buf);

        write_register(nRF24L01::W_ACK_PAYLOAD | (pipe & 0x07), current, rf24_min(len, static_cast<uint8_t>(32)));
        return !(status & _BV(nRF24L01::TX_FULL));
    }
    return 0;
}

/****************************************************************************/

bool RF24::isAckPayloadAvailable(void)
{
    return available();
}

/****************************************************************************/

bool RF24::isPVariant(void)
{
    return _is_p_variant;
}

/****************************************************************************/

void RF24::setAutoAck(bool enable)
{
    if (enable) {
        write_register(nRF24L01::EN_AA, 0x3F);
    }
    else {
        write_register(nRF24L01::EN_AA, 0);
        // accommodate ACK payloads feature
        if (ack_payloads_enabled) {
            disableAckPayload();
        }
    }
}

/****************************************************************************/

void RF24::setAutoAck(uint8_t pipe, bool enable)
{
    if (pipe < 6) {
        uint8_t en_aa = read_register(nRF24L01::EN_AA);
        if (enable) {
            en_aa |= static_cast<uint8_t>(_BV(pipe));
        }
        else {
            en_aa = static_cast<uint8_t>(en_aa & ~_BV(pipe));
            if (ack_payloads_enabled && !pipe) {
                disableAckPayload();
            }
        }
        write_register(nRF24L01::EN_AA, en_aa);
    }
}

/****************************************************************************/

bool RF24::testCarrier(void)
{
    return (read_register(nRF24L01::CD) & 1);
}

/****************************************************************************/

bool RF24::testRPD(void)
{
    return (read_register(nRF24L01::RPD) & 1);
}

/****************************************************************************/

void RF24::setPALevel(uint8_t level, bool lnaEnable)
{
    uint8_t setup = read_register(nRF24L01::RF_SETUP) & static_cast<uint8_t>(0xF8);
    setup |= _pa_level_reg_value(level, lnaEnable);
    write_register(nRF24L01::RF_SETUP, setup);
}

/****************************************************************************/

uint8_t RF24::getPALevel(void)
{
    return (read_register(nRF24L01::RF_SETUP) & (_BV(nRF24L01::RF_PWR_LOW) | _BV(nRF24L01::RF_PWR_HIGH))) >> 1;
}

/****************************************************************************/

uint8_t RF24::getARC(void)
{
    return read_register(nRF24L01::OBSERVE_TX) & 0x0F;
}

/****************************************************************************/

bool RF24::setDataRate(rf24_datarate_e speed)
{
    bool result = false;
    uint8_t setup = read_register(nRF24L01::RF_SETUP);

    // HIGH and LOW '00' is 1Mbs - our default
    setup = static_cast<uint8_t>(setup & ~(_BV(nRF24L01::RF_DR_LOW) | _BV(nRF24L01::RF_DR_HIGH)));
    setup |= _data_rate_reg_value(speed);

    write_register(nRF24L01::RF_SETUP, setup);

    // Verify our result
    if (read_register(nRF24L01::RF_SETUP) == setup) {
        result = true;
    }
    return result;
}

/****************************************************************************/

rf24_datarate_e RF24::getDataRate(void)
{
    rf24_datarate_e result;
    uint8_t dr = read_register(nRF24L01::RF_SETUP) & (_BV(nRF24L01::RF_DR_LOW) | _BV(nRF24L01::RF_DR_HIGH));

    // switch uses RAM (evil!)
    // Order matters in our case below
    if (dr == _BV(nRF24L01::RF_DR_LOW)) {
        // '10' = 250KBPS
        result = RF24_250KBPS;
    }
    else if (dr == _BV(nRF24L01::RF_DR_HIGH)) {
        // '01' = 2MBPS
        result = RF24_2MBPS;
    }
    else {
        // '00' = 1MBPS
        result = RF24_1MBPS;
    }
    return result;
}

/****************************************************************************/

void RF24::setCRCLength(rf24_crclength_e length)
{
    config_reg = static_cast<uint8_t>(config_reg & ~(_BV(nRF24L01::CRCO) | _BV(nRF24L01::EN_CRC)));

    // switch uses RAM (evil!)
    if (length == RF24_CRC_DISABLED) {
        // Do nothing, we turned it off above.
    }
    else if (length == RF24_CRC_8) {
        config_reg |= _BV(nRF24L01::EN_CRC);
    }
    else {
        config_reg |= _BV(nRF24L01::EN_CRC);
        config_reg |= _BV(nRF24L01::CRCO);
    }
    write_register(nRF24L01::CONFIG, config_reg);
}

/****************************************************************************/

rf24_crclength_e RF24::getCRCLength(void)
{
    rf24_crclength_e result = RF24_CRC_DISABLED;
    uint8_t AA = read_register(nRF24L01::EN_AA);
    config_reg = read_register(nRF24L01::CONFIG);

    if (config_reg & _BV(nRF24L01::EN_CRC) || AA) {
        if (config_reg & _BV(nRF24L01::CRCO)) {
            result = RF24_CRC_16;
        }
        else {
            result = RF24_CRC_8;
        }
    }

    return result;
}

/****************************************************************************/

void RF24::disableCRC(void)
{
    config_reg = static_cast<uint8_t>(config_reg & ~_BV(nRF24L01::EN_CRC));
    write_register(nRF24L01::CONFIG, config_reg);
}

/****************************************************************************/
void RF24::setRetries(uint8_t delay, uint8_t count)
{
    write_register(nRF24L01::SETUP_RETR, static_cast<uint8_t>(rf24_min(15, delay) << nRF24L01::ARD | rf24_min(15, count)));
}

/****************************************************************************/
void RF24::startConstCarrier(rf24_pa_dbm_e level, uint8_t channel)
{
    stopListening();
    write_register(nRF24L01::RF_SETUP, read_register(nRF24L01::RF_SETUP) | _BV(nRF24L01::CONT_WAVE) | _BV(nRF24L01::PLL_LOCK));
    if (isPVariant()) {
        setAutoAck(0);
        setRetries(0, 0);
        uint8_t dummy_buf[32];
        for (uint8_t i = 0; i < 32; ++i)
            dummy_buf[i] = 0xFF;

        // use write_register() instead of openWritingPipe() to bypass
        // truncation of the address with the current RF24::addr_width value
        write_register(nRF24L01::TX_ADDR, reinterpret_cast<uint8_t*>(&dummy_buf), 5);
        flush_tx(); // so we can write to top level

        // use write_register() instead of write_payload() to bypass
        // truncation of the payload with the current RF24::payload_size value
        write_register(nRF24L01::W_TX_PAYLOAD, reinterpret_cast<const uint8_t*>(&dummy_buf), 32);

        disableCRC();
    }
    setPALevel(level);
    setChannel(channel);
    IF_RF24_DEBUG(printf_P(PSTR("RF_SETUP=%02x\r\n"), read_register(nRF24L01::RF_SETUP)));
    ce(HIGH);
    if (isPVariant()) {
        delay(1);  // datasheet says 1 ms is ok in this instance
        reUseTX(); // CE gets toggled here
    }
}

/****************************************************************************/

void RF24::stopConstCarrier()
{
    /*
     * A note from the datasheet:
     * Do not use REUSE_TX_PL together with CONT_WAVE=1. When both these
     * registers are set the chip does not react when setting CE low. If
     * however, both registers are set PWR_UP = 0 will turn TX mode off.
     */
    powerDown(); // per datasheet recommendation (just to be safe)
    write_register(nRF24L01::RF_SETUP, static_cast<uint8_t>(read_register(nRF24L01::RF_SETUP) & ~_BV(nRF24L01::CONT_WAVE) & ~_BV(nRF24L01::PLL_LOCK)));
    ce(LOW);
    flush_tx();
    if (isPVariant()) {
        // restore the cached TX address
        write_register(nRF24L01::TX_ADDR, pipe0_writing_address, addr_width);
    }
}

/****************************************************************************/

void RF24::toggleAllPipes(bool isEnabled)
{
    write_register(nRF24L01::EN_RXADDR, static_cast<uint8_t>(isEnabled ? 0x3F : 0));
}

/****************************************************************************/

uint8_t RF24::_data_rate_reg_value(rf24_datarate_e speed)
{
#if !defined(F_CPU) || F_CPU > 20000000
    txDelay = 280;
#else //16Mhz Arduino
    txDelay = 85;
#endif
    if (speed == RF24_250KBPS) {
#if !defined(F_CPU) || F_CPU > 20000000
        txDelay = 505;
#else //16Mhz Arduino
        txDelay = 155;
#endif
        // Must set the RF_DR_LOW to 1; RF_DR_HIGH (used to be RF_DR) is already 0
        // Making it '10'.
        return static_cast<uint8_t>(_BV(nRF24L01::RF_DR_LOW));
    }
    else if (speed == RF24_2MBPS) {
#if !defined(F_CPU) || F_CPU > 20000000
        txDelay = 240;
#else // 16Mhz Arduino
        txDelay = 65;
#endif
        // Set 2Mbs, RF_DR (RF_DR_HIGH) is set 1
        // Making it '01'
        return static_cast<uint8_t>(_BV(nRF24L01::RF_DR_HIGH));
    }
    // HIGH and LOW '00' is 1Mbs - our default
    return static_cast<uint8_t>(0);
}

/****************************************************************************/

uint8_t RF24::_pa_level_reg_value(uint8_t level, bool lnaEnable)
{
    // If invalid level, go to max PA
    // Else set level as requested
    // + lnaEnable (1 or 0) to support the SI24R1 chip extra bit
    return static_cast<uint8_t>(((level > RF24_PA_MAX ? static_cast<uint8_t>(RF24_PA_MAX) : level) << 1) + lnaEnable);
}

/****************************************************************************/

void RF24::setRadiation(uint8_t level, rf24_datarate_e speed, bool lnaEnable)
{
    uint8_t setup = _data_rate_reg_value(speed);
    setup |= _pa_level_reg_value(level, lnaEnable);
    write_register(nRF24L01::RF_SETUP, setup);
}