Advertisement
Guest User

Untitled

a guest
Feb 25th, 2018
114
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 38.56 KB | None | 0 0
  1. #define F_CPU 16000000UL
  2. #define BAUD 57600 // NB not good for 115200, possibly need U2X high precision mode. Use setbaud.h features?
  3.  
  4. //#include <util/setbaud.h>
  5. #include <util/delay.h>
  6. #include <inttypes.h>
  7. #include "nRF24L01.h"
  8.  
  9. // ******************************************
  10. //
  11. // UART stuff - minimal logging
  12. //
  13. // ******************************************
  14.  
  15. #define UART_MAX_ECHOABLE_ARRAY_LEN 50 // 5 byte array of unit8_t plus commas = 20 chars string length plus terminating 0
  16.  
  17. void uart_init() {
  18.     UBRR0 = F_CPU/16/BAUD-1; // NB this will set the 0L and the 0H. The BAUD-1 part is from the AVR datasheet, presumably kills an OBO error.
  19.     UCSR0B = (1<<RXEN0)|(1<<TXEN0); // Enable receive and transmit
  20.     UCSR0C = _BV(UCSZ01) | _BV(UCSZ00); // 8 data, 2 stop?
  21. }
  22.  
  23. void uart_putchar(char c) {
  24.     loop_until_bit_is_set(UCSR0A, UDRE0); /* Wait until data register empty. */
  25.     UDR0 = c;
  26. }
  27.  
  28. char uart_getchar(void) {
  29.     loop_until_bit_is_set(UCSR0A, RXC0); /* Wait until data exists. */
  30.     return UDR0;
  31. }
  32.  
  33. void uart_send(const char *txt){
  34.   uint8_t index = 0;
  35.   while(txt[index] != 0){
  36.    uart_putchar(txt[index]);
  37.    index++;
  38.   }
  39. }
  40.  
  41. void uart_send(int num){
  42.   char chars[7] = {0}; // Maximum length for decimal string representation of an an int is  7 chars, as in "-32767\0"
  43.   uart_int_to_decimal(num, chars);
  44.   uart_send(chars);
  45. }
  46.  
  47. void uart_send_hex(uint8_t num){
  48.   char chars[3] = {0}; // Maximum length for hexadecimal string representation of an a uint8_t is 3 chars, as in "FF\0"
  49.   uart_int_to_hex(num, chars);
  50.   uart_send(chars);
  51. }
  52.  
  53. void uart_sendl(const char *txt){
  54.   uart_send(txt);
  55.   uart_send("\r\n");
  56. }
  57.  
  58. void uart_sendl(int num){
  59.   uart_send(num);
  60.   uart_send("\r\n");
  61. }
  62.  
  63. void uart_send(uint8_t* array, uint8_t len){
  64.   char txt[UART_MAX_ECHOABLE_ARRAY_LEN] = {0};
  65.   uart_array_to_hex(array, len, txt);
  66.   uart_send(txt);
  67. }
  68.  
  69. void uart_array_to_hex(uint8_t* array, uint8_t len, char *txt){
  70.   for(uint8_t i = 0; i < len; i++){
  71.      char arrayMember[3] = {0}; // Max len
  72.      uart_int_to_hex(array[i], arrayMember);
  73.      uint8_t memberIdx = 0;
  74.      int foo = 0;
  75.      while(arrayMember[memberIdx] != 0){
  76.        txt[0] = arrayMember[memberIdx];
  77.        memberIdx ++;
  78.        txt++;
  79.        foo++;
  80.      }
  81.      if(i < len-1){
  82.        txt[0] = ',';
  83.        txt++;
  84.      }
  85.   }
  86. };
  87.  
  88. void uart_int_to_decimal(int value, char *ptr){
  89.   int temp;
  90.   if(value==0){  
  91.     *ptr++='0';
  92.     *ptr='\0';
  93.     return;
  94.   }
  95.   if(value<0){
  96.     value*=(-1);    
  97.     *ptr++='-';
  98.   }
  99.  
  100.   for(temp=value;temp>0;temp/=10,ptr++);
  101.   *ptr='\0';
  102.   for(temp=value;temp>0;temp/=10){
  103.     *--ptr=temp%10+'0';
  104.   }
  105. }
  106.  
  107. char hexchars[]="0123456789ABCDEF";
  108. void uart_int_to_hex(uint8_t value, char *ptr){
  109.  
  110.   ptr[0] = (hexchars[(value>>4)&0xf]);
  111.   ptr[1] = (hexchars[value&0xf]);
  112. }
  113.  
  114. // ******************************************
  115. //
  116. // Nordic Semiconductor nRF24L01+
  117. //
  118. // ******************************************
  119.  
  120. uint8_t nrf_master_address[5] = {0xE1,0xE2,0xE3,0xE4,0xE5};
  121. uint8_t nrf_slave_address[5] = {0xD1,0xD2,0xD3,0xD4,0xD5};
  122.  
  123. // CE is green; D9 = PB5
  124. // CSN is D10 = PB2
  125.  
  126. // Where is the hardware connected?
  127.  
  128. #define SPI_DEVICE_NRF 0 // See further info about this spi device under "spi stuff" below
  129. #define NRF_PORT PORTB
  130. #define NRF_PORT_DIR DDRB
  131. #define NRF_CSN_PIN 2
  132. #define NRF_CE_PIN 1
  133. #define NRF_USE_INTX true  // Use INT0 or INT1 to signal nRF activity. Generally this will be used on receive.
  134. #define NRF_WHICH_INT 0 // INT0 or INT1. You need to define ISR (INTx_vect){...} as appropriate.
  135.  
  136. // Options
  137.  
  138. #define NRF_DEFAULT_FREQUENCY 2478 // 2478 is above wifi and legal in the USA.
  139. #define NRF_DEFAULT_PAYLOAD_WIDTH 3 // in bytes. Used to set RX pipe width.
  140. #define NRF_ROLE_TX true // This is default
  141. #define NRF_ROLE_RX false
  142. #define NRF_FCC_COMPLIANT true // Limits frequencies to < 2.482GHz for US regulatory compliance
  143. #define NRF_DEFAULT_RETRIES 3 // Up to 15
  144. #define NRF_DEFAULT_RETRY_DELAY 0 // Sets retry delay according to the formula (n+1)*250uS up to 15=4000us.
  145. #define NRF_USE_AUTO_ACKNOWLEDGE true
  146. #define NRF_TEST_ROLE NRF_ROLE_TX
  147.  
  148. // Some nRF24L01 resources suggest a 10us delay after some ops, particularly sending SPI commands
  149. // and before sending data associated with that command. Often this seems unnecessary so it's
  150. // selectable here.
  151.  
  152. #define USE_NRF_DELAY 0
  153. #if USE_NRF_DELAY == 1
  154.   #define NRF_COURTESY_DELAY _delay_us(10);
  155. #else
  156.   #define NRF_COURTESY_DELAY
  157. #endif
  158.  
  159. // Caution: these extra defines, not in nRF24L01.h, represent
  160. // features which are possibly nRF24L01+ only.
  161.  
  162. #define FEATURE 0x1D // This is a register
  163. #define EN_DPL 0x02  // Enable dynamic payload
  164. #define EN_ACK_PAY 0x01
  165. #define EN_DYN_ACK 0x00
  166. #define CONT_WAVE 0x07
  167. #define RF_DR_LOW 0x05
  168. #define RF_DR_HIGH 0x03
  169. #define RPD 0x00
  170. #define W_TX_PAYLOAD_NOACK 0xB0 // Command which was missing from the header
  171.  
  172. // Select and deselect the nRF chip. NB that CS on the nRF is active-low.
  173. // This all now handled with spi_select etc.
  174. // FIXME: spi_select does not support NRF_COURTESY_DELAY, though that seems unnecessary.
  175. // Be careful in case this causes future problems.
  176.  
  177. /*
  178. void nrf_select(){
  179.   spi_select(SPI_DEVICE_NRF);
  180.   //uart_sendl(NRF_PORT);
  181.   //NRF_PORT &= ~(1<<NRF_CSN_PIN);
  182.   NRF_COURTESY_DELAY
  183. }
  184.  
  185. void //nrf_deselect(){
  186.   spi_deselect();
  187.   //NRF_PORT |= (1<<NRF_CSN_PIN);
  188.   NRF_COURTESY_DELAY
  189. }
  190. */
  191. // Enable and disable the nRF chip. This is active-high.
  192.  
  193. void nrf_enable(){
  194.   NRF_PORT |= (1<<NRF_CE_PIN);
  195.   NRF_COURTESY_DELAY
  196. }
  197.  
  198. void nrf_disable(){
  199.   NRF_PORT &= ~(1<<NRF_CE_PIN);
  200.   NRF_COURTESY_DELAY
  201. }
  202.  
  203. // Get a single-byte registerM
  204.  
  205. uint8_t nrf_getreg(uint8_t reg){
  206.   //nrf_select();
  207.   spi_select(SPI_DEVICE_NRF);
  208.   reg = spi_transact(reg); // Should really be R_REGISTER | reg, but R_REGISTER is 0.
  209.   NRF_COURTESY_DELAY
  210.   uint8_t val = spi_transact(0b00000000); // Dummy byte so the SPI sends zeroes
  211.   NRF_COURTESY_DELAY
  212.   //nrf_deselect();
  213.   spi_deselect();
  214.   return val;
  215. }
  216.  
  217. // Get a multi-byte register
  218.  
  219. void nrf_getreg(uint8_t reg, uint8_t len, uint8_t* val){
  220.   int i;
  221.   NRF_COURTESY_DELAY
  222.   //nrf_select();
  223.   spi_select(SPI_DEVICE_NRF);
  224.   reg = spi_transact(reg); // Should really be R_REGISTER | reg, but R_REGISTER is 0.
  225.   NRF_COURTESY_DELAY
  226.   for(i = 0; i < len; i++){
  227.     val[i] = spi_transact(0x00); // Dummy byte so the SPI sends zeroes
  228.     NRF_COURTESY_DELAY
  229.   }
  230.   //nrf_deselect();
  231.   spi_deselect();
  232. }
  233.  
  234. // Set a single-byte register
  235.  
  236. void nrf_setreg(uint8_t reg, uint8_t data){
  237.  
  238.   //nrf_select();
  239.   spi_select(SPI_DEVICE_NRF);
  240.   reg = spi_transact(W_REGISTER | reg); // Set which register to write
  241.   NRF_COURTESY_DELAY
  242.   reg = spi_transact(data); // Write data
  243.   NRF_COURTESY_DELAY
  244.   //nrf_deselect();
  245.   spi_deselect();
  246. }
  247.  
  248. // Set a multi-byte register
  249.  
  250. void nrf_setreg(uint8_t reg, uint8_t *data, uint8_t len){
  251.  
  252.   //nrf_select();
  253.   spi_select(SPI_DEVICE_NRF);
  254.   reg = spi_transact(W_REGISTER | reg); // Set which register to write
  255.   NRF_COURTESY_DELAY
  256.   for(uint8_t i = 0; i < len; i++){
  257.     reg = spi_transact(data[i]); // Write data
  258.     NRF_COURTESY_DELAY
  259.   }
  260.   //nrf_deselect();
  261.   spi_deselect();
  262.  
  263. }
  264.  
  265. // Powerup and powerdown the nRF chip.
  266. // It takes 1.5ms with internel osc, or 150us with external osc (which we think
  267. // we have) to get from powerdown to standby, so we don't want to do that too
  268. // often - consider leaving powered up.
  269.  
  270. void nrf_powerup(){
  271.   uint8_t cfreg = nrf_getreg(CONFIG);
  272.   cfreg = cfreg | (1<<PWR_UP);
  273.   nrf_setreg(CONFIG, cfreg);
  274.   _delay_ms(5); // Theoretically 1.5ms to reach stby while CE is low; 150us if we're on external clock which we think we are.
  275. }
  276.  
  277. void nrf_powerdown(){
  278.   uint8_t cfreg = nrf_getreg(CONFIG);
  279.   cfreg &= ~(1<<PWR_UP);
  280.   nrf_setreg(CONFIG, cfreg);
  281.   _delay_ms(5); // FIXME: It doesn't really say how long it takes to power down. This is a courtesy delay and is possibly way, way too long, or unnecessary.
  282. }
  283.  
  284. // Send the payload to the nRF. The command W_TX_PAYLOAD is followed by the bytes to be sent.
  285. // The delays are possibly unnecessary, or at least other than after setting CSN
  286.  
  287. void nrf_tx_immediate(uint8_t* payload, uint8_t len){
  288.  
  289.   //nrf_select();
  290.   spi_select(SPI_DEVICE_NRF);
  291.   if(NRF_USE_AUTO_ACKNOWLEDGE){
  292.     spi_transact(W_TX_PAYLOAD);
  293.   } else {
  294.     spi_transact(W_TX_PAYLOAD_NOACK);
  295.   }
  296.   NRF_COURTESY_DELAY
  297.   for(uint8_t i = 0; i < len; i++){
  298.     spi_transact(payload[i]);
  299.     NRF_COURTESY_DELAY
  300.   }
  301.   //nrf_deselect();
  302.   spi_deselect();
  303.  
  304.   // Pulse CE to actually transmit the data
  305.      
  306.   //nrf_select();
  307.   //NRF_COURTESY_DELAY // In some implementations we needed a 10 millisecond (millisecond!) delay here, but it seems OK without.
  308.   nrf_enable();
  309.   _delay_us(15); // This actually is required per the datasheet; apparently minimum CE high is 10us.
  310.   nrf_disable();
  311.   //NRF_COURTESY_DELAY
  312.   ////nrf_deselect();
  313.   _delay_us(2000); // FIXME: Ensure we've had time for all the retries and so on. With 250us and 3 retries set, 1000 should be enough, but wasn't.
  314.                    // Possibly this is due to PLL settling delay?
  315.                    // Anyway, assuming we're asynchronously sending it won't matter and we can probably take this out
  316.                    
  317.   // Hard reset all the IRQ flags. This appears to be essential.
  318.  
  319.   nrf_clear_irqs();
  320.  
  321. }
  322. // Read received data
  323.  
  324. // This reads everything from the three buffers on the nRF into these three arrays.
  325. // Usually, just ensure we get each one as it comes in; if nrf_getata() != 0, there's
  326. // at least something in nrf_received[0].
  327.  
  328. // Don't call this unless you're happy to have all of nrf_received overwritten
  329.  
  330. uint8_t nrf_received[3][NRF_DEFAULT_PAYLOAD_WIDTH];
  331.  
  332. bool nrf_pendingPkts = false;
  333.  
  334. uint8_t nrf_pollfordata(){
  335.  
  336.   uint8_t msgcount = 0;
  337.  
  338.   while(~nrf_getreg(STATUS) & RX_DR){
  339.     //nrf_select();
  340.     spi_select(SPI_DEVICE_NRF);
  341.     spi_transact(R_RX_PAYLOAD);
  342.     NRF_COURTESY_DELAY
  343.     for(uint8_t i = 0; i < NRF_DEFAULT_PAYLOAD_WIDTH; i++){
  344.       nrf_received[msgcount][i] = spi_transact(0x00);
  345.     }
  346.     /*uart_send("Receive:");
  347.     uart_send(nrf_received[msgcount],NRF_DEFAULT_PAYLOAD_WIDTH);
  348.     uart_sendl("");*/
  349.     msgcount++;
  350.     //nrf_deselect();
  351.     spi_deselect();
  352.   }
  353.   nrf_pendingPkts = false;
  354.   nrf_clear_irqs();
  355.   return msgcount;
  356.  
  357. }
  358.  
  359. // Clear any set IRQ-type-indicating flags. Active low!
  360.  
  361. void nrf_clear_irqs(){
  362.  
  363.   /*
  364.   // RX_DR "received data ready" there is something to receive
  365.   // TX_DS "transmit data sent" (dependent on successful acknowledgement if selected)
  366.   // MAX_RT "maximum number of retries" has been reached.
  367.  
  368.   uint8_t statusReg = nrf_getreg(STATUS);
  369.   statusReg |= (1<<RX_DR | 1<<TX_DS | 1<<MAX_RT);
  370.   nrf_setreg(STATUS, statusReg);
  371.  
  372.   */
  373.  
  374.   /*
  375.    
  376.   // Fastest possible fully-inlined IRQ reset
  377.  
  378.   NRF_PORT &= ~(1<<NRF_CSN_PIN);    // Select nRF chip
  379.   SPDR = W_REGISTER | STATUS;
  380.   while(!(SPSR & (1<<SPIF)));
  381.   // Set all IRQ flags inactive-high
  382.   SPDR = 0x70; // Flag high all the writable bits in the register
  383.   while(!(SPSR & (1<<SPIF)));
  384.   NRF_PORT |= (1<<NRF_CSN_PIN);
  385.  
  386.   */
  387.  
  388.   // Because the only writable bits in STATUS are the three IRQs, and because their value ORs to 0x70
  389.   // this basically boils down to:
  390.  
  391.   nrf_setreg(STATUS, 0x70);
  392.  
  393. }
  394.  
  395. // Flush any leftover stuff in the transmit buffers.
  396.  
  397. void nrf_flush_tx(){
  398.   //nrf_select();
  399.   spi_select(SPI_DEVICE_NRF);
  400.   spi_transact(FLUSH_TX); // FLUSH_TX is a command not a register so it gets sent directly
  401.   NRF_COURTESY_DELAY
  402.   //nrf_deselect();
  403.   spi_deselect();
  404. }
  405.  
  406. // Flush any leftover stuff in the receive buffers.
  407.  
  408. void nrf_flush_rx(){
  409.   //nrf_select();
  410.   spi_select(SPI_DEVICE_NRF);
  411.   spi_transact(FLUSH_RX); // FLUSH_RX is a command not a register so it gets sent directly
  412.   NRF_COURTESY_DELAY
  413.   //nrf_deselect();
  414.   spi_deselect();
  415. }
  416.  
  417. // Be what the datasheet calls a PTX or PRX (primarily transmitter or receiver)
  418.  
  419. void nrf_setrole(bool isTx){
  420.  
  421.   uint8_t cfreg = nrf_getreg(CONFIG);
  422.   if(isTx){
  423.     cfreg &= ~(1<<PRIM_RX); // Be a transmitter
  424.   } else {
  425.     cfreg |= (1<<PRIM_RX);  // Be a receiver
  426.   }
  427.   nrf_setreg(CONFIG, cfreg);
  428.  
  429. }
  430.  
  431. // Set radio freqency. The hardware will do 125 channels, which must be 2+MHz apart at 2Mbps
  432. // Not all channels are legal everywhere.
  433.  
  434. bool nrf_setfreq(int freq){
  435.   if(freq < 2400 || freq > 2525){
  436.     nrf_err("Requested frequency not available");
  437.     return false;
  438.   }
  439.   if(NRF_FCC_COMPLIANT && freq > 2482){
  440.     nrf_err("Cannot set frequency over 2.482GHz with bandwidth <=2MHz in FCC controlled locale");
  441.     return false;
  442.   }
  443.   nrf_setreg(RF_CH, NRF_DEFAULT_FREQUENCY - 2400);
  444.   return true;
  445. }
  446.  
  447. // Set retry count and delay. Not really in use at the moment.
  448. // Args: retries, number of retries <16
  449. //       dly, delay according to (dly + 1) * 250us, for a maximum of 15=4000us
  450.  
  451. void nrf_setretries(uint8_t retries, uint8_t dly){
  452.   nrf_setreg(SETUP_RETR, retries | (dly << ARD)); // ARD is 4, to get the upper 4 bytes.  
  453. }
  454.  
  455. // Set the width of the receive pipe's payload.
  456. // This sets all the pipes, though we really only care about pipe 0 since it's used for auto-ack
  457. // This implementation of the nRF24L01 doesn't deal with multiple pipe operation.
  458.  
  459. void nrf_set_rx_payload_width(uint8_t width){
  460.   for(uint8_t i = 0; i < 6; i++){
  461.     nrf_setreg(RX_PW_P0 + i, width); // Register addresses are sequential, so we can add the incrementing variable
  462.   }
  463. }
  464.  
  465. // Set whether to use auto-acknowledgement
  466.  
  467. void nrf_set_use_auto_ack(bool autoAck){
  468.   if(autoAck){
  469.     nrf_setreg(EN_AA, ENAA_P5 | ENAA_P4 | ENAA_P3 | ENAA_P2 | ENAA_P1 | ENAA_P0);
  470.   } else {
  471.     nrf_setreg(EN_AA,0x00);
  472.   }
  473.  
  474.   // W_TX_PAYLOAD_NOACK command is always enabled in init();
  475.  
  476. }
  477.  
  478. // Log some info about the nRF24L01 setup. Usually just alias to a usart send function.
  479.  
  480. void nrf_log(const char* str){
  481.   uart_sendl(str);
  482. }
  483.  
  484. // Send an error message. Really just adds a prefix. Again, alias to a usart send function.
  485.  
  486. void nrf_err(const char* str){
  487.   uart_send("NRF24L01: Error: ");
  488.   uart_sendl(str);
  489. }
  490.  
  491. // Example ISR for packet arrival. All this does (with the uart_sends commented
  492. // out) is set a flag, but critical timing states could also be stored here.
  493. // Uses nrf_pendingPkts bool to signal stuff available
  494. // NB change defines to point the code to the right interrupt.
  495.  
  496. ISR(INT0_vect) {
  497.   nrf_pendingPkts = true;
  498. }
  499.  
  500. ISR(BADISR_vect){
  501.  uart_sendl("Error in ISR setup.");
  502. }
  503.  
  504. void nrf_disable_interrupts(bool receivedData, bool transmitComplete, bool transmitFailed){
  505.  
  506.   uint8_t val = nrf_getreg(CONFIG);
  507.  
  508.   if(receivedData){
  509.     val |= (1<<MASK_RX_DR);
  510.   } else {
  511.     val &= ~(1<<MASK_RX_DR);    
  512.   }
  513.  
  514.   if(transmitComplete){
  515.     val |= (1<<MASK_TX_DS);
  516.   } else {
  517.     val &= ~(1<<MASK_TX_DS);    
  518.   }
  519.  
  520.   if(transmitFailed){
  521.     val |= (1<<MASK_MAX_RT);
  522.   } else {
  523.     val &= ~(1<<MASK_MAX_RT);    
  524.   }
  525.  
  526.   nrf_setreg(CONFIG, val);
  527.  
  528. }
  529.  
  530. // Set up the nRF chip as from cold start.
  531. // This will clear everything and leave the chip in transmit mode but powered down, deselected and disabled.
  532. // It may take a few milliseconds to run, if the nRF chip needs a long timeout to reach standby.
  533.  
  534. void nrf_init(){
  535.  
  536.   // Set CE and CSN pins to be outputs
  537.   // CE is green wire, arduino pin D9/PB1
  538.   // CSN pin is blue wire, arduino pin D10/PB2, but is now dealt with by the SPI stuff
  539.  
  540.   //NRF_PORT_DIR |= (1<<NRF_CE_PIN) | (1<NRF_CSN_PIN);
  541.   NRF_PORT_DIR |= (1<NRF_CSN_PIN);
  542.  
  543.   // Set up RX interrupts using INTx pins
  544.   // NB - this is set up for the ATmega328. 168 is possibly identical.
  545.  
  546.   if(NRF_USE_INTX){
  547.     if(NRF_WHICH_INT == 0){
  548.       DDRD &= ~(1 << DDD2);      // Make the relevant pin an input
  549.       EICRA |= (1 << ISC01);     // Trigger on falling edges only.
  550.       EIMSK |= (1 << INT0);      // Turns on interrupts for that pin
  551.     } else {
  552.       DDRD &= ~(1 << DDD3);      // Make the relevant pin an input
  553.       EICRA |= (1 << ISC11);     // Trigger on falling edges only.
  554.       EIMSK |= (1 << INT1);      // Turns on interrupts for that pin
  555.     }
  556.     sei();
  557.   }
  558.  
  559.   //nrf_deselect();
  560.   spi_deselect(); // CSN high
  561.   nrf_disable(); // CE low
  562.  
  563.   // Set up nRF24L01 chip.
  564.  
  565.   nrf_powerdown();
  566.   nrf_setrole(NRF_ROLE_TX);
  567.   nrf_setfreq(NRF_DEFAULT_FREQUENCY);
  568.   nrf_setretries(NRF_DEFAULT_RETRIES, NRF_DEFAULT_RETRY_DELAY); // Number of retries <16; Delay (n+1)*250us, max 15=4000us
  569.   nrf_set_rx_payload_width(NRF_DEFAULT_PAYLOAD_WIDTH);
  570.   nrf_flush_tx();
  571.   nrf_flush_rx();
  572.   nrf_clear_irqs();
  573.   nrf_disable_interrupts(false, false, false); // Don't disable any interrupts (probably get modified later anyway)
  574.  
  575.   // Enable sending packets without auto acknowledgement (Always enable this,
  576.   // just don't actually use W_TX_PAYLOAD_NOACK unless we're asked to.)
  577.  
  578.   uint8_t featureReg = nrf_getreg(FEATURE);
  579.   featureReg |= (1 << EN_DYN_ACK); // This equates to 0x01, since EN_DYN_ACK == 0.
  580.   nrf_setreg(FEATURE, featureReg);
  581.  
  582.   // Addresses
  583.   // Set P0 so that basic auto-ack will work, but we aren't really supporting any other pipes in this simple framework
  584.  
  585.   nrf_setreg(TX_ADDR, nrf_master_address, 5); // Set transmission address
  586.   nrf_setreg(RX_ADDR_P0, nrf_master_address, 5); // Pipe-0 receive addr should equal transmission address for automatic acknowledgement
  587.  
  588.   // Finished setup. Send some debug.
  589.  
  590.   //nrf_log("nRF24L01: Post-reset. Status now:");
  591.   //nrf_read_status(); // Reads a bunch of registers and sends out over uart in a sort of human readable format.
  592.  
  593. }
  594.  
  595. // ******************************************
  596. //
  597. // SMPTE-12M Linear Timecode Reader
  598. //
  599. // ******************************************
  600.  
  601. #define LTC_REQUIRED_FRAMES 30
  602. #define LTC_AVG_FRAMES 16
  603.  
  604. uint8_t ltc_magic_number_A = 0b00111111; // 3F
  605. uint8_t ltc_magic_number_B = 0b11111101; // FD
  606. uint8_t ltc_magic_number_A_rev = 0b11111100; // FC
  607. uint8_t ltc_magic_number_B_rev = 0b10111111; // BF
  608. uint8_t ltc_bitperiod_threshold = 75; // For clk/64, this should work for most frame rates.
  609. uint8_t ltc_buf[11]; // 11 so we can shift easily
  610. uint8_t ltc_buf2[11]; // 11 so we can shift easily
  611. uint8_t *rptr;
  612. uint8_t *wptr;
  613. volatile bool ltc_short_wait_flag = false;
  614. volatile bool ltc_frame_ready = false;
  615.  
  616. // Log some info about the LTC reader setup. Usually just alias to a usart send function.
  617.  
  618. void ltc_log(const char* str){
  619.   uart_send("LTC Reader: ");
  620.   uart_sendl(str);
  621. }
  622.  
  623. void ltc_init(){
  624.  
  625.   ltc_log("Set up...");
  626.  
  627.   // Signal: PD7 AIN1 neg - arduino digital 7, ATmega328 pin 13
  628.   // Signal ground: PD6 AINO pos - arduino digital 6, ATmega328 pin 12
  629.  
  630.   // Set up ports
  631.  
  632.   DDRD &= ~((1<<7) | (1<<6));  // Set PD6 and PD7 as inputs TODO: Break pin assigns out into settings, if they can be changed at all
  633.   PORTD &= ~((1<<7) | (1<<6)); // with pullup off
  634.  
  635.   // Set up ADC/AC hardware
  636.  
  637.   ADCSRA &= ~(1<<ADEN); // Disable the ADC
  638.   ADCSRB &= ~(1<<ACME); // Disable analog comparator input multiplexer so we always read AIN0 and AIN1
  639.   ADCSRB &= ~((1<<ADTS2) | (1<<ADTS1)); // Clear two MSB of ADTSn, which will  
  640.   ADCSRB |= 1<<ADTS0;                   // in concert with this select "analog comparator" in ADC status register B.
  641.   DIDR1 = (1<<AIN1D) | (1<AIN0D); // Disable the digital input buffer on the AINx pins to reduce current consumption
  642.   ACSR = (0<<ACIE) | (1<<ACIC); // Bits 3 and 2 - enable interrupt.
  643.                // Otherwise, most of what we want is zeroes:
  644.                // ACD (7) = Analog Comparator Disable
  645.                // ACBG (6) = use bandgap reference instead of positive input.
  646.                // ACO (5) Read-only comparator output state
  647.                // ACI (4) Interrupt flag. Can be cleared manually, so clear it here to avoid shenanigans.
  648.                // ACIS[1:0] Zeroed - comparator interrupt on output toggle.
  649.   //ACSR |= ((1<<ACIS1) | (1<<ACIS0));
  650.   ACSR &= ~((1<<ACIS1) | (0<<ACIS0));
  651.  
  652.   // Set up timer
  653.  
  654.   TCCR1A = 0x00; // Don't want any output compare pins toggling, nor any waveform generator functions
  655.   TCCR1B = 0x00; // Explicitly zero the register to avoid shenanigans
  656.   TCCR1B |= ((0<<ICNC1) | // Enable noise canceler. Requires four sequential identical samples to trip (operates on both anacomp and input capture events)
  657.              (1<<ICES1) | // Trip on rising edge first. This gets swapped a lot later.
  658.              (1<<CS10) | // Clock prescaler selection 12:10. 101 = clk/1024, 100 = /256, 011 = /64, 010 = /8, 0x1 = /1. 110 = ext clock on T1, falling edge. 111 = rising edge
  659.              (1<<CS11) |
  660.              (0<<CS12)
  661.              );
  662.   TIMSK1 = 0x00; // Explicitly zero the register to avoid shenanigans
  663.   TIMSK1 |= (1<<ICIE1); // Enable input capture interrupt, which is the one used by the AC.
  664.  
  665.   for(uint8_t i = 0; i < 11; i++){
  666.     ltc_buf[i] = ltc_buf2[i] = 0;
  667.   }
  668.  
  669.   wptr = ltc_buf;
  670.   rptr = ltc_buf2;
  671.  
  672. }
  673.  
  674. ISR(ANALOG_COMP_vect){ // Currently disabled; see line ACSR = (0<<ACIE) | (1<<ACIC); // above
  675.   uart_sendl("Foo");
  676.   /*TCNT1=0
  677.   if(ACSR & (1<<ACIS0)){ // We just saw a falling output edge
  678.     ACSR |= 1<<ACIS0;
  679.   } else { // We just saw a rising output edge
  680.     ACSR &= ~(1<<ACIS0);
  681.   } */
  682. }
  683.  
  684. volatile uint32_t ltc_frametime = 0;
  685. volatile uint32_t ltc_frametime_wkg = 0; // This is used to signal a frame decoded when it's nonzero.
  686. //uint8_t ltc_avgframes = 0;
  687. uint8_t lastTime = 0;
  688. //uint8_t ltc_transitions = 0;
  689. bool ltc_signal = false;
  690. //const uint8_t  TCCR_ICES1 =  (1 << ICES1); // IRC adds
  691.  
  692. ISR(TIMER1_CAPT_vect){
  693.  
  694.   //lastTime = ICR1; // Input capture register. Will have captured the counter value at the moment of the interrupt
  695.   ltc_frametime += ICR1; // Update the total time for this frame
  696.   TCNT1=0; // Zero the timer for this bitperiod
  697.  
  698.   // Flip looking for rising or falling edges
  699.  
  700.   /*if(TCCR1B & (1<<ICES1)){
  701.     TCCR1B &= ~(1<<ICES1);
  702.   } else {
  703.     TCCR1B |= (1<<ICES1);
  704.   }*/
  705.  
  706.   TCCR1B = TCCR1B == 67 ? 3 : 67; // Abbreviates the above
  707.   //TCCR1B ^= TCCR_ICES1; // IRC adds
  708.  
  709.   // Figure out whether this was a long or short bitperiod
  710.   // and if it was short, figure out if it's the second short
  711.   // one in a row.
  712.  
  713.   if(ICR1>ltc_bitperiod_threshold){
  714.     // It's a zero. Zero the last bit in the buffer.
  715.     wptr[9] &= ~(0x80);
  716.     //ltc_short_wait_flag = false; // Possibly prevents shenanigans
  717.   } else {
  718.     // It's possibly part of a 1
  719.     if(ltc_short_wait_flag){
  720.       // It's a 1
  721.       wptr[9] |= 0x80; // Set the last bit in the buffer.
  722.       ltc_short_wait_flag = false;
  723.     } else {
  724.       // It's presmably the beginning of a 1
  725.       ltc_short_wait_flag = true;
  726.       return;
  727.     }
  728.   }
  729.  
  730.   // Check to see if we've found a full frame
  731.  
  732.   if(wptr[8] == ltc_magic_number_A_rev && wptr[9] == ltc_magic_number_B_rev){
  733.  
  734.     if(!ltc_signal){
  735.       ltc_log("Detected signal.");
  736.       ltc_signal = true;
  737.     }
  738.    
  739.     ltc_frametime_wkg = ltc_frametime; // Set this nonzero to indicate a frame decoded.
  740.     ltc_frametime = 0;
  741.  
  742.     // Swap buffers
  743.    
  744.     if (rptr == ltc_buf){
  745.       rptr = ltc_buf2;
  746.       wptr = ltc_buf;
  747.     }else{
  748.       rptr = ltc_buf;
  749.       wptr = ltc_buf2;
  750.     }
  751.   }
  752.  
  753.   // Shuffle the buffer
  754.  
  755.   // TODO: Optimise with asm? Investigate srac instruction - shift right with carry
  756.  
  757.   for(uint8_t i = 0; i < 10; i++){ // Remember we made an extra byte on the end we don't need?
  758.     wptr[i] = (wptr[i] >> 1) | (wptr[i+1] << 7);
  759.   }
  760.  
  761. }
  762.  
  763. uint32_t ltc_timeavg = 0;
  764. uint8_t ltc_avgcount = 0;
  765. uint8_t ltc_maxavg = 32;
  766. uint16_t ltc_frametime_avg;
  767.  
  768. typedef enum ltc_framerate{
  769.   UNKNOWN,
  770.   R23976,
  771.   R24,
  772.   R25,
  773.   R2997,
  774.   R30
  775. };
  776.  
  777. const char* ltc_framerate_names[] = {
  778.   "Resolving...",
  779.   "23.976",
  780.   "24",
  781.   "25",
  782.   "29.970",
  783.   "30"  
  784. };
  785.  
  786. uint8_t ltc_framerate_maxframes[] = {
  787.   0, 23, 23, 24, 29, 29
  788. };
  789.  
  790.  
  791. ltc_framerate ltc_framerate_now = UNKNOWN;
  792. ltc_framerate ltc_framerate_then = UNKNOWN;
  793.  
  794. uint8_t ltc_hh = 0;
  795. uint8_t ltc_mm = 0;
  796. uint8_t ltc_ss = 0;
  797. uint8_t ltc_ff = 0;
  798. bool ltc_df = false;
  799. /*
  800. uint8_t ltc_prev_hh = 0;
  801. uint8_t ltc_prev_mm = 0;
  802. uint8_t ltc_prev_ss = 0;
  803. uint8_t ltc_prev_ff = 0;
  804. bool prev_ltc_df = false;
  805. */
  806. void ltc_decode_frame(){
  807.   /*ltc_prev_hh = ltc_hh;
  808.   ltc_prev_mm = ltc_mm;
  809.   ltc_prev_ss = ltc_ss;
  810.   ltc_prev_ff = ltc_ff;*/
  811.  
  812.   uint8_t nums[8];
  813.   nums[0] = rptr[7] & 0b00000011;
  814.   nums[1] = rptr[6] & 0b00001111;
  815.   nums[2] = rptr[5] & 0b00000111;
  816.   nums[3] = rptr[4] & 0b00001111;
  817.   nums[4] = (rptr[3] & 0b00000111);
  818.   nums[5] = (rptr[2] & 0b00001111);
  819.   nums[6] = (rptr[1] & 0b00000011);
  820.   nums[7] = (rptr[0] & 0b00001111);
  821.   uart_send(nums, 8);
  822.   uart_send("\r\n");
  823.   display_show(nums);
  824.  
  825.   /*
  826.   ltc_hh = (10*(rptr[7] & 0b00000011)) + (rptr[6] & 0b00001111); // Other bits in hrs tens are reserved and binary group flag
  827.   ltc_mm = (10*(rptr[5] & 0b00000111)) + (rptr[4] & 0b00001111); // Other bit in mins tens is binary group flag
  828.   ltc_ss = (10*(rptr[3] & 0b00000111)) + (rptr[2] & 0b00001111); // Other bit in secs tens is biphase mark correction bit
  829.   ltc_ff = (10*(rptr[1] & 0b00000011)) + (rptr[0] & 0b00001111); // Other bits in frames tens are drop frame and color frame flags
  830.   ltc_df = (rptr[1] & 0b00000100) == 4;
  831.   */
  832. }
  833.  
  834. // ******************************************
  835. //
  836. // 7-segment display
  837. //
  838. // ******************************************
  839. /*
  840.  * This was the version for the plugboard
  841. uint8_t display_font[] = {
  842. //  cdebafg dp
  843.   0b11111100,
  844.   0b10010000,
  845.   0b01111010,
  846.   0b11011010,
  847.   0b10010110,
  848.   0b11001110,
  849.   0b11101110,
  850.   0b10011000,
  851.   0b11111110,
  852.   0b11011110,
  853. };
  854. */
  855. uint8_t display_font[] = {
  856.  
  857. //  gfedcb.a
  858.   0b01111101, // 0
  859.   0b00001100, // 1
  860.   0b10110101, // 2
  861.   0b10011101, // 3
  862.   0b11001100, // 4
  863.   0b11011001, // 5
  864.   0b11111001, // 6
  865.   0b00001101, // 7
  866.   0b11111101, // 8
  867.   0b11011101, // 9
  868. };
  869.  
  870. // Where is the hardware connected?
  871.  
  872. #define SPI_DEVICE_DSPLY 1
  873. #define DSPLY_PORT PORTB
  874. #define DSPLY_PORT_DIR DDRB
  875. #define DSPLY_CS_PIN 0
  876. #define DSPLY_LATCH_PORT PORTD
  877. #define DSPLY_LATCH_PORT_DIR DDRD
  878. #define DSPLY_LATCH_PIN 5
  879.  
  880. void display_init(){
  881.  
  882.   DSPLY_LATCH_PORT_DIR |= (1 << DSPLY_LATCH_PIN);
  883.   DSPLY_LATCH_PORT &= ~(1 << DSPLY_LATCH_PIN);
  884.   display_test();
  885.  
  886. }
  887.  
  888. void display_latch(){
  889.   DSPLY_LATCH_PORT |= (1 << DSPLY_LATCH_PIN);
  890.   _delay_ms(1);
  891.   DSPLY_LATCH_PORT &= ~(1 << DSPLY_LATCH_PIN);
  892. }
  893.  
  894. void display_test(){
  895.   uint8_t eights[] = {8,8,8,8,8,8,8,8};
  896.   display_show(eights);
  897.   _delay_ms(500);
  898.   display_clear();
  899. }
  900.  
  901. void display_show(uint8_t nums[8]){
  902.   spi_select(SPI_DEVICE_DSPLY);
  903.   uint8_t i = 7;
  904.   do{
  905.     uint8_t dp = 0;
  906.     if(i==1 || i == 3 || i == 5) dp = 0b00000010;
  907.     spi_transact(display_font[nums[i]] | dp);
  908.   } while (i--);
  909.   display_latch();
  910.   spi_deselect();
  911. }
  912.  
  913. void display_clear(){
  914.   spi_select(SPI_DEVICE_DSPLY);
  915.   for(uint8_t i = 0; i < 8; i++){
  916.     spi_transact(0);
  917.   }
  918.   display_latch();
  919.   spi_deselect();
  920. }
  921.  
  922.  
  923. // ******************************************
  924. //
  925. // SPI stuff
  926. //
  927. // ******************************************
  928.  
  929. typedef struct{
  930.  
  931.   uint8_t pin;
  932.   volatile uint8_t *port;
  933.   volatile uint8_t *ddr;
  934.   bool activeHigh;
  935.  
  936. }spi_device;
  937.  
  938. // Declare SPI devices for this project:
  939. // Syntax: pin on port, port, active hi/low
  940. // Each SPI device also needs a uint8_t called something like SPI_DEVICE_WHATEVER identifying the order
  941. // in which it appears here.
  942.  
  943. // Where is the hardware connected?
  944.  
  945. spi_device spi_devices[] = {
  946.  {
  947.    .pin = NRF_CSN_PIN,
  948.    .port = &NRF_PORT,
  949.    .ddr = &NRF_PORT_DIR,
  950.    .activeHigh = false
  951.  },
  952.  {
  953.    .pin = DSPLY_CS_PIN,
  954.    .port = &DSPLY_PORT,
  955.    .ddr = &DSPLY_PORT_DIR,
  956.    .activeHigh = true
  957.  }
  958. };
  959.  
  960. uint8_t spi_currently_selected = 255;
  961.  
  962. void spi_init(){
  963.  
  964.   // Set /SS, MOSI and SCK as output
  965.   // /SS is PB2, MOSI is PB3, SCK is PB5
  966.   // NB most applications will also need at least a chip select set as output
  967.  
  968.   DDRB |= (1<<DDB5) | (1<<DDB3) | (1<<DDB2);
  969.  
  970.   // Set SPE (SPI Enable) and MSTR (use clock rate/16) of the SPCR register
  971.  
  972.   SPCR |= (1<<SPE) | (1<<MSTR) | (1<<SPR0);
  973.  
  974.   // Do not enable SPI interrupt, since we're only supporting master mode operation
  975.  
  976.   // Prepare chip select pins and ports for the required IO work
  977.  
  978.   for(uint8_t i = 0; i < sizeof(spi_devices) / sizeof(spi_device); i++){
  979.     spi_devices[i].pin = (1<<spi_devices[i].pin); // Convert it to a bitmask as that's how we'll always use it.
  980.     *spi_devices[i].ddr |= spi_devices[i].pin;
  981.   }
  982.  
  983. }
  984.  
  985. uint8_t spi_transact(uint8_t data){ // Single bytes
  986.  
  987.   SPDR = data;
  988.   while(!(SPSR & (1<<SPIF)));
  989.   return SPDR;
  990.  
  991. }
  992.  
  993. void spi_transact(uint8_t * data, uint8_t len, uint8_t* response){ // Multi bytes
  994.   for(uint8_t i = 0; i < len; i++){
  995.     response[i] = spi_transact(data[i]);
  996.   }
  997. }
  998.  
  999. void spi_select(uint8_t dev){
  1000.  
  1001.   if(spi_currently_selected != 255){
  1002.     uart_sendl("Glitch. Attempted to select SPI device when already selected.");
  1003.     return;
  1004.   }
  1005.  
  1006.   if(spi_devices[dev].activeHigh){
  1007.     *spi_devices[dev].port |= spi_devices[dev].pin;
  1008.   } else {
  1009.     *spi_devices[dev].port &= ~spi_devices[dev].pin;
  1010.   }
  1011.  
  1012.   spi_currently_selected = dev;
  1013.  
  1014. }
  1015.  
  1016. void spi_deselect(){
  1017.  
  1018.   if(spi_currently_selected == 255){
  1019.     uart_sendl("Glitch. Attempted to deselect SPI device when none selected.");
  1020.     return;
  1021.   }
  1022.    
  1023.   if(spi_devices[spi_currently_selected].activeHigh){
  1024.     *spi_devices[spi_currently_selected].port &= ~spi_devices[spi_currently_selected].pin;
  1025.   } else {
  1026.     *spi_devices[spi_currently_selected].port |= spi_devices[spi_currently_selected].pin;
  1027.   }
  1028.  
  1029.   spi_currently_selected = 255;
  1030.  
  1031. }
  1032.  
  1033. uint8_t ltc_expectedframe = 0;
  1034. uint8_t ltc_goodframes = 0;
  1035. bool ltc_codegood = false;
  1036.  
  1037. int main(void){
  1038.  
  1039.   uart_init();
  1040.   spi_init();
  1041.   nrf_init();
  1042.   sei();
  1043.   ltc_init();
  1044.  
  1045.   nrf_read_status();
  1046.  
  1047.  
  1048.   display_init();
  1049.  
  1050.   //return 0;
  1051.  
  1052.   while(1){
  1053.    
  1054.     if(ltc_frametime_wkg>0){ // Nonzero working frame time indicates a frame decoded
  1055.      
  1056.       // Get times and DF flag from decoded data
  1057.      
  1058.       ltc_decode_frame();
  1059.  
  1060.       // If we know what rate we're doing, it's possible to work out whether we have good code
  1061.  
  1062.       if(ltc_framerate_now != UNKNOWN){
  1063.        
  1064.         if(ltc_ff != ltc_expectedframe){
  1065.          
  1066.           // If this wasn't the expected frame, zero the good-frames counter and reset the rate to unknown, as we may have been wrong
  1067.          
  1068.           ltc_goodframes = 0;
  1069.           ltc_framerate_now = UNKNOWN;
  1070.          
  1071.         } else {
  1072.          
  1073.           // If this was the expected frame but we aren't yet confident that we have good code, increase the good-frames counter
  1074.          
  1075.           if(!ltc_codegood) ltc_goodframes++;
  1076.         }
  1077.        
  1078.  
  1079.         if(ltc_goodframes >= LTC_REQUIRED_FRAMES){
  1080.          
  1081.           // If we've had enough good frames, we now have good timecode. If we hadn't already decided that, flag it up.
  1082.  
  1083.           if(!ltc_codegood){
  1084.             ltc_log("Good timecode. ");
  1085.             ltc_codegood = true;
  1086.           }  
  1087.  
  1088.         } else {
  1089.          
  1090.           // If we haven't had enough good frames, but we already thought we had good timecode, declare that we now don't have good timecode.
  1091.          
  1092.           if(ltc_codegood){
  1093.             ltc_log("Bad timecode.");
  1094.             ltc_codegood = false;
  1095.             ltc_framerate_now = UNKNOWN;
  1096.             ltc_signal = false; // TODO: Really this should get zeroed after some time has passed without transitions
  1097.           }
  1098.         }
  1099.       }
  1100.      
  1101.      /*
  1102.       ltc_expectedframe = ltc_get_next_frame();
  1103.  
  1104.       ltc_timeavg += ltc_frametime_wkg;
  1105.       ltc_avgcount ++;
  1106.      
  1107.       if(ltc_avgcount > ltc_maxavg){
  1108.          ltc_frametime_avg = ltc_timeavg / ltc_maxavg;
  1109.          ltc_timeavg = 0;
  1110.          ltc_avgcount = 0;
  1111.       }
  1112. */
  1113.  
  1114. /*
  1115.       Notes - approx clk/64 periods per frame based on signal from Fostex FR-2TC board.
  1116.  
  1117.       23.976 - around 10708-10710 (Ideal: 10427.0833)
  1118.       24 - around 10697-10699 (Ideal: 10416.667)
  1119.       25 - 10267-10269 (Ideal: 10000)
  1120.       2997 - 8551-8554 (Ideal: 8341.667)
  1121.       30 - 8543-8547 (Ideal: 8333.33)
  1122.      
  1123.      
  1124.       23.976  10648 10652
  1125.       24      10637 10640
  1126.       25      10210 10211
  1127.       29.970  8493  8497
  1128.       30      8483  8486
  1129. */
  1130.      
  1131.       //  ((f_cpu/64)*1001)/30000
  1132.      
  1133.       // TODO: rates of 50, 5994 and 60 exist in recent versions of SMPTE-12M.
  1134.       /*
  1135.       ltc_framerate_now = UNKNOWN;
  1136.       if(ltc_frametime_avg > 10644){
  1137.         ltc_framerate_now = R23976;
  1138.       } else if(ltc_frametime_avg < 10644 && ltc_frametime_avg > 10635){
  1139.         ltc_framerate_now = R24;
  1140.       } else if (ltc_frametime_avg < 10220 && ltc_frametime_avg > 10200){ // can be fairly wide on this
  1141.         ltc_framerate_now = R25;
  1142.       } else if (ltc_frametime_avg < 8500 && ltc_frametime_avg > 8490){
  1143.         ltc_framerate_now = R2997;
  1144.       } else if (ltc_frametime_avg < 8490){
  1145.         ltc_framerate_now = R30;
  1146.       }*/
  1147.       /*
  1148.       if(ltc_framerate_then != ltc_framerate_now){
  1149.         uart_send("LTC Reader: Frame rate changed to ");
  1150.         uart_sendl(ltc_framerate_names[ltc_framerate_now]);
  1151.         ltc_framerate_then = ltc_framerate_now;
  1152.         ltc_codegood = false;
  1153.       }
  1154.      
  1155.       ltc_codegood = true;
  1156.  
  1157.       if(true){
  1158.         uart_send(ltc_ff);
  1159.         uart_send(" ");
  1160.         uart_send(ltc_frametime_avg);
  1161.         uart_send(" ");
  1162.         uart_send(ltc_framerate_names[ltc_framerate_now]);
  1163.         uart_send(" ");
  1164.         uart_sendl(ltc_df ? "DF" : "NDF");
  1165.       }
  1166.       */
  1167.       ltc_frametime_wkg = 0; // Must zero this after handling a frame.
  1168.      
  1169.     }
  1170.   }
  1171. }
  1172.  
  1173. uint8_t ltc_get_next_frame(){
  1174.   if(ltc_ff == ltc_framerate_maxframes[ltc_framerate_now]){
  1175.     if(ltc_df &&
  1176.       ltc_ss == 59 &&
  1177.       ltc_mm != 9 &&
  1178.       ltc_mm != 19 &&
  1179.       ltc_mm != 29 &&
  1180.       ltc_mm != 39 &&
  1181.       ltc_mm != 49 &&
  1182.       ltc_mm != 59    
  1183.     ){
  1184.       return 2;
  1185.     } else {
  1186.       return 0;
  1187.     }
  1188.   } else {
  1189.     return ltc_ff + 1;
  1190.   }
  1191. }
  1192.  
  1193. /*
  1194. void ltc_get_framerate_ui_name(ltc_framerate rate, char* name){
  1195.   switch(rate){
  1196.     case UNKNOWN:
  1197.       name = "Wait..";
  1198.     break;
  1199.     case R23976:
  1200.       name = "23.976";
  1201.     break;
  1202.     case R24:
  1203.       name = "24.000";
  1204.     break;
  1205.     case R25:
  1206.       name = "25.000";
  1207.     break;
  1208.     case R2997:
  1209.       name = "29.970";
  1210.     break;
  1211.     case R30:
  1212.       name = "30.000";
  1213.     break;
  1214.   }
  1215. }
  1216. */
  1217. // Prints out a load of status information about the nRF24L01 attached.
  1218.  
  1219. void nrf_read_status(){
  1220.  
  1221.   uint8_t gpreg; // General-purpose variable to hold registers we won't need twice
  1222.   uart_sendl("nRF24L01 configuration\r\n");
  1223.  
  1224.   uart_sendl("  Radio setup:");
  1225.  
  1226.   uart_send("    Freq: ");
  1227.   gpreg = nrf_getreg(RF_CH);
  1228.   int freq = gpreg + 2400;
  1229.   uart_send(freq);
  1230.   uart_send("MHz; ");
  1231.   uint8_t configRegister = nrf_getreg(CONFIG);
  1232.   gpreg = nrf_getreg(RF_SETUP);
  1233.   uart_send("; RF output: ");
  1234.   uart_send(18 - (((gpreg & 0x06) >> 1) * 6)); // 00 = -18, 01 = -12, 10 = 06, 11 = 0.
  1235.   uart_send("dBm; ");
  1236.   uart_send("Mode: ");
  1237.   uart_send(configRegister & (1 << PRIM_RX) ? "RX; " : "TX; ");
  1238.   uart_send("\r\n    TX addr: ");
  1239.   uint8_t txaddr[5];
  1240.   nrf_getreg(TX_ADDR, 5, txaddr);
  1241.   uart_send(txaddr, 5);
  1242.   uart_send("\r\n    RX addr P0: ");
  1243.   nrf_getreg(RX_ADDR_P0, 5, txaddr);
  1244.   uart_send(txaddr, 5);
  1245.   uart_send("\r\n    (XP) RF ambient >-64dBm: ");
  1246.   uart_send(nrf_getreg(RPD) & 0x1); // RPD will be 1 if there's >-64dBm of signal at this freq
  1247.   uart_send("; Radio power-up: ");
  1248.   uart_send(configRegister & 1<<PWR_UP ? 1 : 0);
  1249.   uart_send("; Bitrate: ");
  1250.   if(gpreg & 1 << RF_DR_LOW){
  1251.     uart_send("250Kbps");
  1252.   } else {
  1253.     if(gpreg & 1 << RF_DR_HIGH){
  1254.       uart_send("2Mbps");
  1255.     } else {
  1256.       uart_send("1Mbps");
  1257.     }
  1258.   }
  1259.   uart_send("; TX carrier?: ");
  1260.   uart_send(gpreg & 1 << CONT_WAVE ? 1 : 0);
  1261.   uart_sendl("");
  1262.  
  1263.  
  1264.   gpreg = nrf_getreg(OBSERVE_TX);
  1265.   uart_send("    Total lost pkts: ");
  1266.   uart_send((int)(gpreg >> 4));// Get the upper 4 bits, 7:4
  1267.   uart_send("; Retransmitted this pkt: ");
  1268.   uart_send((int)(gpreg & 0xF));// Get the lower 4 bits, 3:0
  1269.  
  1270.   uart_sendl("\r\n\r\n  Packet configuration:");
  1271.  
  1272.   uart_send("    Use CRC: ");
  1273.   uart_send(configRegister & 1<<PWR_UP ? 1 : 0);
  1274.   uart_send("; CRC len: ");
  1275.   uart_send(configRegister & 1 << CRCO ? "2 " : "1 ");
  1276.   uart_send("; IRQ masked? RX_DR ");
  1277.   uart_send(configRegister & 1<<MASK_RX_DR ? 1 : 0);
  1278.   uart_send("; TX_DS ");
  1279.   uart_send(configRegister & 1<<MASK_TX_DS ? 1 : 0);
  1280.   uart_send("; MAX_RT: ");
  1281.   uart_send(configRegister & 1<<MASK_MAX_RT ? 1 : 0);
  1282.   uart_sendl("");
  1283.  
  1284.   gpreg = nrf_getreg(SETUP_RETR);
  1285.   uart_send("    Retry delay: ");
  1286.   uart_send((int)(((gpreg >> 4)+1) * 250));// Get the upper 4 bits, 7:4 in nordic nomenclature; 250ms per code value
  1287.   uart_send("us; max retries: ");
  1288.   uart_send(gpreg & 0xF); // Get the lower 4 bits; this represents the 0-16 retry count directly.
  1289.   uart_send("; Addr len: ");
  1290.   uart_send(nrf_getreg(SETUP_AW) + 2);
  1291.   uart_send(" bytes; ");
  1292.  
  1293.   gpreg = nrf_getreg(FEATURE);
  1294.   uart_send("\r\n    Enable dyn payload len: ");
  1295.   uart_send(gpreg & 1<<EN_DPL ? 1 : 0);
  1296.   uart_send("; Enable acknowledge payload:  ");
  1297.   uart_send(gpreg & 1<<EN_ACK_PAY ? 1 : 0);
  1298.   uart_send("; Enable tx of no-ack pkts: ");
  1299.   uart_send(gpreg & 1<<EN_DYN_ACK ? 1 : 0);
  1300.  
  1301.   uart_sendl("\r\n");
  1302.  
  1303.   uart_sendl("  Current status:");
  1304.   gpreg = nrf_getreg(STATUS);
  1305.   uart_send("    RX Data Rdy: ");
  1306.   uart_send(gpreg & 1<<RX_DR ? 1 : 0);
  1307.   uart_send("; Pkt Ackn'd: ");
  1308.   uart_send(gpreg & 1<<TX_DS ? 1 : 0);
  1309.   uart_send("; TX fifo full: ");
  1310.   uart_send(gpreg & 1<<TX_FULL ? 1 : 0);
  1311.   uart_send("\r\n    Data avail on pipe: ");
  1312.     uint8_t rxPVal = (gpreg & 0xE)>>1;
  1313.   if(rxPVal > 6){
  1314.     uart_sendl("None");  
  1315.   } else {
  1316.     uart_sendl(rxPVal);
  1317.   }
  1318.  
  1319.   gpreg = nrf_getreg(FIFO_STATUS);
  1320.  
  1321.   uart_send("    Reuse TX payload: ");
  1322.   uart_send(gpreg & 1<<TX_REUSE ? 1 : 0);
  1323.   uart_send("; TX fifo full: ");
  1324.   uart_send(gpreg & 1<<FIFO_FULL ? 1 : 0);
  1325.   uart_send("; TX fifo empty: ");
  1326.   uart_send(gpreg & 1<<TX_EMPTY ? 1 : 0);
  1327.   uart_send("; RX fifo full: ");
  1328.   uart_send(gpreg & 1<<RX_FULL ? 1 : 0);
  1329.   uart_send("; RX fifo empty: ");
  1330.   uart_send(gpreg & 1<<RX_EMPTY ? 1 : 0);
  1331.   uart_sendl("");
  1332.  
  1333.   uint8_t enaa = nrf_getreg(EN_AA);
  1334.   uint8_t enrxaddr = nrf_getreg(EN_RXADDR);
  1335.   uint8_t enDynPlLen = nrf_getreg(DYNPD);
  1336.  
  1337.   uart_sendl("\r\n  Per-pipe configuration:\r\n\tRX_ADDR\tEN_AA\tERX\tDPL\tRX_PW");
  1338.  
  1339.   for(uint8_t i = 0; i < 6; i++){
  1340.     uart_send("    ");
  1341.     uart_send(i);
  1342.     uart_send(":\t");
  1343.     uart_send_hex(nrf_getreg(RX_ADDR_P0 + i));
  1344.     uart_send("\t");
  1345.     uart_send(enaa & 1<<i ? 1 : 0);
  1346.     uart_send("\t");
  1347.     uart_send(enrxaddr & 1<<i ? 1 : 0);
  1348.     uart_send("\t");
  1349.     uart_send(enDynPlLen & 1<<i ? 1 : 0);
  1350.     uart_send("\t");
  1351.     uart_sendl(nrf_getreg(RX_PW_P0 + i));
  1352.   }
  1353.   uart_sendl("\r\nEnd of nRF24L01 configuration\r\n");
  1354.  
  1355. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement