Ein Roboter mit bürstenlosem Antrieb, differenzial und NRF24L01 Funk. Großflächig gebaut um ein großes Solarpanel aufzunehmen. https://gitlab.informatik.hs-fulda.de/fdai5253/roboter
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1632 lines
44 KiB

  1. /*
  2. Copyright (C) 2011 J. Coliz <maniacbug@ymail.com>
  3. This program is free software; you can redistribute it and/or
  4. modify it under the terms of the GNU General Public License
  5. version 2 as published by the Free Software Foundation.
  6. */
  7. #include "nRF24L01.h"
  8. #include "RF24_config.h"
  9. #include "RF24.h"
  10. /****************************************************************************/
  11. void RF24::csn(bool mode)
  12. {
  13. #if defined (RF24_TINY)
  14. if (ce_pin != csn_pin) {
  15. digitalWrite(csn_pin,mode);
  16. }
  17. else {
  18. if (mode == HIGH) {
  19. PORTB |= (1<<PINB2); // SCK->CSN HIGH
  20. delayMicroseconds(100); // allow csn to settle.
  21. }
  22. else {
  23. PORTB &= ~(1<<PINB2); // SCK->CSN LOW
  24. delayMicroseconds(11); // allow csn to settle
  25. }
  26. }
  27. // Return, CSN toggle complete
  28. return;
  29. #elif defined(ARDUINO) && !defined (RF24_SPI_TRANSACTIONS)
  30. // Minimum ideal SPI bus speed is 2x data rate
  31. // If we assume 2Mbs data rate and 16Mhz clock, a
  32. // divider of 4 is the minimum we want.
  33. // CLK:BUS 8Mhz:2Mhz, 16Mhz:4Mhz, or 20Mhz:5Mhz
  34. #if !defined (SOFTSPI)
  35. _SPI.setBitOrder(MSBFIRST);
  36. _SPI.setDataMode(SPI_MODE0);
  37. #if !defined(F_CPU) || F_CPU < 20000000
  38. _SPI.setClockDivider(SPI_CLOCK_DIV2);
  39. #elif F_CPU < 40000000
  40. _SPI.setClockDivider(SPI_CLOCK_DIV4);
  41. #elif F_CPU < 80000000
  42. _SPI.setClockDivider(SPI_CLOCK_DIV8);
  43. #elif F_CPU < 160000000
  44. _SPI.setClockDivider(SPI_CLOCK_DIV16);
  45. #elif F_CPU < 320000000
  46. _SPI.setClockDivider(SPI_CLOCK_DIV32);
  47. #elif F_CPU < 640000000
  48. _SPI.setClockDivider(SPI_CLOCK_DIV64);
  49. #elif F_CPU < 1280000000
  50. _SPI.setClockDivider(SPI_CLOCK_DIV128);
  51. #else
  52. #error "Unsupported CPU frequency. Please set correct SPI divider."
  53. #endif
  54. #endif
  55. #elif defined (RF24_RPi)
  56. if(!mode)
  57. _SPI.chipSelect(csn_pin);
  58. #endif
  59. #if !defined (RF24_LINUX)
  60. digitalWrite(csn_pin,mode);
  61. delayMicroseconds(csDelay);
  62. #endif
  63. }
  64. /****************************************************************************/
  65. void RF24::ce(bool level)
  66. {
  67. //Allow for 3-pin use on ATTiny
  68. if (ce_pin != csn_pin) digitalWrite(ce_pin,level);
  69. }
  70. /****************************************************************************/
  71. inline void RF24::beginTransaction() {
  72. #if defined (RF24_SPI_TRANSACTIONS)
  73. _SPI.beginTransaction(SPISettings(RF24_SPI_SPEED, MSBFIRST, SPI_MODE0));
  74. #endif
  75. csn(LOW);
  76. }
  77. /****************************************************************************/
  78. inline void RF24::endTransaction() {
  79. csn(HIGH);
  80. #if defined (RF24_SPI_TRANSACTIONS)
  81. _SPI.endTransaction();
  82. #endif
  83. }
  84. /****************************************************************************/
  85. uint8_t RF24::read_register(uint8_t reg, uint8_t* buf, uint8_t len)
  86. {
  87. uint8_t status;
  88. #if defined (RF24_LINUX)
  89. beginTransaction(); //configures the spi settings for RPi, locks mutex and setting csn low
  90. uint8_t * prx = spi_rxbuff;
  91. uint8_t * ptx = spi_txbuff;
  92. uint8_t size = len + 1; // Add register value to transmit buffer
  93. *ptx++ = ( R_REGISTER | ( REGISTER_MASK & reg ) );
  94. while (len--){ *ptx++ = RF24_NOP; } // Dummy operation, just for reading
  95. _SPI.transfernb( (char *) spi_txbuff, (char *) spi_rxbuff, size);
  96. status = *prx++; // status is 1st byte of receive buffer
  97. // decrement before to skip status byte
  98. while ( --size ){ *buf++ = *prx++; }
  99. endTransaction(); //unlocks mutex and setting csn high
  100. #else
  101. beginTransaction();
  102. status = _SPI.transfer( R_REGISTER | ( REGISTER_MASK & reg ) );
  103. while ( len-- ){
  104. *buf++ = _SPI.transfer(0xff);
  105. }
  106. endTransaction();
  107. #endif
  108. return status;
  109. }
  110. /****************************************************************************/
  111. uint8_t RF24::read_register(uint8_t reg)
  112. {
  113. uint8_t result;
  114. #if defined (RF24_LINUX)
  115. beginTransaction();
  116. uint8_t * prx = spi_rxbuff;
  117. uint8_t * ptx = spi_txbuff;
  118. *ptx++ = ( R_REGISTER | ( REGISTER_MASK & reg ) );
  119. *ptx++ = RF24_NOP ; // Dummy operation, just for reading
  120. _SPI.transfernb( (char *) spi_txbuff, (char *) spi_rxbuff, 2);
  121. result = *++prx; // result is 2nd byte of receive buffer
  122. endTransaction();
  123. #else
  124. beginTransaction();
  125. _SPI.transfer( R_REGISTER | ( REGISTER_MASK & reg ) );
  126. result = _SPI.transfer(0xff);
  127. endTransaction();
  128. #endif
  129. return result;
  130. }
  131. /****************************************************************************/
  132. uint8_t RF24::write_register(uint8_t reg, const uint8_t* buf, uint8_t len)
  133. {
  134. uint8_t status;
  135. #if defined (RF24_LINUX)
  136. beginTransaction();
  137. uint8_t * prx = spi_rxbuff;
  138. uint8_t * ptx = spi_txbuff;
  139. uint8_t size = len + 1; // Add register value to transmit buffer
  140. *ptx++ = ( W_REGISTER | ( REGISTER_MASK & reg ) );
  141. while ( len-- )
  142. *ptx++ = *buf++;
  143. _SPI.transfernb( (char *) spi_txbuff, (char *) spi_rxbuff, size);
  144. status = *prx; // status is 1st byte of receive buffer
  145. endTransaction();
  146. #else
  147. beginTransaction();
  148. status = _SPI.transfer( W_REGISTER | ( REGISTER_MASK & reg ) );
  149. while ( len-- )
  150. _SPI.transfer(*buf++);
  151. endTransaction();
  152. #endif
  153. return status;
  154. }
  155. /****************************************************************************/
  156. uint8_t RF24::write_register(uint8_t reg, uint8_t value)
  157. {
  158. uint8_t status;
  159. IF_SERIAL_DEBUG(printf_P(PSTR("write_register(%02x,%02x)\r\n"),reg,value));
  160. #if defined (RF24_LINUX)
  161. beginTransaction();
  162. uint8_t * prx = spi_rxbuff;
  163. uint8_t * ptx = spi_txbuff;
  164. *ptx++ = ( W_REGISTER | ( REGISTER_MASK & reg ) );
  165. *ptx = value ;
  166. _SPI.transfernb( (char *) spi_txbuff, (char *) spi_rxbuff, 2);
  167. status = *prx++; // status is 1st byte of receive buffer
  168. endTransaction();
  169. #else
  170. beginTransaction();
  171. status = _SPI.transfer( W_REGISTER | ( REGISTER_MASK & reg ) );
  172. _SPI.transfer(value);
  173. endTransaction();
  174. #endif
  175. return status;
  176. }
  177. /****************************************************************************/
  178. uint8_t RF24::write_payload(const void* buf, uint8_t data_len, const uint8_t writeType)
  179. {
  180. uint8_t status;
  181. const uint8_t* current = reinterpret_cast<const uint8_t*>(buf);
  182. data_len = rf24_min(data_len, payload_size);
  183. uint8_t blank_len = dynamic_payloads_enabled ? 0 : payload_size - data_len;
  184. //printf("[Writing %u bytes %u blanks]",data_len,blank_len);
  185. IF_SERIAL_DEBUG( printf("[Writing %u bytes %u blanks]\n",data_len,blank_len); );
  186. #if defined (RF24_LINUX)
  187. beginTransaction();
  188. uint8_t * prx = spi_rxbuff;
  189. uint8_t * ptx = spi_txbuff;
  190. uint8_t size;
  191. size = data_len + blank_len + 1 ; // Add register value to transmit buffer
  192. *ptx++ = writeType;
  193. while ( data_len-- )
  194. *ptx++ = *current++;
  195. while ( blank_len-- )
  196. *ptx++ = 0;
  197. _SPI.transfernb( (char *) spi_txbuff, (char *) spi_rxbuff, size);
  198. status = *prx; // status is 1st byte of receive buffer
  199. endTransaction();
  200. #else
  201. beginTransaction();
  202. status = _SPI.transfer( writeType );
  203. while ( data_len-- ) {
  204. _SPI.transfer(*current++);
  205. }
  206. while ( blank_len-- ) {
  207. _SPI.transfer(0);
  208. }
  209. endTransaction();
  210. #endif
  211. return status;
  212. }
  213. /****************************************************************************/
  214. uint8_t RF24::read_payload(void* buf, uint8_t data_len)
  215. {
  216. uint8_t status;
  217. uint8_t* current = reinterpret_cast<uint8_t*>(buf);
  218. if(data_len > payload_size) data_len = payload_size;
  219. uint8_t blank_len = dynamic_payloads_enabled ? 0 : payload_size - data_len;
  220. //printf("[Reading %u bytes %u blanks]",data_len,blank_len);
  221. IF_SERIAL_DEBUG( printf("[Reading %u bytes %u blanks]\n",data_len,blank_len); );
  222. #if defined (RF24_LINUX)
  223. beginTransaction();
  224. uint8_t * prx = spi_rxbuff;
  225. uint8_t * ptx = spi_txbuff;
  226. uint8_t size;
  227. size = data_len + blank_len + 1; // Add register value to transmit buffer
  228. *ptx++ = R_RX_PAYLOAD;
  229. while(--size)
  230. *ptx++ = RF24_NOP;
  231. size = data_len + blank_len + 1; // Size has been lost during while, re affect
  232. _SPI.transfernb( (char *) spi_txbuff, (char *) spi_rxbuff, size);
  233. status = *prx++; // 1st byte is status
  234. if (data_len > 0) {
  235. while ( --data_len ) // Decrement before to skip 1st status byte
  236. *current++ = *prx++;
  237. *current = *prx;
  238. }
  239. endTransaction();
  240. #else
  241. beginTransaction();
  242. status = _SPI.transfer( R_RX_PAYLOAD );
  243. while ( data_len-- ) {
  244. *current++ = _SPI.transfer(0xFF);
  245. }
  246. while ( blank_len-- ) {
  247. _SPI.transfer(0xff);
  248. }
  249. endTransaction();
  250. #endif
  251. return status;
  252. }
  253. /****************************************************************************/
  254. uint8_t RF24::flush_rx(void)
  255. {
  256. return spiTrans( FLUSH_RX );
  257. }
  258. /****************************************************************************/
  259. uint8_t RF24::flush_tx(void)
  260. {
  261. return spiTrans( FLUSH_TX );
  262. }
  263. /****************************************************************************/
  264. uint8_t RF24::spiTrans(uint8_t cmd){
  265. uint8_t status;
  266. beginTransaction();
  267. status = _SPI.transfer( cmd );
  268. endTransaction();
  269. return status;
  270. }
  271. /****************************************************************************/
  272. uint8_t RF24::get_status(void)
  273. {
  274. return spiTrans(RF24_NOP);
  275. }
  276. /****************************************************************************/
  277. #if !defined (MINIMAL)
  278. void RF24::print_status(uint8_t status)
  279. {
  280. printf_P(PSTR("STATUS\t\t = 0x%02x RX_DR=%x TX_DS=%x MAX_RT=%x RX_P_NO=%x TX_FULL=%x\r\n"),
  281. status,
  282. (status & _BV(RX_DR))?1:0,
  283. (status & _BV(TX_DS))?1:0,
  284. (status & _BV(MAX_RT))?1:0,
  285. ((status >> RX_P_NO) & 0x07),
  286. (status & _BV(TX_FULL))?1:0
  287. );
  288. }
  289. /****************************************************************************/
  290. void RF24::print_observe_tx(uint8_t value)
  291. {
  292. printf_P(PSTR("OBSERVE_TX=%02x: POLS_CNT=%x ARC_CNT=%x\r\n"),
  293. value,
  294. (value >> PLOS_CNT) & 0x0F,
  295. (value >> ARC_CNT) & 0x0F
  296. );
  297. }
  298. /****************************************************************************/
  299. void RF24::print_byte_register(const char* name, uint8_t reg, uint8_t qty)
  300. {
  301. //char extra_tab = strlen_P(name) < 8 ? '\t' : 0;
  302. //printf_P(PSTR(PRIPSTR"\t%c ="),name,extra_tab);
  303. #if defined (RF24_LINUX)
  304. printf("%s\t =", name);
  305. #else
  306. printf_P(PSTR(PRIPSTR"\t ="),name);
  307. #endif
  308. while (qty--)
  309. printf_P(PSTR(" 0x%02x"),read_register(reg++));
  310. printf_P(PSTR("\r\n"));
  311. }
  312. /****************************************************************************/
  313. void RF24::print_address_register(const char* name, uint8_t reg, uint8_t qty)
  314. {
  315. #if defined (RF24_LINUX)
  316. printf("%s\t =",name);
  317. #else
  318. printf_P(PSTR(PRIPSTR"\t ="),name);
  319. #endif
  320. while (qty--)
  321. {
  322. uint8_t buffer[addr_width];
  323. read_register(reg++,buffer,sizeof buffer);
  324. printf_P(PSTR(" 0x"));
  325. uint8_t* bufptr = buffer + sizeof buffer;
  326. while( --bufptr >= buffer )
  327. printf_P(PSTR("%02x"),*bufptr);
  328. }
  329. printf_P(PSTR("\r\n"));
  330. }
  331. #endif
  332. /****************************************************************************/
  333. RF24::RF24(uint16_t _cepin, uint16_t _cspin):
  334. ce_pin(_cepin), csn_pin(_cspin), p_variant(false),
  335. payload_size(32), dynamic_payloads_enabled(false), addr_width(5),csDelay(5)//,pipe0_reading_address(0)
  336. {
  337. pipe0_reading_address[0]=0;
  338. }
  339. /****************************************************************************/
  340. #if defined (RF24_LINUX) && !defined (MRAA)//RPi constructor
  341. RF24::RF24(uint16_t _cepin, uint16_t _cspin, uint32_t _spi_speed):
  342. ce_pin(_cepin),csn_pin(_cspin),spi_speed(_spi_speed),p_variant(false), payload_size(32), dynamic_payloads_enabled(false),addr_width(5)//,pipe0_reading_address(0)
  343. {
  344. pipe0_reading_address[0]=0;
  345. }
  346. #endif
  347. /****************************************************************************/
  348. void RF24::setChannel(uint8_t channel)
  349. {
  350. const uint8_t max_channel = 125;
  351. write_register(RF_CH,rf24_min(channel,max_channel));
  352. }
  353. uint8_t RF24::getChannel()
  354. {
  355. return read_register(RF_CH);
  356. }
  357. /****************************************************************************/
  358. void RF24::setPayloadSize(uint8_t size)
  359. {
  360. payload_size = rf24_min(size,32);
  361. }
  362. /****************************************************************************/
  363. uint8_t RF24::getPayloadSize(void)
  364. {
  365. return payload_size;
  366. }
  367. /****************************************************************************/
  368. #if !defined (MINIMAL)
  369. static const char rf24_datarate_e_str_0[] PROGMEM = "1MBPS";
  370. static const char rf24_datarate_e_str_1[] PROGMEM = "2MBPS";
  371. static const char rf24_datarate_e_str_2[] PROGMEM = "250KBPS";
  372. static const char * const rf24_datarate_e_str_P[] PROGMEM = {
  373. rf24_datarate_e_str_0,
  374. rf24_datarate_e_str_1,
  375. rf24_datarate_e_str_2,
  376. };
  377. static const char rf24_model_e_str_0[] PROGMEM = "nRF24L01";
  378. static const char rf24_model_e_str_1[] PROGMEM = "nRF24L01+";
  379. static const char * const rf24_model_e_str_P[] PROGMEM = {
  380. rf24_model_e_str_0,
  381. rf24_model_e_str_1,
  382. };
  383. static const char rf24_crclength_e_str_0[] PROGMEM = "Disabled";
  384. static const char rf24_crclength_e_str_1[] PROGMEM = "8 bits";
  385. static const char rf24_crclength_e_str_2[] PROGMEM = "16 bits" ;
  386. static const char * const rf24_crclength_e_str_P[] PROGMEM = {
  387. rf24_crclength_e_str_0,
  388. rf24_crclength_e_str_1,
  389. rf24_crclength_e_str_2,
  390. };
  391. static const char rf24_pa_dbm_e_str_0[] PROGMEM = "PA_MIN";
  392. static const char rf24_pa_dbm_e_str_1[] PROGMEM = "PA_LOW";
  393. static const char rf24_pa_dbm_e_str_2[] PROGMEM = "PA_HIGH";
  394. static const char rf24_pa_dbm_e_str_3[] PROGMEM = "PA_MAX";
  395. static const char * const rf24_pa_dbm_e_str_P[] PROGMEM = {
  396. rf24_pa_dbm_e_str_0,
  397. rf24_pa_dbm_e_str_1,
  398. rf24_pa_dbm_e_str_2,
  399. rf24_pa_dbm_e_str_3,
  400. };
  401. #if defined (RF24_LINUX)
  402. static const char rf24_csn_e_str_0[] = "CE0 (PI Hardware Driven)";
  403. static const char rf24_csn_e_str_1[] = "CE1 (PI Hardware Driven)";
  404. static const char rf24_csn_e_str_2[] = "CE2 (PI Hardware Driven)";
  405. static const char rf24_csn_e_str_3[] = "Custom GPIO Software Driven";
  406. static const char * const rf24_csn_e_str_P[] = {
  407. rf24_csn_e_str_0,
  408. rf24_csn_e_str_1,
  409. rf24_csn_e_str_2,
  410. rf24_csn_e_str_3,
  411. };
  412. #endif
  413. void RF24::printDetails(void)
  414. {
  415. #if defined (RF24_RPi)
  416. printf("================ SPI Configuration ================\n" );
  417. if (csn_pin < BCM2835_SPI_CS_NONE ){
  418. printf("CSN Pin \t = %s\n",rf24_csn_e_str_P[csn_pin]);
  419. }else{
  420. printf("CSN Pin \t = Custom GPIO%d%s\n", csn_pin,
  421. csn_pin==RPI_V2_GPIO_P1_26 ? " (CE1) Software Driven" : "" );
  422. }
  423. printf("CE Pin \t = Custom GPIO%d\n", ce_pin );
  424. printf("Clock Speed\t = " );
  425. switch (spi_speed)
  426. {
  427. case BCM2835_SPI_SPEED_64MHZ : printf("64 Mhz"); break ;
  428. case BCM2835_SPI_SPEED_32MHZ : printf("32 Mhz"); break ;
  429. case BCM2835_SPI_SPEED_16MHZ : printf("16 Mhz"); break ;
  430. case BCM2835_SPI_SPEED_8MHZ : printf("8 Mhz"); break ;
  431. case BCM2835_SPI_SPEED_4MHZ : printf("4 Mhz"); break ;
  432. case BCM2835_SPI_SPEED_2MHZ : printf("2 Mhz"); break ;
  433. case BCM2835_SPI_SPEED_1MHZ : printf("1 Mhz"); break ;
  434. case BCM2835_SPI_SPEED_512KHZ: printf("512 KHz"); break ;
  435. case BCM2835_SPI_SPEED_256KHZ: printf("256 KHz"); break ;
  436. case BCM2835_SPI_SPEED_128KHZ: printf("128 KHz"); break ;
  437. case BCM2835_SPI_SPEED_64KHZ : printf("64 KHz"); break ;
  438. case BCM2835_SPI_SPEED_32KHZ : printf("32 KHz"); break ;
  439. case BCM2835_SPI_SPEED_16KHZ : printf("16 KHz"); break ;
  440. case BCM2835_SPI_SPEED_8KHZ : printf("8 KHz"); break ;
  441. default : printf("8 Mhz"); break ;
  442. }
  443. printf("\n================ NRF Configuration ================\n");
  444. #endif //Linux
  445. print_status(get_status());
  446. print_address_register(PSTR("RX_ADDR_P0-1"),RX_ADDR_P0,2);
  447. print_byte_register(PSTR("RX_ADDR_P2-5"),RX_ADDR_P2,4);
  448. print_address_register(PSTR("TX_ADDR\t"),TX_ADDR);
  449. print_byte_register(PSTR("RX_PW_P0-6"),RX_PW_P0,6);
  450. print_byte_register(PSTR("EN_AA\t"),EN_AA);
  451. print_byte_register(PSTR("EN_RXADDR"),EN_RXADDR);
  452. print_byte_register(PSTR("RF_CH\t"),RF_CH);
  453. print_byte_register(PSTR("RF_SETUP"),RF_SETUP);
  454. print_byte_register(PSTR("CONFIG\t"),NRF_CONFIG);
  455. print_byte_register(PSTR("DYNPD/FEATURE"),DYNPD,2);
  456. printf_P(PSTR("Data Rate\t = " PRIPSTR "\r\n"),pgm_read_ptr(&rf24_datarate_e_str_P[getDataRate()]));
  457. printf_P(PSTR("Model\t\t = " PRIPSTR "\r\n"),pgm_read_ptr(&rf24_model_e_str_P[isPVariant()]));
  458. printf_P(PSTR("CRC Length\t = " PRIPSTR "\r\n"),pgm_read_ptr(&rf24_crclength_e_str_P[getCRCLength()]));
  459. printf_P(PSTR("PA Power\t = " PRIPSTR "\r\n"), pgm_read_ptr(&rf24_pa_dbm_e_str_P[getPALevel()]));
  460. }
  461. #endif
  462. /****************************************************************************/
  463. bool RF24::begin(void)
  464. {
  465. uint8_t setup=0;
  466. #if defined (RF24_LINUX)
  467. #if defined (MRAA)
  468. GPIO();
  469. gpio.begin(ce_pin,csn_pin);
  470. #endif
  471. #ifdef RF24_RPi
  472. switch(csn_pin){ //Ensure valid hardware CS pin
  473. case 0: break;
  474. case 1: break;
  475. // Allow BCM2835 enums for RPi
  476. case 8: csn_pin = 0; break;
  477. case 7: csn_pin = 1; break;
  478. default: csn_pin = 0; break;
  479. }
  480. #endif
  481. _SPI.begin(csn_pin);
  482. pinMode(ce_pin,OUTPUT);
  483. ce(LOW);
  484. delay(100);
  485. #elif defined(LITTLEWIRE)
  486. pinMode(csn_pin,OUTPUT);
  487. _SPI.begin();
  488. csn(HIGH);
  489. #elif defined(XMEGA_D3)
  490. if (ce_pin != csn_pin) pinMode(ce_pin,OUTPUT);
  491. _SPI.begin(csn_pin);
  492. ce(LOW);
  493. csn(HIGH);
  494. delay(200);
  495. #else
  496. // Initialize pins
  497. if (ce_pin != csn_pin) pinMode(ce_pin,OUTPUT);
  498. #if ! defined(LITTLEWIRE)
  499. if (ce_pin != csn_pin)
  500. #endif
  501. pinMode(csn_pin,OUTPUT);
  502. _SPI.begin();
  503. ce(LOW);
  504. csn(HIGH);
  505. #if defined (__ARDUINO_X86__)
  506. delay(100);
  507. #endif
  508. #endif //Linux
  509. // Must allow the radio time to settle else configuration bits will not necessarily stick.
  510. // This is actually only required following power up but some settling time also appears to
  511. // be required after resets too. For full coverage, we'll always assume the worst.
  512. // Enabling 16b CRC is by far the most obvious case if the wrong timing is used - or skipped.
  513. // Technically we require 4.5ms + 14us as a worst case. We'll just call it 5ms for good measure.
  514. // WARNING: Delay is based on P-variant whereby non-P *may* require different timing.
  515. delay( 5 ) ;
  516. // Reset NRF_CONFIG and enable 16-bit CRC.
  517. write_register( NRF_CONFIG, 0x0C ) ;
  518. // Set 1500uS (minimum for 32B payload in ESB@250KBPS) timeouts, to make testing a little easier
  519. // WARNING: If this is ever lowered, either 250KBS mode with AA is broken or maximum packet
  520. // sizes must never be used. See documentation for a more complete explanation.
  521. setRetries(5,15);
  522. // Reset value is MAX
  523. //setPALevel( RF24_PA_MAX ) ;
  524. // check for connected module and if this is a p nRF24l01 variant
  525. //
  526. if( setDataRate( RF24_250KBPS ) )
  527. {
  528. p_variant = true ;
  529. }
  530. setup = read_register(RF_SETUP);
  531. /*if( setup == 0b00001110 ) // register default for nRF24L01P
  532. {
  533. p_variant = true ;
  534. }*/
  535. // Then set the data rate to the slowest (and most reliable) speed supported by all
  536. // hardware.
  537. setDataRate( RF24_1MBPS ) ;
  538. // Initialize CRC and request 2-byte (16bit) CRC
  539. //setCRCLength( RF24_CRC_16 ) ;
  540. // Disable dynamic payloads, to match dynamic_payloads_enabled setting - Reset value is 0
  541. toggle_features();
  542. write_register(FEATURE,0 );
  543. write_register(DYNPD,0);
  544. dynamic_payloads_enabled = false;
  545. // Reset current status
  546. // Notice reset and flush is the last thing we do
  547. write_register(NRF_STATUS,_BV(RX_DR) | _BV(TX_DS) | _BV(MAX_RT) );
  548. // Set up default configuration. Callers can always change it later.
  549. // This channel should be universally safe and not bleed over into adjacent
  550. // spectrum.
  551. setChannel(76);
  552. // Flush buffers
  553. flush_rx();
  554. flush_tx();
  555. powerUp(); //Power up by default when begin() is called
  556. // Enable PTX, do not write CE high so radio will remain in standby I mode ( 130us max to transition to RX or TX instead of 1500us from powerUp )
  557. // PTX should use only 22uA of power
  558. write_register(NRF_CONFIG, ( read_register(NRF_CONFIG) ) & ~_BV(PRIM_RX) );
  559. // if setup is 0 or ff then there was no response from module
  560. return ( setup != 0 && setup != 0xff );
  561. }
  562. /****************************************************************************/
  563. bool RF24::isChipConnected()
  564. {
  565. uint8_t setup = read_register(SETUP_AW);
  566. if(setup >= 1 && setup <= 3)
  567. {
  568. return true;
  569. }
  570. return false;
  571. }
  572. /****************************************************************************/
  573. void RF24::startListening(void)
  574. {
  575. #if !defined (RF24_TINY) && ! defined(LITTLEWIRE)
  576. powerUp();
  577. #endif
  578. write_register(NRF_CONFIG, read_register(NRF_CONFIG) | _BV(PRIM_RX));
  579. write_register(NRF_STATUS, _BV(RX_DR) | _BV(TX_DS) | _BV(MAX_RT) );
  580. ce(HIGH);
  581. // Restore the pipe0 adddress, if exists
  582. if (pipe0_reading_address[0] > 0){
  583. write_register(RX_ADDR_P0, pipe0_reading_address, addr_width);
  584. }else{
  585. closeReadingPipe(0);
  586. }
  587. // Flush buffers
  588. //flush_rx();
  589. if(read_register(FEATURE) & _BV(EN_ACK_PAY)){
  590. flush_tx();
  591. }
  592. // Go!
  593. //delayMicroseconds(100);
  594. }
  595. /****************************************************************************/
  596. static const uint8_t child_pipe_enable[] PROGMEM =
  597. {
  598. ERX_P0, ERX_P1, ERX_P2, ERX_P3, ERX_P4, ERX_P5
  599. };
  600. void RF24::stopListening(void)
  601. {
  602. ce(LOW);
  603. delayMicroseconds(txDelay);
  604. if(read_register(FEATURE) & _BV(EN_ACK_PAY)){
  605. delayMicroseconds(txDelay); //200
  606. flush_tx();
  607. }
  608. //flush_rx();
  609. write_register(NRF_CONFIG, ( read_register(NRF_CONFIG) ) & ~_BV(PRIM_RX) );
  610. #if defined (RF24_TINY) || defined (LITTLEWIRE)
  611. // for 3 pins solution TX mode is only left with additonal powerDown/powerUp cycle
  612. if (ce_pin == csn_pin) {
  613. powerDown();
  614. powerUp();
  615. }
  616. #endif
  617. write_register(EN_RXADDR,read_register(EN_RXADDR) | _BV(pgm_read_byte(&child_pipe_enable[0]))); // Enable RX on pipe0
  618. //delayMicroseconds(100);
  619. }
  620. /****************************************************************************/
  621. void RF24::powerDown(void)
  622. {
  623. ce(LOW); // Guarantee CE is low on powerDown
  624. write_register(NRF_CONFIG,read_register(NRF_CONFIG) & ~_BV(PWR_UP));
  625. }
  626. /****************************************************************************/
  627. //Power up now. Radio will not power down unless instructed by MCU for config changes etc.
  628. void RF24::powerUp(void)
  629. {
  630. uint8_t cfg = read_register(NRF_CONFIG);
  631. // if not powered up then power up and wait for the radio to initialize
  632. if (!(cfg & _BV(PWR_UP))){
  633. write_register(NRF_CONFIG, cfg | _BV(PWR_UP));
  634. // For nRF24L01+ to go from power down mode to TX or RX mode it must first pass through stand-by mode.
  635. // There must be a delay of Tpd2stby (see Table 16.) after the nRF24L01+ leaves power down mode before
  636. // the CEis set high. - Tpd2stby can be up to 5ms per the 1.0 datasheet
  637. delay(5);
  638. }
  639. }
  640. /******************************************************************/
  641. #if defined (FAILURE_HANDLING) || defined (RF24_LINUX)
  642. void RF24::errNotify(){
  643. #if defined (SERIAL_DEBUG) || defined (RF24_LINUX)
  644. printf_P(PSTR("RF24 HARDWARE FAIL: Radio not responding, verify pin connections, wiring, etc.\r\n"));
  645. #endif
  646. #if defined (FAILURE_HANDLING)
  647. failureDetected = 1;
  648. #else
  649. delay(5000);
  650. #endif
  651. }
  652. #endif
  653. /******************************************************************/
  654. //Similar to the previous write, clears the interrupt flags
  655. bool RF24::write( const void* buf, uint8_t len, const bool multicast )
  656. {
  657. //Start Writing
  658. startFastWrite(buf,len,multicast);
  659. //Wait until complete or failed
  660. #if defined (FAILURE_HANDLING) || defined (RF24_LINUX)
  661. uint32_t timer = millis();
  662. #endif
  663. while( ! ( get_status() & ( _BV(TX_DS) | _BV(MAX_RT) ))) {
  664. #if defined (FAILURE_HANDLING) || defined (RF24_LINUX)
  665. if(millis() - timer > 95){
  666. errNotify();
  667. #if defined (FAILURE_HANDLING)
  668. return 0;
  669. #else
  670. delay(100);
  671. #endif
  672. }
  673. #endif
  674. }
  675. ce(LOW);
  676. uint8_t status = write_register(NRF_STATUS,_BV(RX_DR) | _BV(TX_DS) | _BV(MAX_RT) );
  677. //Max retries exceeded
  678. if( status & _BV(MAX_RT)){
  679. flush_tx(); //Only going to be 1 packet int the FIFO at a time using this method, so just flush
  680. return 0;
  681. }
  682. //TX OK 1 or 0
  683. return 1;
  684. }
  685. bool RF24::write( const void* buf, uint8_t len ){
  686. return write(buf,len,0);
  687. }
  688. /****************************************************************************/
  689. //For general use, the interrupt flags are not important to clear
  690. bool RF24::writeBlocking( const void* buf, uint8_t len, uint32_t timeout )
  691. {
  692. //Block until the FIFO is NOT full.
  693. //Keep track of the MAX retries and set auto-retry if seeing failures
  694. //This way the FIFO will fill up and allow blocking until packets go through
  695. //The radio will auto-clear everything in the FIFO as long as CE remains high
  696. uint32_t timer = millis(); //Get the time that the payload transmission started
  697. while( ( get_status() & ( _BV(TX_FULL) ))) { //Blocking only if FIFO is full. This will loop and block until TX is successful or timeout
  698. if( get_status() & _BV(MAX_RT)){ //If MAX Retries have been reached
  699. reUseTX(); //Set re-transmit and clear the MAX_RT interrupt flag
  700. if(millis() - timer > timeout){ return 0; } //If this payload has exceeded the user-defined timeout, exit and return 0
  701. }
  702. #if defined (FAILURE_HANDLING) || defined (RF24_LINUX)
  703. if(millis() - timer > (timeout+95) ){
  704. errNotify();
  705. #if defined (FAILURE_HANDLING)
  706. return 0;
  707. #endif
  708. }
  709. #endif
  710. }
  711. //Start Writing
  712. startFastWrite(buf,len,0); //Write the payload if a buffer is clear
  713. return 1; //Return 1 to indicate successful transmission
  714. }
  715. /****************************************************************************/
  716. void RF24::reUseTX(){
  717. write_register(NRF_STATUS,_BV(MAX_RT) ); //Clear max retry flag
  718. spiTrans( REUSE_TX_PL );
  719. ce(LOW); //Re-Transfer packet
  720. ce(HIGH);
  721. }
  722. /****************************************************************************/
  723. bool RF24::writeFast( const void* buf, uint8_t len, const bool multicast )
  724. {
  725. //Block until the FIFO is NOT full.
  726. //Keep track of the MAX retries and set auto-retry if seeing failures
  727. //Return 0 so the user can control the retrys and set a timer or failure counter if required
  728. //The radio will auto-clear everything in the FIFO as long as CE remains high
  729. #if defined (FAILURE_HANDLING) || defined (RF24_LINUX)
  730. uint32_t timer = millis();
  731. #endif
  732. while( ( get_status() & ( _BV(TX_FULL) ))) { //Blocking only if FIFO is full. This will loop and block until TX is successful or fail
  733. if( get_status() & _BV(MAX_RT)){
  734. //reUseTX(); //Set re-transmit
  735. write_register(NRF_STATUS,_BV(MAX_RT) ); //Clear max retry flag
  736. return 0; //Return 0. The previous payload has been retransmitted
  737. //From the user perspective, if you get a 0, just keep trying to send the same payload
  738. }
  739. #if defined (FAILURE_HANDLING) || defined (RF24_LINUX)
  740. if(millis() - timer > 95 ){
  741. errNotify();
  742. #if defined (FAILURE_HANDLING)
  743. return 0;
  744. #endif
  745. }
  746. #endif
  747. }
  748. //Start Writing
  749. startFastWrite(buf,len,multicast);
  750. return 1;
  751. }
  752. bool RF24::writeFast( const void* buf, uint8_t len ){
  753. return writeFast(buf,len,0);
  754. }
  755. /****************************************************************************/
  756. //Per the documentation, we want to set PTX Mode when not listening. Then all we do is write data and set CE high
  757. //In this mode, if we can keep the FIFO buffers loaded, packets will transmit immediately (no 130us delay)
  758. //Otherwise we enter Standby-II mode, which is still faster than standby mode
  759. //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
  760. void RF24::startFastWrite( const void* buf, uint8_t len, const bool multicast, bool startTx){ //TMRh20
  761. //write_payload( buf,len);
  762. write_payload( buf, len,multicast ? W_TX_PAYLOAD_NO_ACK : W_TX_PAYLOAD ) ;
  763. if(startTx){
  764. ce(HIGH);
  765. }
  766. }
  767. /****************************************************************************/
  768. //Added the original startWrite back in so users can still use interrupts, ack payloads, etc
  769. //Allows the library to pass all tests
  770. void RF24::startWrite( const void* buf, uint8_t len, const bool multicast ){
  771. // Send the payload
  772. //write_payload( buf, len );
  773. write_payload( buf, len,multicast? W_TX_PAYLOAD_NO_ACK : W_TX_PAYLOAD ) ;
  774. ce(HIGH);
  775. #if !defined(F_CPU) || F_CPU > 20000000
  776. delayMicroseconds(10);
  777. #endif
  778. ce(LOW);
  779. }
  780. /****************************************************************************/
  781. bool RF24::rxFifoFull(){
  782. return read_register(FIFO_STATUS) & _BV(RX_FULL);
  783. }
  784. /****************************************************************************/
  785. bool RF24::txStandBy(){
  786. #if defined (FAILURE_HANDLING) || defined (RF24_LINUX)
  787. uint32_t timeout = millis();
  788. #endif
  789. while( ! (read_register(FIFO_STATUS) & _BV(TX_EMPTY)) ){
  790. if( get_status() & _BV(MAX_RT)){
  791. write_register(NRF_STATUS,_BV(MAX_RT) );
  792. ce(LOW);
  793. flush_tx(); //Non blocking, flush the data
  794. return 0;
  795. }
  796. #if defined (FAILURE_HANDLING) || defined (RF24_LINUX)
  797. if( millis() - timeout > 95){
  798. errNotify();
  799. #if defined (FAILURE_HANDLING)
  800. return 0;
  801. #endif
  802. }
  803. #endif
  804. }
  805. ce(LOW); //Set STANDBY-I mode
  806. return 1;
  807. }
  808. /****************************************************************************/
  809. bool RF24::txStandBy(uint32_t timeout, bool startTx){
  810. if(startTx){
  811. stopListening();
  812. ce(HIGH);
  813. }
  814. uint32_t start = millis();
  815. while( ! (read_register(FIFO_STATUS) & _BV(TX_EMPTY)) ){
  816. if( get_status() & _BV(MAX_RT)){
  817. write_register(NRF_STATUS,_BV(MAX_RT) );
  818. ce(LOW); //Set re-transmit
  819. ce(HIGH);
  820. if(millis() - start >= timeout){
  821. ce(LOW); flush_tx(); return 0;
  822. }
  823. }
  824. #if defined (FAILURE_HANDLING) || defined (RF24_LINUX)
  825. if( millis() - start > (timeout+95)){
  826. errNotify();
  827. #if defined (FAILURE_HANDLING)
  828. return 0;
  829. #endif
  830. }
  831. #endif
  832. }
  833. ce(LOW); //Set STANDBY-I mode
  834. return 1;
  835. }
  836. /****************************************************************************/
  837. void RF24::maskIRQ(bool tx, bool fail, bool rx){
  838. uint8_t config = read_register(NRF_CONFIG);
  839. /* clear the interrupt flags */
  840. config &= ~(1 << MASK_MAX_RT | 1 << MASK_TX_DS | 1 << MASK_RX_DR);
  841. /* set the specified interrupt flags */
  842. config |= fail << MASK_MAX_RT | tx << MASK_TX_DS | rx << MASK_RX_DR;
  843. write_register(NRF_CONFIG, config);
  844. }
  845. /****************************************************************************/
  846. uint8_t RF24::getDynamicPayloadSize(void)
  847. {
  848. uint8_t result = 0;
  849. #if defined (RF24_LINUX)
  850. spi_txbuff[0] = R_RX_PL_WID;
  851. spi_rxbuff[1] = 0xff;
  852. beginTransaction();
  853. _SPI.transfernb( (char *) spi_txbuff, (char *) spi_rxbuff, 2);
  854. result = spi_rxbuff[1];
  855. endTransaction();
  856. #else
  857. beginTransaction();
  858. _SPI.transfer( R_RX_PL_WID );
  859. result = _SPI.transfer(0xff);
  860. endTransaction();
  861. #endif
  862. if(result > 32) { flush_rx(); delay(2); return 0; }
  863. return result;
  864. }
  865. /****************************************************************************/
  866. bool RF24::available(void)
  867. {
  868. return available(NULL);
  869. }
  870. /****************************************************************************/
  871. bool RF24::available(uint8_t* pipe_num)
  872. {
  873. if (!( read_register(FIFO_STATUS) & _BV(RX_EMPTY) )){
  874. // If the caller wants the pipe number, include that
  875. if ( pipe_num ){
  876. uint8_t status = get_status();
  877. *pipe_num = ( status >> RX_P_NO ) & 0x07;
  878. }
  879. return 1;
  880. }
  881. return 0;
  882. }
  883. /****************************************************************************/
  884. void RF24::read( void* buf, uint8_t len ){
  885. // Fetch the payload
  886. read_payload( buf, len );
  887. //Clear the two possible interrupt flags with one command
  888. write_register(NRF_STATUS,_BV(RX_DR) | _BV(MAX_RT) | _BV(TX_DS) );
  889. }
  890. /****************************************************************************/
  891. void RF24::whatHappened(bool& tx_ok,bool& tx_fail,bool& rx_ready)
  892. {
  893. // Read the status & reset the status in one easy call
  894. // Or is that such a good idea?
  895. uint8_t status = write_register(NRF_STATUS,_BV(RX_DR) | _BV(TX_DS) | _BV(MAX_RT) );
  896. // Report to the user what happened
  897. tx_ok = status & _BV(TX_DS);
  898. tx_fail = status & _BV(MAX_RT);
  899. rx_ready = status & _BV(RX_DR);
  900. }
  901. /****************************************************************************/
  902. void RF24::openWritingPipe(uint64_t value)
  903. {
  904. // Note that AVR 8-bit uC's store this LSB first, and the NRF24L01(+)
  905. // expects it LSB first too, so we're good.
  906. write_register(RX_ADDR_P0, reinterpret_cast<uint8_t*>(&value), addr_width);
  907. write_register(TX_ADDR, reinterpret_cast<uint8_t*>(&value), addr_width);
  908. //const uint8_t max_payload_size = 32;
  909. //write_register(RX_PW_P0,rf24_min(payload_size,max_payload_size));
  910. write_register(RX_PW_P0,payload_size);
  911. }
  912. /****************************************************************************/
  913. void RF24::openWritingPipe(const uint8_t *address)
  914. {
  915. // Note that AVR 8-bit uC's store this LSB first, and the NRF24L01(+)
  916. // expects it LSB first too, so we're good.
  917. write_register(RX_ADDR_P0,address, addr_width);
  918. write_register(TX_ADDR, address, addr_width);
  919. //const uint8_t max_payload_size = 32;
  920. //write_register(RX_PW_P0,rf24_min(payload_size,max_payload_size));
  921. write_register(RX_PW_P0,payload_size);
  922. }
  923. /****************************************************************************/
  924. static const uint8_t child_pipe[] PROGMEM =
  925. {
  926. RX_ADDR_P0, RX_ADDR_P1, RX_ADDR_P2, RX_ADDR_P3, RX_ADDR_P4, RX_ADDR_P5
  927. };
  928. static const uint8_t child_payload_size[] PROGMEM =
  929. {
  930. RX_PW_P0, RX_PW_P1, RX_PW_P2, RX_PW_P3, RX_PW_P4, RX_PW_P5
  931. };
  932. void RF24::openReadingPipe(uint8_t child, uint64_t address)
  933. {
  934. // If this is pipe 0, cache the address. This is needed because
  935. // openWritingPipe() will overwrite the pipe 0 address, so
  936. // startListening() will have to restore it.
  937. if (child == 0){
  938. memcpy(pipe0_reading_address,&address,addr_width);
  939. }
  940. if (child <= 6)
  941. {
  942. // For pipes 2-5, only write the LSB
  943. if ( child < 2 )
  944. write_register(pgm_read_byte(&child_pipe[child]), reinterpret_cast<const uint8_t*>(&address), addr_width);
  945. else
  946. write_register(pgm_read_byte(&child_pipe[child]), reinterpret_cast<const uint8_t*>(&address), 1);
  947. write_register(pgm_read_byte(&child_payload_size[child]),payload_size);
  948. // Note it would be more efficient to set all of the bits for all open
  949. // pipes at once. However, I thought it would make the calling code
  950. // more simple to do it this way.
  951. write_register(EN_RXADDR,read_register(EN_RXADDR) | _BV(pgm_read_byte(&child_pipe_enable[child])));
  952. }
  953. }
  954. /****************************************************************************/
  955. void RF24::setAddressWidth(uint8_t a_width){
  956. if(a_width -= 2){
  957. write_register(SETUP_AW,a_width%4);
  958. addr_width = (a_width%4) + 2;
  959. }else{
  960. write_register(SETUP_AW,0);
  961. addr_width = 2;
  962. }
  963. }
  964. /****************************************************************************/
  965. void RF24::openReadingPipe(uint8_t child, const uint8_t *address)
  966. {
  967. // If this is pipe 0, cache the address. This is needed because
  968. // openWritingPipe() will overwrite the pipe 0 address, so
  969. // startListening() will have to restore it.
  970. if (child == 0){
  971. memcpy(pipe0_reading_address,address,addr_width);
  972. }
  973. if (child <= 6)
  974. {
  975. // For pipes 2-5, only write the LSB
  976. if ( child < 2 ){
  977. write_register(pgm_read_byte(&child_pipe[child]), address, addr_width);
  978. }else{
  979. write_register(pgm_read_byte(&child_pipe[child]), address, 1);
  980. }
  981. write_register(pgm_read_byte(&child_payload_size[child]),payload_size);
  982. // Note it would be more efficient to set all of the bits for all open
  983. // pipes at once. However, I thought it would make the calling code
  984. // more simple to do it this way.
  985. write_register(EN_RXADDR,read_register(EN_RXADDR) | _BV(pgm_read_byte(&child_pipe_enable[child])));
  986. }
  987. }
  988. /****************************************************************************/
  989. void RF24::closeReadingPipe( uint8_t pipe )
  990. {
  991. write_register(EN_RXADDR,read_register(EN_RXADDR) & ~_BV(pgm_read_byte(&child_pipe_enable[pipe])));
  992. }
  993. /****************************************************************************/
  994. void RF24::toggle_features(void)
  995. {
  996. beginTransaction();
  997. _SPI.transfer( ACTIVATE );
  998. _SPI.transfer( 0x73 );
  999. endTransaction();
  1000. }
  1001. /****************************************************************************/
  1002. void RF24::enableDynamicPayloads(void)
  1003. {
  1004. // Enable dynamic payload throughout the system
  1005. //toggle_features();
  1006. write_register(FEATURE,read_register(FEATURE) | _BV(EN_DPL) );
  1007. IF_SERIAL_DEBUG(printf("FEATURE=%i\r\n",read_register(FEATURE)));
  1008. // Enable dynamic payload on all pipes
  1009. //
  1010. // Not sure the use case of only having dynamic payload on certain
  1011. // pipes, so the library does not support it.
  1012. write_register(DYNPD,read_register(DYNPD) | _BV(DPL_P5) | _BV(DPL_P4) | _BV(DPL_P3) | _BV(DPL_P2) | _BV(DPL_P1) | _BV(DPL_P0));
  1013. dynamic_payloads_enabled = true;
  1014. }
  1015. /****************************************************************************/
  1016. void RF24::disableDynamicPayloads(void)
  1017. {
  1018. // Disables dynamic payload throughout the system. Also disables Ack Payloads
  1019. //toggle_features();
  1020. write_register(FEATURE, 0);
  1021. IF_SERIAL_DEBUG(printf("FEATURE=%i\r\n",read_register(FEATURE)));
  1022. // Disable dynamic payload on all pipes
  1023. //
  1024. // Not sure the use case of only having dynamic payload on certain
  1025. // pipes, so the library does not support it.
  1026. write_register(DYNPD, 0);
  1027. dynamic_payloads_enabled = false;
  1028. }
  1029. /****************************************************************************/
  1030. void RF24::enableAckPayload(void)
  1031. {
  1032. //
  1033. // enable ack payload and dynamic payload features
  1034. //
  1035. //toggle_features();
  1036. write_register(FEATURE,read_register(FEATURE) | _BV(EN_ACK_PAY) | _BV(EN_DPL) );
  1037. IF_SERIAL_DEBUG(printf("FEATURE=%i\r\n",read_register(FEATURE)));
  1038. //
  1039. // Enable dynamic payload on pipes 0 & 1
  1040. //
  1041. write_register(DYNPD,read_register(DYNPD) | _BV(DPL_P1) | _BV(DPL_P0));
  1042. dynamic_payloads_enabled = true;
  1043. }
  1044. /****************************************************************************/
  1045. void RF24::enableDynamicAck(void){
  1046. //
  1047. // enable dynamic ack features
  1048. //
  1049. //toggle_features();
  1050. write_register(FEATURE,read_register(FEATURE) | _BV(EN_DYN_ACK) );
  1051. IF_SERIAL_DEBUG(printf("FEATURE=%i\r\n",read_register(FEATURE)));
  1052. }
  1053. /****************************************************************************/
  1054. void RF24::writeAckPayload(uint8_t pipe, const void* buf, uint8_t len)
  1055. {
  1056. const uint8_t* current = reinterpret_cast<const uint8_t*>(buf);
  1057. uint8_t data_len = rf24_min(len,32);
  1058. #if defined (RF24_LINUX)
  1059. beginTransaction();
  1060. uint8_t * ptx = spi_txbuff;
  1061. uint8_t size = data_len + 1 ; // Add register value to transmit buffer
  1062. *ptx++ = W_ACK_PAYLOAD | ( pipe & 0x07 );
  1063. while ( data_len-- ){
  1064. *ptx++ = *current++;
  1065. }
  1066. _SPI.transfern( (char *) spi_txbuff, size);
  1067. endTransaction();
  1068. #else
  1069. beginTransaction();
  1070. _SPI.transfer(W_ACK_PAYLOAD | ( pipe & 0x07 ) );
  1071. while ( data_len-- )
  1072. _SPI.transfer(*current++);
  1073. endTransaction();
  1074. #endif
  1075. }
  1076. /****************************************************************************/
  1077. bool RF24::isAckPayloadAvailable(void)
  1078. {
  1079. return ! (read_register(FIFO_STATUS) & _BV(RX_EMPTY));
  1080. }
  1081. /****************************************************************************/
  1082. bool RF24::isPVariant(void)
  1083. {
  1084. return p_variant ;
  1085. }
  1086. /****************************************************************************/
  1087. void RF24::setAutoAck(bool enable)
  1088. {
  1089. if ( enable )
  1090. write_register(EN_AA, 0x3F);
  1091. else
  1092. write_register(EN_AA, 0);
  1093. }
  1094. /****************************************************************************/
  1095. void RF24::setAutoAck( uint8_t pipe, bool enable )
  1096. {
  1097. if ( pipe <= 6 )
  1098. {
  1099. uint8_t en_aa = read_register( EN_AA ) ;
  1100. if( enable )
  1101. {
  1102. en_aa |= _BV(pipe) ;
  1103. }
  1104. else
  1105. {
  1106. en_aa &= ~_BV(pipe) ;
  1107. }
  1108. write_register( EN_AA, en_aa ) ;
  1109. }
  1110. }
  1111. /****************************************************************************/
  1112. bool RF24::testCarrier(void)
  1113. {
  1114. return ( read_register(CD) & 1 );
  1115. }
  1116. /****************************************************************************/
  1117. bool RF24::testRPD(void)
  1118. {
  1119. return ( read_register(RPD) & 1 ) ;
  1120. }
  1121. /****************************************************************************/
  1122. void RF24::setPALevel(uint8_t level)
  1123. {
  1124. uint8_t setup = read_register(RF_SETUP) & 0xF8;
  1125. if(level > 3){ // If invalid level, go to max PA
  1126. level = (RF24_PA_MAX << 1) + 1; // +1 to support the SI24R1 chip extra bit
  1127. }else{
  1128. level = (level << 1) + 1; // Else set level as requested
  1129. }
  1130. write_register( RF_SETUP, setup |= level ) ; // Write it to the chip
  1131. }
  1132. /****************************************************************************/
  1133. uint8_t RF24::getPALevel(void)
  1134. {
  1135. return (read_register(RF_SETUP) & (_BV(RF_PWR_LOW) | _BV(RF_PWR_HIGH))) >> 1 ;
  1136. }
  1137. /****************************************************************************/
  1138. bool RF24::setDataRate(rf24_datarate_e speed)
  1139. {
  1140. bool result = false;
  1141. uint8_t setup = read_register(RF_SETUP) ;
  1142. // HIGH and LOW '00' is 1Mbs - our default
  1143. setup &= ~(_BV(RF_DR_LOW) | _BV(RF_DR_HIGH)) ;
  1144. #if !defined(F_CPU) || F_CPU > 20000000
  1145. txDelay=250;
  1146. #else //16Mhz Arduino
  1147. txDelay=85;
  1148. #endif
  1149. if( speed == RF24_250KBPS )
  1150. {
  1151. // Must set the RF_DR_LOW to 1; RF_DR_HIGH (used to be RF_DR) is already 0
  1152. // Making it '10'.
  1153. setup |= _BV( RF_DR_LOW ) ;
  1154. #if !defined(F_CPU) || F_CPU > 20000000
  1155. txDelay=450;
  1156. #else //16Mhz Arduino
  1157. txDelay=155;
  1158. #endif
  1159. }
  1160. else
  1161. {
  1162. // Set 2Mbs, RF_DR (RF_DR_HIGH) is set 1
  1163. // Making it '01'
  1164. if ( speed == RF24_2MBPS )
  1165. {
  1166. setup |= _BV(RF_DR_HIGH);
  1167. #if !defined(F_CPU) || F_CPU > 20000000
  1168. txDelay=190;
  1169. #else //16Mhz Arduino
  1170. txDelay=65;
  1171. #endif
  1172. }
  1173. }
  1174. write_register(RF_SETUP,setup);
  1175. // Verify our result
  1176. if ( read_register(RF_SETUP) == setup )
  1177. {
  1178. result = true;
  1179. }
  1180. return result;
  1181. }
  1182. /****************************************************************************/
  1183. rf24_datarate_e RF24::getDataRate( void )
  1184. {
  1185. rf24_datarate_e result ;
  1186. uint8_t dr = read_register(RF_SETUP) & (_BV(RF_DR_LOW) | _BV(RF_DR_HIGH));
  1187. // switch uses RAM (evil!)
  1188. // Order matters in our case below
  1189. if ( dr == _BV(RF_DR_LOW) )
  1190. {
  1191. // '10' = 250KBPS
  1192. result = RF24_250KBPS ;
  1193. }
  1194. else if ( dr == _BV(RF_DR_HIGH) )
  1195. {
  1196. // '01' = 2MBPS
  1197. result = RF24_2MBPS ;
  1198. }
  1199. else
  1200. {
  1201. // '00' = 1MBPS
  1202. result = RF24_1MBPS ;
  1203. }
  1204. return result ;
  1205. }
  1206. /****************************************************************************/
  1207. void RF24::setCRCLength(rf24_crclength_e length)
  1208. {
  1209. uint8_t config = read_register(NRF_CONFIG) & ~( _BV(CRCO) | _BV(EN_CRC)) ;
  1210. // switch uses RAM (evil!)
  1211. if ( length == RF24_CRC_DISABLED )
  1212. {
  1213. // Do nothing, we turned it off above.
  1214. }
  1215. else if ( length == RF24_CRC_8 )
  1216. {
  1217. config |= _BV(EN_CRC);
  1218. }
  1219. else
  1220. {
  1221. config |= _BV(EN_CRC);
  1222. config |= _BV( CRCO );
  1223. }
  1224. write_register( NRF_CONFIG, config ) ;
  1225. }
  1226. /****************************************************************************/
  1227. rf24_crclength_e RF24::getCRCLength(void)
  1228. {
  1229. rf24_crclength_e result = RF24_CRC_DISABLED;
  1230. uint8_t config = read_register(NRF_CONFIG) & ( _BV(CRCO) | _BV(EN_CRC)) ;
  1231. uint8_t AA = read_register(EN_AA);
  1232. if ( config & _BV(EN_CRC ) || AA)
  1233. {
  1234. if ( config & _BV(CRCO) )
  1235. result = RF24_CRC_16;
  1236. else
  1237. result = RF24_CRC_8;
  1238. }
  1239. return result;
  1240. }
  1241. /****************************************************************************/
  1242. void RF24::disableCRC( void )
  1243. {
  1244. uint8_t disable = read_register(NRF_CONFIG) & ~_BV(EN_CRC) ;
  1245. write_register( NRF_CONFIG, disable ) ;
  1246. }
  1247. /****************************************************************************/
  1248. void RF24::setRetries(uint8_t delay, uint8_t count)
  1249. {
  1250. write_register(SETUP_RETR,(delay&0xf)<<ARD | (count&0xf)<<ARC);
  1251. }
  1252. //ATTiny support code pulled in from https://github.com/jscrane/RF24
  1253. #if defined(RF24_TINY)
  1254. void SPIClass::begin() {
  1255. // set USCK and DO for output
  1256. // set DI for input
  1257. #if defined(__AVR_ATtiny25__) || defined(__AVR_ATtiny45__) || defined(__AVR_ATtiny85__)
  1258. DDRB |= (1 << PB2) | (1 << PB1);
  1259. DDRB &= ~(1 << PB0);
  1260. #elif defined(__AVR_ATtiny24__) || defined(__AVR_ATtiny44__) || defined(__AVR_ATtiny84__)
  1261. DDRA |= (1 << PA4) | (1 << PA5);
  1262. DDRA &= ~(1 << PA6);
  1263. #elif defined(__AVR_ATtiny2313__) || defined(__AVR_ATtiny4313__)
  1264. DDRB |= (1 << PB7) | (1 << PB6);
  1265. DDRB &= ~(1 << PB5);
  1266. #elif defined(__AVR_ATtiny861__)
  1267. DDRB |= (1 << PB2) | (1 << PB1);
  1268. DDRB &= ~(1 << PB0);
  1269. #endif
  1270. USICR = _BV(USIWM0);
  1271. }
  1272. byte SPIClass::transfer(byte b) {
  1273. USIDR = b;
  1274. USISR = _BV(USIOIF);
  1275. do
  1276. USICR = _BV(USIWM0) | _BV(USICS1) | _BV(USICLK) | _BV(USITC);
  1277. while ((USISR & _BV(USIOIF)) == 0);
  1278. return USIDR;
  1279. }
  1280. void SPIClass::end() {}
  1281. void SPIClass::setDataMode(uint8_t mode){}
  1282. void SPIClass::setBitOrder(uint8_t bitOrder){}
  1283. void SPIClass::setClockDivider(uint8_t rate){}
  1284. #endif