Advertisement
Guest User

Untitled

a guest
Sep 22nd, 2018
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 67.11 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. #define UART_BUFFER_LEN 150
  18.  
  19. void uart_init() {
  20.     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.
  21.     UCSR0B = (1<<RXEN0)|(1<<TXEN0); // Enable receive and transmit
  22.     UCSR0C = _BV(UCSZ01) | _BV(UCSZ00); // 8 data, 2 stop?
  23. }
  24.  
  25. void uart_putchar(char c) {
  26.     loop_until_bit_is_set(UCSR0A, UDRE0); /* Wait until data register empty. */
  27.     UDR0 = c;
  28. }
  29.  
  30. char uart_getchar(void) {
  31.     loop_until_bit_is_set(UCSR0A, RXC0); /* Wait until data exists. */
  32.     return UDR0;
  33. }
  34.  
  35. void uart_send_old(const char *txt){
  36.   uint8_t index = 0;
  37.   while(txt[index] != 0){
  38.    uart_putchar(txt[index]);
  39.    index++;
  40.   }
  41. }
  42.  
  43. volatile char uart_buffer[UART_BUFFER_LEN] = {0,};
  44. volatile uint8_t uart_buffer_next = 0;
  45. volatile uint8_t uart_buffer_len = 0;
  46. volatile uint8_t fill = 0; // FIXME: rename.
  47. bool uart_poller_started = false;
  48.  
  49. void uart_send(const char *txt){
  50.   uint8_t charIndex = 0;
  51.   if(!uart_poller_started){
  52.     uart_send_old(txt);
  53.     return;
  54.   }
  55.   while(txt[charIndex] != 0){
  56.    fill++;
  57.    if(fill>UART_BUFFER_LEN){
  58.     uart_send_old("UART buffer overflow.\r\n");
  59.     uart_buffer_len = 0;
  60.     uart_buffer_next = 0;
  61.     fill = 0;
  62.    }
  63.    uart_buffer[uart_buffer_len] = txt[charIndex];
  64.    uart_buffer_len++;
  65.    charIndex++;
  66.    if(uart_buffer_len==UART_BUFFER_LEN)uart_buffer_len = 0;
  67.   }
  68. }
  69.  
  70. void uart_async_send_poll(){
  71.   if(!uart_poller_started)uart_sendl("UART Send: Polling...");
  72.   uart_poller_started = true;
  73.   if(uart_buffer_next == uart_buffer_len) return; // Nothing to send
  74.   if(!(UCSR0A & (1<<UDRE0))) return; // Busy sending
  75.   fill--;
  76.   UDR0 = uart_buffer[uart_buffer_next]; // Send character
  77.   uart_buffer_next ++; // Increment the next character to send
  78.   if(uart_buffer_next==UART_BUFFER_LEN)uart_buffer_next=0;
  79.  
  80. }
  81.  
  82. void uart_send(int num){
  83.   char chars[7] = {0}; // Maximum length for decimal string representation of an an int is  7 chars, as in "-32767\0"
  84.   uart_int_to_decimal(num, chars);
  85.   //if(num<10) uart_send("0");
  86.   uart_send(chars);
  87. }
  88.  
  89. void uart_send(uint32_t num){
  90.   char chars[11] = {0}; // Maximum length for decimal string representation of an a uint32_t is 11 chars, as in "4294967296\0"
  91.   uart_int32_to_decimal(num, chars);
  92.   uart_send(chars);
  93. }
  94.  
  95. void uart_send_hex(uint8_t num){
  96.   char chars[3] = {0}; // Maximum length for hexadecimal string representation of an a uint8_t is 3 chars, as in "FF\0"
  97.   uart_int_to_hex(num, chars);
  98.   uart_send(chars);
  99. }
  100.  
  101. void uart_sendl(const char *txt){
  102.   uart_send(txt);
  103.   uart_send("\r\n");
  104. }
  105.  
  106. void uart_sendl(int num){
  107.   uart_send(num);
  108.   uart_send("\r\n");
  109. }
  110.  
  111. void uart_sendl(uint32_t num){
  112.   uart_send(num);
  113.   uart_send("\r\n");
  114. }
  115.  
  116. void uart_send(uint8_t* array, uint8_t len){
  117.   char txt[UART_MAX_ECHOABLE_ARRAY_LEN] = {0};
  118.   uart_array_to_hex(array, len, txt);
  119.   uart_send(txt);
  120. }
  121.  
  122. void uart_array_to_hex(uint8_t* array, uint8_t len, char *txt){
  123.   for(uint8_t i = 0; i < len; i++){
  124.      char arrayMember[3] = {0}; // Max len
  125.      uart_int_to_hex(array[i], arrayMember);
  126.      uint8_t memberIdx = 0;
  127.      //int foo = 0;
  128.      while(arrayMember[memberIdx] != 0){
  129.        txt[0] = arrayMember[memberIdx];
  130.        memberIdx ++;
  131.        txt++;
  132.        //foo++;
  133.      }
  134.      /*if(i < len-1){
  135.        txt[0] = ',';
  136.        txt++;
  137.      }*/
  138.   }
  139. };
  140.  
  141. void uart_int_to_decimal(int value, char *ptr){
  142.   int temp;
  143.   if(value==0){  
  144.     *ptr++='0';
  145.     *ptr++='0';
  146.     *ptr='\0';
  147.     return;
  148.   }
  149.   if(value<0){
  150.     value*=(-1);    
  151.     *ptr++='-';
  152.   }
  153.  
  154.   if(value<10){
  155.     *ptr++='0'; // This works fine and ensures we get "08" not "8"
  156.   }
  157.  
  158.   for(temp=value;temp>0;temp/=10,ptr++);
  159.   *ptr='\0';
  160.   for(temp=value;temp>0;temp/=10){
  161.     *--ptr=temp%10+'0';
  162.   }
  163. }
  164.  
  165. void uart_int32_to_decimal(uint32_t value, char *ptr){
  166.   uint32_t temp;
  167.   if(value==0){  
  168.     *ptr++='0';
  169.     *ptr='\0';
  170.     return;
  171.   }
  172.   if(value<0){
  173.     value*=(-1);    
  174.     *ptr++='!';
  175.   }
  176.  
  177.   for(temp=value;temp>0;temp/=10,ptr++);
  178.   *ptr='\0';
  179.   for(temp=value;temp>0;temp/=10){
  180.     *--ptr=temp%10+'0';
  181.   }
  182. }
  183.  
  184. char uart_hexchars[]="0123456789ABCDEF";
  185. void uart_int_to_hex(uint8_t value, char *ptr){
  186.   ptr[0] = (uart_hexchars[(value>>4)&0xf]);
  187.   ptr[1] = (uart_hexchars[value&0xf]);
  188. }
  189.  
  190. // ******************************************
  191. //
  192. // Nordic Semiconductor nRF24L01+
  193. //
  194. // ******************************************
  195.  
  196. uint8_t nrf_master_address[5] = {0xE1,0xE2,0xE3,0xE4,0xE5};
  197. uint8_t nrf_slave_address[5] = {0xD1,0xD2,0xD3,0xD4,0xD5};
  198.  
  199. // CE is green; D9 = PB5
  200. // CSN is D10 = PB2
  201.  
  202. // Where is the hardware connected?
  203.  
  204. #define SPI_DEVICE_NRF 0 // See further info about this spi device under "spi stuff" below
  205. #define NRF_PORT PORTB
  206. #define NRF_PORT_DIR DDRB
  207. #define NRF_CSN_PIN 2
  208. #define NRF_CE_PIN 1
  209. #define NRF_USE_INTX false  // Use INT0 or INT1 to signal nRF activity. Generally this will be used on receive.
  210. #define NRF_WHICH_INT 0 // INT0 or INT1. You need to define ISR (INTx_vect){...} as appropriate.
  211.  
  212. // Options
  213.  
  214. #define NRF_DEFAULT_frEQUENCY 2478 // 2478 is above wifi and legal in the USA.
  215. #define NRF_DEFAULT_PAYLOAD_WIDTH 3 // in bytes. Used to set RX pipe width.
  216. #define NRF_ROLE_TX true // This is default
  217. #define NRF_ROLE_RX false
  218. #define NRF_FCC_COMPLIANT true // Limits frequencies to < 2.482GHz for US regulatory compliance
  219. #define NRF_DEFAULT_RETRIES 3 // Up to 15
  220. #define NRF_DEFAULT_RETRY_DELAY 0 // Sets retry delay according to the formula (n+1)*250uS up to 15=4000us.
  221. #define NRF_USE_AUTO_ACKNOWLEDGE true
  222. #define NRF_TEST_ROLE NRF_ROLE_TX
  223.  
  224. // Some nRF24L01 resources suggest a 10us delay after some ops, particularly sending SPI commands
  225. // and before sending data associated with that command. Often this seems unnecessary so it's
  226. // selectable here.
  227.  
  228. #define USE_NRF_DELAY 0
  229. #if USE_NRF_DELAY == 1
  230.   #define NRF_COURTESY_DELAY _delay_us(10);
  231. #else
  232.   #define NRF_COURTESY_DELAY
  233. #endif
  234.  
  235. // Caution: these extra defines, not in nRF24L01.h, represent
  236. // features which are possibly nRF24L01+ only.
  237.  
  238. #define FEATURE 0x1D // This is a register
  239. #define EN_DPL 0x02  // Enable dynamic payload
  240. #define EN_ACK_PAY 0x01
  241. #define EN_DYN_ACK 0x00
  242. #define CONT_WAVE 0x07
  243. #define RF_DR_LOW 0x05
  244. #define RF_DR_HIGH 0x03
  245. #define RPD 0x00
  246. #define W_TX_PAYLOAD_NOACK 0xB0 // Command which was missing from the header
  247.  
  248. // Select and deselect the nRF chip. NB that CS on the nRF is active-low.
  249. // This all now handled with spi_select etc.
  250. // FIXME: spi_select does not support NRF_COURTESY_DELAY, though that seems unnecessary.
  251. // Be careful in case this causes future problems.
  252.  
  253. /*
  254. void nrf_select(){
  255.   spi_select(SPI_DEVICE_NRF);
  256.   //uart_sendl(NRF_PORT);
  257.   //NRF_PORT &= ~(1<<NRF_CSN_PIN);
  258.   NRF_COURTESY_DELAY
  259. }
  260.  
  261. void //nrf_deselect(){
  262.   spi_deselect();
  263.   //NRF_PORT |= (1<<NRF_CSN_PIN);
  264.   NRF_COURTESY_DELAY
  265. }
  266. */
  267. // Enable and disable the nRF chip. This is active-high.
  268.  
  269. void nrf_enable(){
  270.   NRF_PORT |= (1<<NRF_CE_PIN);
  271.   NRF_COURTESY_DELAY
  272. }
  273.  
  274. void nrf_disable(){
  275.   NRF_PORT &= ~(1<<NRF_CE_PIN);
  276.   NRF_COURTESY_DELAY
  277. }
  278.  
  279. // Get a single-byte registerM
  280.  
  281. uint8_t nrf_getreg(uint8_t reg){
  282.   //nrf_select();
  283.   spi_select(SPI_DEVICE_NRF);
  284.   reg = spi_transact(reg); // Should really be R_REGISTER | reg, but R_REGISTER is 0.
  285.   NRF_COURTESY_DELAY
  286.   uint8_t val = spi_transact(0b00000000); // Dummy byte so the SPI sends zeroes
  287.   NRF_COURTESY_DELAY
  288.   //nrf_deselect();
  289.   spi_deselect();
  290.   return val;
  291. }
  292.  
  293. // Get a multi-byte register
  294.  
  295. void nrf_getreg(uint8_t reg, uint8_t len, uint8_t* val){
  296.   int i;
  297.   NRF_COURTESY_DELAY
  298.   //nrf_select();
  299.   spi_select(SPI_DEVICE_NRF);
  300.   reg = spi_transact(reg); // Should really be R_REGISTER | reg, but R_REGISTER is 0.
  301.   NRF_COURTESY_DELAY
  302.   for(i = 0; i < len; i++){
  303.     val[i] = spi_transact(0x00); // Dummy byte so the SPI sends zeroes
  304.     NRF_COURTESY_DELAY
  305.   }
  306.   //nrf_deselect();
  307.   spi_deselect();
  308. }
  309.  
  310. // Set a single-byte register
  311.  
  312. void nrf_setreg(uint8_t reg, uint8_t data){
  313.  
  314.   //nrf_select();
  315.   spi_select(SPI_DEVICE_NRF);
  316.   reg = spi_transact(W_REGISTER | reg); // Set which register to write
  317.   NRF_COURTESY_DELAY
  318.   reg = spi_transact(data); // Write data
  319.   NRF_COURTESY_DELAY
  320.   //nrf_deselect();
  321.   spi_deselect();
  322. }
  323.  
  324. // Set a multi-byte register
  325.  
  326. void nrf_setreg(uint8_t reg, uint8_t *data, uint8_t len){
  327.  
  328.   //nrf_select();
  329.   spi_select(SPI_DEVICE_NRF);
  330.   reg = spi_transact(W_REGISTER | reg); // Set which register to write
  331.   NRF_COURTESY_DELAY
  332.   for(uint8_t i = 0; i < len; i++){
  333.     reg = spi_transact(data[i]); // Write data
  334.     NRF_COURTESY_DELAY
  335.   }
  336.   //nrf_deselect();
  337.   spi_deselect();
  338.  
  339. }
  340.  
  341. // Powerup and powerdown the nRF chip.
  342. // It takes 1.5ms with internel osc, or 150us with external osc (which we think
  343. // we have) to get from powerdown to standby, so we don't want to do that too
  344. // often - consider leaving powered up.
  345.  
  346. void nrf_powerup(){
  347.   uint8_t cfreg = nrf_getreg(CONFIG);
  348.   cfreg = cfreg | (1<<PWR_UP);
  349.   nrf_setreg(CONFIG, cfreg);
  350.   _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.
  351. }
  352.  
  353. void nrf_powerdown(){
  354.   uint8_t cfreg = nrf_getreg(CONFIG);
  355.   cfreg &= ~(1<<PWR_UP);
  356.   nrf_setreg(CONFIG, cfreg);
  357.   _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.
  358. }
  359.  
  360. // Send the payload to the nRF. The command W_TX_PAYLOAD is followed by the bytes to be sent.
  361. // The delays are possibly unnecessary, or at least other than after setting CSN
  362.  
  363. void nrf_tx_immediate(uint8_t* payload, uint8_t len){
  364.  
  365.   //nrf_select();
  366.   spi_select(SPI_DEVICE_NRF);
  367.   if(NRF_USE_AUTO_ACKNOWLEDGE){
  368.     spi_transact(W_TX_PAYLOAD);
  369.   } else {
  370.     spi_transact(W_TX_PAYLOAD_NOACK);
  371.   }
  372.   NRF_COURTESY_DELAY
  373.   for(uint8_t i = 0; i < len; i++){
  374.     spi_transact(payload[i]);
  375.     NRF_COURTESY_DELAY
  376.   }
  377.   //nrf_deselect();
  378.   spi_deselect();
  379.  
  380.   // Pulse CE to actually transmit the data
  381.      
  382.   //nrf_select();
  383.   //NRF_COURTESY_DELAY // In some implementations we needed a 10 millisecond (millisecond!) delay here, but it seems OK without.
  384.   nrf_enable();
  385.   _delay_us(15); // This actually is required per the datasheet; apparently minimum CE high is 10us.
  386.   nrf_disable();
  387.   //NRF_COURTESY_DELAY
  388.   ////nrf_deselect();
  389.   _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.
  390.                    // Possibly this is due to PLL settling delay?
  391.                    // Anyway, assuming we're asynchronously sending it won't matter and we can probably take this out
  392.                    
  393.   // Hard reset all the IRQ flags. This appears to be essential.
  394.  
  395.   nrf_clear_irqs();
  396.  
  397. }
  398. // Read received data
  399.  
  400. // This reads everything from the three buffers on the nRF into these three arrays.
  401. // Usually, just ensure we get each one as it comes in; if nrf_getata() != 0, there's
  402. // at least something in nrf_received[0].
  403.  
  404. // Don't call this unless you're happy to have all of nrf_received overwritten
  405.  
  406. uint8_t nrf_received[3][NRF_DEFAULT_PAYLOAD_WIDTH];
  407.  
  408. bool nrf_pendingPkts = false;
  409.  
  410. uint8_t nrf_pollfordata(){
  411.  
  412.   uint8_t msgcount = 0;
  413.  
  414.   while(~nrf_getreg(STATUS) & RX_DR){
  415.     //nrf_select();
  416.     spi_select(SPI_DEVICE_NRF);
  417.     spi_transact(R_RX_PAYLOAD);
  418.     NRF_COURTESY_DELAY
  419.     for(uint8_t i = 0; i < NRF_DEFAULT_PAYLOAD_WIDTH; i++){
  420.       nrf_received[msgcount][i] = spi_transact(0x00);
  421.     }
  422.     /*uart_send("Receive:");
  423.     uart_send(nrf_received[msgcount],NRF_DEFAULT_PAYLOAD_WIDTH);
  424.     uart_sendl("");*/
  425.     msgcount++;
  426.     //nrf_deselect();
  427.     spi_deselect();
  428.   }
  429.   nrf_pendingPkts = false;
  430.   nrf_clear_irqs();
  431.   return msgcount;
  432.  
  433. }
  434.  
  435. // Clear any set IRQ-type-indicating flags. Active low!
  436.  
  437. void nrf_clear_irqs(){
  438.  
  439.   /*
  440.   // RX_DR "received data ready" there is something to receive
  441.   // TX_DS "transmit data sent" (dependent on successful acknowledgement if selected)
  442.   // MAX_RT "maximum number of retries" has been reached.
  443.  
  444.   uint8_t statusReg = nrf_getreg(STATUS);
  445.   statusReg |= (1<<RX_DR | 1<<TX_DS | 1<<MAX_RT);
  446.   nrf_setreg(STATUS, statusReg);
  447.  
  448.   */
  449.  
  450.   /*
  451.    
  452.   // Fastest possible fully-inlined IRQ reset
  453.  
  454.   NRF_PORT &= ~(1<<NRF_CSN_PIN);    // Select nRF chip
  455.   SPDR = W_REGISTER | STATUS;
  456.   while(!(SPSR & (1<<SPIF)));
  457.   // Set all IRQ flags inactive-high
  458.   SPDR = 0x70; // Flag high all the writable bits in the register
  459.   while(!(SPSR & (1<<SPIF)));
  460.   NRF_PORT |= (1<<NRF_CSN_PIN);
  461.  
  462.   */
  463.  
  464.   // Because the only writable bits in STATUS are the three IRQs, and because their value ORs to 0x70
  465.   // this basically boils down to:
  466.  
  467.   nrf_setreg(STATUS, 0x70);
  468.  
  469. }
  470.  
  471. // Flush any leftover stuff in the transmit buffers.
  472.  
  473. void nrf_flush_tx(){
  474.   //nrf_select();
  475.   spi_select(SPI_DEVICE_NRF);
  476.   spi_transact(FLUSH_TX); // FLUSH_TX is a command not a register so it gets sent directly
  477.   NRF_COURTESY_DELAY
  478.   //nrf_deselect();
  479.   spi_deselect();
  480. }
  481.  
  482. // Flush any leftover stuff in the receive buffers.
  483.  
  484. void nrf_flush_rx(){
  485.   //nrf_select();
  486.   spi_select(SPI_DEVICE_NRF);
  487.   spi_transact(FLUSH_RX); // FLUSH_RX is a command not a register so it gets sent directly
  488.   NRF_COURTESY_DELAY
  489.   //nrf_deselect();
  490.   spi_deselect();
  491. }
  492.  
  493. // Be what the datasheet calls a PTX or PRX (primarily transmitter or receiver)
  494.  
  495. void nrf_setrole(bool isTx){
  496.  
  497.   uint8_t cfreg = nrf_getreg(CONFIG);
  498.   if(isTx){
  499.     cfreg &= ~(1<<PRIM_RX); // Be a transmitter
  500.   } else {
  501.     cfreg |= (1<<PRIM_RX);  // Be a receiver
  502.   }
  503.   nrf_setreg(CONFIG, cfreg);
  504.  
  505. }
  506.  
  507. // Set radio freqency. The hardware will do 125 channels, which must be 2+MHz apart at 2Mbps
  508. // Not all channels are legal everywhere.
  509.  
  510. bool nrf_setfreq(int freq){
  511.   if(freq < 2400 || freq > 2525){
  512.     nrf_err("Requested frequency not available");
  513.     return false;
  514.   }
  515.   if(NRF_FCC_COMPLIANT && freq > 2482){
  516.     nrf_err("Cannot set frequency over 2.482GHz with bandwidth <=2MHz in FCC controlled locale");
  517.     return false;
  518.   }
  519.   nrf_setreg(RF_CH, NRF_DEFAULT_frEQUENCY - 2400);
  520.   return true;
  521. }
  522.  
  523. // Set retry count and delay. Not really in use at the moment.
  524. // Args: retries, number of retries <16
  525. //       dly, delay according to (dly + 1) * 250us, for a maximum of 15=4000us
  526.  
  527. void nrf_setretries(uint8_t retries, uint8_t dly){
  528.   nrf_setreg(SETUP_RETR, retries | (dly << ARD)); // ARD is 4, to get the upper 4 bytes.  
  529. }
  530.  
  531. // Set the width of the receive pipe's payload.
  532. // This sets all the pipes, though we really only care about pipe 0 since it's used for auto-ack
  533. // This implementation of the nRF24L01 doesn't deal with multiple pipe operation.
  534.  
  535. void nrf_set_rx_payload_width(uint8_t width){
  536.   for(uint8_t i = 0; i < 6; i++){
  537.     nrf_setreg(RX_PW_P0 + i, width); // Register addresses are sequential, so we can add the incrementing variable
  538.   }
  539. }
  540.  
  541. // Set whether to use auto-acknowledgement
  542.  
  543. void nrf_set_use_auto_ack(bool autoAck){
  544.   if(autoAck){
  545.     nrf_setreg(EN_AA, ENAA_P5 | ENAA_P4 | ENAA_P3 | ENAA_P2 | ENAA_P1 | ENAA_P0);
  546.   } else {
  547.     nrf_setreg(EN_AA,0x00);
  548.   }
  549.  
  550.   // W_TX_PAYLOAD_NOACK command is always enabled in init();
  551.  
  552. }
  553.  
  554. // Log some info about the nRF24L01 setup. Usually just alias to a usart send function.
  555.  
  556. void nrf_log(const char* str){
  557.   uart_sendl(str);
  558. }
  559.  
  560. // Send an error message. Really just adds a prefix. Again, alias to a usart send function.
  561.  
  562. void nrf_err(const char* str){
  563.   uart_send("NRF24L01: Error: ");
  564.   uart_sendl(str);
  565. }
  566.  
  567. // Example ISR for packet arrival. All this does (with the uart_sends commented
  568. // out) is set a flag, but critical timing states could also be stored here.
  569. // Uses nrf_pendingPkts bool to signal stuff available
  570. // NB change defines to point the code to the right interrupt.
  571.  
  572. // FIXME: Make sure this isn't actually active so as not to screw up timecode timing.
  573. /*
  574. ISR(INT0_vect) {
  575.   nrf_pendingPkts = true;
  576. }
  577. */
  578. ISR(BADISR_vect){
  579.  uart_sendl("Error in ISR setup.");
  580. }
  581.  
  582. void nrf_disable_interrupts(bool receivedData, bool transmitComplete, bool transmitFailed){
  583.  
  584.   uint8_t val = nrf_getreg(CONFIG);
  585.  
  586.   if(receivedData){
  587.     val |= (1<<MASK_RX_DR);
  588.   } else {
  589.     val &= ~(1<<MASK_RX_DR);    
  590.   }
  591.  
  592.   if(transmitComplete){
  593.     val |= (1<<MASK_TX_DS);
  594.   } else {
  595.     val &= ~(1<<MASK_TX_DS);    
  596.   }
  597.  
  598.   if(transmitFailed){
  599.     val |= (1<<MASK_MAX_RT);
  600.   } else {
  601.     val &= ~(1<<MASK_MAX_RT);    
  602.   }
  603.  
  604.   nrf_setreg(CONFIG, val);
  605.  
  606. }
  607.  
  608. // Set up the nRF chip as from cold start.
  609. // This will clear everything and leave the chip in transmit mode but powered down, deselected and disabled.
  610. // It may take a few milliseconds to run, if the nRF chip needs a long timeout to reach standby.
  611.  
  612. void nrf_init(){
  613.  
  614.   // Set CE and CSN pins to be outputs
  615.   // CE is green wire, arduino pin D9/PB1
  616.   // CSN pin is blue wire, arduino pin D10/PB2, but is now dealt with by the SPI stuff
  617.  
  618.   //NRF_PORT_DIR |= (1<<NRF_CE_PIN) | (1<NRF_CSN_PIN);
  619.   NRF_PORT_DIR |= (1<NRF_CSN_PIN);
  620.  
  621.   // Set up RX interrupts using INTx pins
  622.   // NB - this is set up for the ATmega328. 168 is possibly identical.
  623.  
  624.   if(NRF_USE_INTX){
  625.     if(NRF_WHICH_INT == 0){
  626.       DDRD &= ~(1 << DDD2);      // Make the relevant pin an input
  627.       EICRA |= (1 << ISC01);     // Trigger on falling edges only.
  628.       EIMSK |= (1 << INT0);      // Turns on interrupts for that pin
  629.     } else {
  630.       DDRD &= ~(1 << DDD3);      // Make the relevant pin an input
  631.       EICRA |= (1 << ISC11);     // Trigger on falling edges only.
  632.       EIMSK |= (1 << INT1);      // Turns on interrupts for that pin
  633.     }
  634.     //sei(); // TODO FIXME: Dangerous!
  635.   }
  636.  
  637.   //nrf_deselect();
  638.   spi_deselect(); // CSN high
  639.   nrf_disable(); // CE low
  640.  
  641.   // Set up nRF24L01 chip.
  642.  
  643.   nrf_powerdown();
  644.   nrf_setrole(NRF_ROLE_TX);
  645.   nrf_setfreq(NRF_DEFAULT_frEQUENCY);
  646.   nrf_setretries(NRF_DEFAULT_RETRIES, NRF_DEFAULT_RETRY_DELAY); // Number of retries <16; Delay (n+1)*250us, max 15=4000us
  647.   nrf_set_rx_payload_width(NRF_DEFAULT_PAYLOAD_WIDTH);
  648.   nrf_flush_tx();
  649.   nrf_flush_rx();
  650.   nrf_clear_irqs();
  651.   nrf_disable_interrupts(false, false, false); // Don't disable any interrupts (probably get modified later anyway)
  652.  
  653.   // Enable sending packets without auto acknowledgement (Always enable this,
  654.   // just don't actually use W_TX_PAYLOAD_NOACK unless we're asked to.)
  655.  
  656.   uint8_t featureReg = nrf_getreg(FEATURE);
  657.   featureReg |= (1 << EN_DYN_ACK); // This equates to 0x01, since EN_DYN_ACK == 0.
  658.   nrf_setreg(FEATURE, featureReg);
  659.  
  660.   // Addresses
  661.   // Set P0 so that basic auto-ack will work, but we aren't really supporting any other pipes in this simple framework
  662.  
  663.   nrf_setreg(TX_ADDR, nrf_master_address, 5); // Set transmission address
  664.   nrf_setreg(RX_ADDR_P0, nrf_master_address, 5); // Pipe-0 receive addr should equal transmission address for automatic acknowledgement
  665.  
  666.   // Finished setup. Send some debug.
  667.  
  668.   //nrf_log("nRF24L01: Post-reset. Status now:");
  669.   //nrf_read_status(); // Reads a bunch of registers and sends out over uart in a sort of human readable format.
  670.  
  671. }
  672.  
  673. // ******************************************
  674. //
  675. // 7-segment display
  676. //
  677. // ******************************************
  678.  
  679. const uint8_t PROGMEM display_alpha[] = {
  680.  
  681. //  gfedcb.a
  682.  
  683.   0b01111101, // 48 0
  684.   0b00001100, // 49 1
  685.   0b10110101, // 50 2
  686.   0b10011101, // 51 3
  687.   0b11001100, // 52 4
  688.   0b11011001, // 53 5
  689.   0b11111001, // 54 6
  690.   0b00001101, // 55 7
  691.   0b11111101, // 56 8
  692.   0b11011101, // 57 9
  693.  
  694.   // Pad the table for a few chars we're not handling
  695.   // Costs us a few bytes of flash, but makes the code cleaner
  696.  
  697.   0, // :
  698.   0, // ;
  699.   0, // <
  700.   0, // =
  701.   0, // >
  702.   0, // ?
  703.   0, // @
  704.  
  705.   0b11101101, // 65 A
  706.   0b11111000, // 66 b
  707.   0b01110001, // 67 C
  708.   0b10111100, // 68 d
  709.   0b11110001, // 69 E
  710.   0b11100001, // 70 F
  711.   0b01111001, // 71 G
  712.   0b11101000, // 72 h (we use a lowercase h to differentiate it from K/X)
  713.  
  714.   0b01100000, // 73 I
  715.   0b00011100, // 74 J
  716.   0b11101100, // 75 K (may be confused with X or H)
  717.   0b01110000, // 76 L
  718.   0b00101001, // 77 M (not really doable, implemented as segs A, C and E, inverted W)
  719.   0b01101101, // 78 N
  720.   0b01111101, // 79 O
  721.   0b11100101, // 80 P
  722.  
  723.   0b11001101, // 81 q (possibly confusable with the 9 produced by some display drivers, but this number font illuminates segment D as well)
  724.   0b10100000, // 82 r
  725.   0b11011001, // 83 S (may be confused with number 5)
  726.   0b11100000, // 84 t (not that great)
  727.   0b01111100, // 85 U (may be confused with V)
  728.   0b01111100, // 86 V (may be confused with U)
  729.   0b01010100, // 87 W (not really doable, implemented as segs B, D and F, inverted M)
  730.   0b11101100, // 88 X (may be confused with K or H)
  731.  
  732.   0b11011100, // 89 Y
  733.   0b10110101, // 90 Z (may be confused with number 2)
  734.  
  735. };
  736.  
  737. // Where is the hardware connected?
  738.  
  739. #define SPI_DEVICE_DSPLY 1
  740. #define DSPLY_PORT PORTB
  741. #define DSPLY_PORT_DIR DDRB
  742. #define DSPLY_CS_PIN 0
  743. #define DSPLY_LATCH_PORT PORTD
  744. #define DSPLY_LATCH_PORT_DIR DDRD
  745. #define DSPLY_LATCH_PIN 4
  746.  
  747. void display_init(){
  748.  
  749.   DSPLY_LATCH_PORT_DIR |= (1 << DSPLY_LATCH_PIN);
  750.   DSPLY_LATCH_PORT &= ~(1 << DSPLY_LATCH_PIN);
  751.   display_test();
  752.  
  753. }
  754.  
  755. void display_latch(){
  756.   DSPLY_LATCH_PORT |= (1 << DSPLY_LATCH_PIN);
  757.   //_delay_ms(1);
  758.   DSPLY_LATCH_PORT &= ~(1 << DSPLY_LATCH_PIN);
  759. }
  760.  
  761. void display_test(){
  762.   char eights[] = "88888888";
  763.   display_show(eights);
  764.   _delay_ms(500);
  765.   display_clear();
  766. }
  767.  
  768. void display_show(const char *txt){
  769.   display_load_text(txt);
  770.  
  771.   display_latch();
  772. }
  773.  
  774. void display_load_text(const char *txt){
  775.   spi_select(SPI_DEVICE_DSPLY);
  776.   uint8_t i = 7;
  777.   do{
  778.     //uart_send("chr$: ");
  779.     //uart_sendl(i);
  780.  
  781.     if(txt[i] >= '0' && txt[i] <= 'Z'){ // 0 = char 48
  782.       spi_transact(pgm_read_byte_near(display_alpha + (txt[i] - '0')));
  783.     } else {
  784.       spi_transact(0); // Ensures that space, and anything not otherwise handled, becomes a space.
  785.     }
  786.   } while (i--);
  787.   spi_deselect();
  788. }
  789.  
  790. void display_load_raw(uint8_t * displayData){
  791.   spi_select(SPI_DEVICE_DSPLY);
  792.   uint8_t i = 7;
  793.   do{
  794.     spi_transact(displayData[i]);
  795.   } while (i--);
  796.   spi_deselect();
  797. }
  798.  
  799. void display_clear(){
  800.   spi_select(SPI_DEVICE_DSPLY);
  801.   for(uint8_t i = 0; i < 8; i++){
  802.     spi_transact(0);
  803.   }
  804.   display_latch();
  805.   spi_deselect();
  806. }
  807.  
  808. // ******************************************
  809. //
  810. // SMPTE-12M Timecode
  811. //
  812. // ******************************************
  813.  
  814. typedef enum {
  815.   UNKNOWN,
  816.   R23976,
  817.   R24,
  818.   R25,
  819.   R2997,
  820.   R30,
  821.   R5994,
  822.   R50,
  823.   R60
  824. } smpte_framerate;
  825.  
  826. const char* smpte_framerate_names[] = {
  827.   "Resolving...",
  828.   "23.976",
  829.   "24",
  830.   "25",
  831.   "29.970",
  832.   "30",
  833.   "50",
  834.   "59.940",
  835.   "60"
  836. };
  837.  
  838. /*
  839.  * struct _Object { int (*methodptr)(...); }
  840.  * int myimpl(...) {;}  o.methodptr=&myimpl;
  841.  * https://en.cppreference.com/w/c/variadic
  842.  * https://stackoverflow.com/questions/840501/how-do-function-pointers-in-c-work
  843.  */
  844.  
  845. struct smpte_timecode{
  846.   uint8_t hours;
  847.   uint8_t mins;
  848.   uint8_t secs;
  849.   uint8_t frames;
  850.   bool dropframe;
  851.   uint8_t ubits[4];
  852.   bool fwd;
  853.   smpte_framerate framerate;
  854.   uint32_t frametime;
  855. };
  856.  
  857. uint8_t smpte_framerate_maxframes[] = {
  858.   0, 23, 23, 24, 29, 29, 49, 59, 59
  859. };
  860.  
  861. bool smpte_compare(struct smpte_timecode *code1, struct smpte_timecode *code2){ // FIXME: Needs "struct" due to Arduino strangeness
  862.   return
  863.     code1->hours == code2->hours &&
  864.     code1->mins == code2->mins &&
  865.     code1->secs == code2->secs &&
  866.     code1->frames == code2->frames &&
  867.     code1->dropframe == code2->dropframe &&
  868.     code1->framerate == code2->framerate;
  869. }
  870.  
  871. void smpte_ubits_tostring(struct smpte_timecode *code, char *chars){ // FIXME: Needs "struct" due to Arduino strangeness
  872.   uart_array_to_hex(code->ubits, 8, chars);
  873. }
  874.  
  875. void smpte_tostring(struct smpte_timecode *code, char *chars){ // FIXME: Needs "struct" due to Arduino strangeness
  876.  
  877.   // 01:02:03:04 1A2B3C4D 29.97 D\0 == 30 chars
  878.   for(uint8_t i = 0; i < 20; i++){
  879.     chars[i] = 0;
  880.   }
  881.   uart_int_to_decimal(code->hours, chars);
  882.   chars[2] = ':';
  883.   uart_int_to_decimal(code->mins, chars+3);
  884.   chars[5] = ':';
  885.   uart_int_to_decimal(code->secs, chars+6);
  886.   chars[17] = ' ';
  887.   if(code->dropframe){
  888.     chars[8] = ';';
  889.     chars[18] = 'D';
  890.   } else {
  891.     chars[8] = ':';
  892.     chars[18] = ' ';
  893.   }
  894.   uart_int_to_decimal(code->frames, chars+9);
  895.   chars[11] = ' ';
  896.   chars[14] = '.';
  897.   chars[19] = '\0';
  898.  
  899.   switch(code->framerate){
  900.     case R23976:
  901.       chars[12] = '2';
  902.       chars[13] = '3';
  903.       chars[15] = '9';
  904.       chars[16] = '7';
  905.     break;
  906.     case R24:
  907.       chars[12] = '2';
  908.       chars[13] = '4';
  909.       chars[15] = '0';
  910.       chars[16] = '0';
  911.     break;
  912.     case R25:
  913.       chars[12] = '2';
  914.       chars[13] = '5';
  915.       chars[15] = '0';
  916.       chars[16] = '0';
  917.     break;
  918.     case R2997:
  919.       chars[12] = '2';
  920.       chars[13] = '9';
  921.       chars[15] = '9';
  922.       chars[16] = '7';
  923.     break;
  924.     case R30:
  925.       chars[12] = '3';
  926.       chars[13] = '0';
  927.       chars[15] = '0';
  928.       chars[16] = '0';
  929.     break;
  930.     case R50:
  931.       chars[12] = '5';
  932.       chars[13] = '0';
  933.       chars[15] = '0';
  934.       chars[16] = '0';
  935.     break;
  936.     case R5994:
  937.       chars[12] = '5';
  938.       chars[13] = '9';
  939.       chars[15] = '9';
  940.       chars[16] = '4';
  941.     break;
  942.     case R60:
  943.       chars[12] = '6';
  944.       chars[13] = '0';
  945.       chars[15] = '0';
  946.       chars[16] = '0';
  947.     break;
  948.     default:
  949.       chars[12] = 'W';
  950.       chars[13] = 'I';
  951.       chars[14] = 'L';
  952.       chars[15] = 'D';
  953.       chars[16] = ' ';
  954.     break;
  955.   }
  956. }
  957.  
  958. void smpte_increment(struct smpte_timecode *code){ // FIXME: Needs "struct" due to Arduino strangeness
  959.  
  960.   if(code->framerate == UNKNOWN){
  961.     uart_sendl("ERROR: Can't increment, unknown rate.");
  962.     return;
  963.   }
  964.  
  965.   if(code->frames == smpte_framerate_maxframes[code->framerate]){
  966.     if(code->dropframe && code->secs == 59 && ((code->mins +1) % 10 != 0)){
  967.       if(code->framerate == R2997 || code->framerate == R30){
  968.         code->frames = 2; // 29.97 or 30.00 drop
  969.       } else {
  970.         code->frames = 4; // 59.94 or 60.00 drop
  971.       }
  972.     } else {
  973.       code->frames = 0;
  974.     }
  975.     if(code->secs == 59){
  976.       code->secs = 0;
  977.       if(code->mins == 59){
  978.         code->mins = 0;
  979.         if(code->hours == 23){
  980.           code->hours = 0;
  981.         } else {
  982.           code->hours ++;
  983.         }
  984.       } else {
  985.         code->mins ++;
  986.       }
  987.     } else {
  988.       code->secs ++;
  989.     }
  990.   } else {
  991.     code->frames ++;
  992.   }
  993. }
  994.  
  995. // ******************************************
  996. //
  997. // SMPTE-12M Linear Timecode Reader
  998. //
  999. // ******************************************
  1000.  
  1001. // NB wiggle may have to be very significantly larger to make analogue tape work at all.
  1002. // Wiggle room is in F_CPU clocks plus or minus, 5 = +/- 5 clocks
  1003.  
  1004. #include <util/atomic.h>
  1005.  
  1006. // Constants
  1007.  
  1008. #define LTC_MAGIC_A_REV 0b00111111
  1009. #define LTC_MAGIC_B_REV 0b11111101
  1010. #define LTC_MAGIC_A 0b11111100
  1011. #define LTC_MAGIC_B 0b10111111
  1012. #define LTC_BITS_PER_FRAME 80UL
  1013.  
  1014. // Settings
  1015.  
  1016. // 6 = sync over 64 frames, etc
  1017. #define LTC_JAM_FRAMES_SHIFTFACTOR 6
  1018. #define LTC_BITPERIOD_AVG_LEN 64
  1019. #define LTC_BITPERIOD_AVG_SPACING 28
  1020. #define LTC_BITPERIOD_AVG_ADJUST 1.25
  1021. #define LTC_BITPERIOD_TIMEOUT_SAFETY_FACTOR 1.2
  1022.  
  1023. uint8_t ltc_frame_duration_wiggle = 20;
  1024. uint8_t ltc_legal_period_wiggle = 10;
  1025. bool ltc_monotonic = true;
  1026. bool ltc_display_ubits = false;
  1027. uint8_t ltc_required_sequence = 3;
  1028. bool ltc_use_biphase_mark_flag = true;
  1029.  
  1030. // Decoder internal state
  1031.  
  1032. uint16_t ltc_bitperiods[LTC_BITPERIOD_AVG_LEN];
  1033. uint8_t ltc_bitperiod_avgcounter = 0;
  1034. uint8_t ltc_bitperiod_avgindex = 0;
  1035. uint32_t ltc_bitperiod_sum = 0;
  1036. uint8_t ltc_buf[11] = {0,}; // 11 so we can shift easily
  1037. uint8_t ltc_buf2[11] = {0,}; // 11 so we can shift easily
  1038. uint8_t *ltc_readbuffer_ptr = ltc_buf;
  1039. uint8_t *ltc_writebuffer_ptr = ltc_buf2;
  1040. uint8_t ltc_goodframes = 0;
  1041. volatile bool ltc_short_wait_flag;
  1042.  
  1043. // Generator
  1044.  
  1045. uint8_t ltc_gen_bitidx;
  1046. uint16_t ltc_gen_zero_length;
  1047. uint16_t ltc_gen_one_length_1;
  1048. uint16_t ltc_gen_one_length_2;
  1049. uint16_t ltc_gen_dither_qty;
  1050. uint16_t ltc_gen_dither_counter;
  1051. uint8_t ltc_gen_dither_adds;
  1052. uint8_t ltc_gen_buf_1[11];
  1053. uint8_t ltc_gen_buf_2[11];
  1054. uint8_t *ltc_gen_buf_rptr = ltc_gen_buf_1;
  1055. uint8_t *ltc_gen_buf_wptr = ltc_gen_buf_2;
  1056. bool ltc_gen_short_wait_flag = false;
  1057. smpte_timecode ltc_gen_tc_working;
  1058. bool ltc_gen_needs_framedata = false;
  1059. uint8_t ltc_gen_dither_accumulator;
  1060. uint16_t ltc_gen_group_count;
  1061.  
  1062. // Timing
  1063.  
  1064. volatile uint16_t ltc_frame_start_time = 0;
  1065. volatile uint16_t ltc_last_edge_time = 0;
  1066. volatile uint16_t ltc_frame_timer_overflows;
  1067. volatile uint32_t ltc_frametime_now = 0;
  1068. volatile smpte_framerate ltc_framerate_now;
  1069. volatile uint16_t ltc_max_bp;
  1070. volatile uint16_t ltc_min_bp;
  1071. volatile uint16_t ltc_bitperiod_threshold;
  1072. volatile uint16_t ltc_interrupt_delay;
  1073. smpte_timecode ltc_timecode_previous;
  1074. smpte_timecode ltc_timecode_current;
  1075. uint32_t ltc_jam_timer;
  1076. uint32_t ltc_jam_timer_overflows;
  1077. bool ltc_jamming = true;
  1078. uint16_t ltc_jam_framecount;
  1079. uint16_t ltc_jam_last_check;
  1080. uint16_t ltc_jam_start_time;
  1081. uint16_t ltc_frame_timeout;
  1082.  
  1083. // Calibrated pseudo-constants
  1084.  
  1085. uint16_t ltc_bitperiod_longest;
  1086. uint16_t ltc_bitperiod_shortest;
  1087. uint32_t ltc_fr_23976_min;
  1088. uint32_t ltc_fr_23976_max;
  1089. uint32_t ltc_fr_24_min;
  1090. uint32_t ltc_fr_24_max;
  1091. uint32_t ltc_fr_25_min;
  1092. uint32_t ltc_fr_25_max;
  1093. uint32_t ltc_fr_2997_min;
  1094. uint32_t ltc_fr_2997_max;
  1095. uint32_t ltc_fr_30_min;
  1096. uint32_t ltc_fr_30_max;
  1097. uint32_t ltc_fr_50_min;
  1098. uint32_t ltc_fr_50_max;
  1099. uint32_t ltc_fr_5994_min;
  1100. uint32_t ltc_fr_5994_max;
  1101. uint32_t ltc_fr_60_min;
  1102. uint32_t ltc_fr_60_max;
  1103.  
  1104. #define LTC_REV_BITS(v)                       \
  1105. ({                                            \
  1106.     uint8_t val = v;                          \
  1107.     uint8_t res;                              \
  1108.     __asm__                                   \
  1109.     (                                         \
  1110.         "rol %0"      "\n\t"                  \
  1111.         "ror %1"      "\n\t"                  \
  1112.         "rol %0"      "\n\t"                  \
  1113.         "ror %1"      "\n\t"                  \
  1114.         "rol %0"      "\n\t"                  \
  1115.         "ror %1"      "\n\t"                  \
  1116.         "rol %0"      "\n\t"                  \
  1117.         "ror %1"      "\n\t"                  \
  1118.         "rol %0"      "\n\t"                  \
  1119.         "ror %1"      "\n\t"                  \
  1120.         "rol %0"      "\n\t"                  \
  1121.         "ror %1"      "\n\t"                  \
  1122.         "rol %0"      "\n\t"                  \
  1123.         "ror %1"      "\n\t"                  \
  1124.         "rol %0"      "\n\t"                  \
  1125.         "ror %1"      "\n\t"                  \
  1126.         : "=&d" (val), "=r" (res)             \
  1127.         : "0" (val)                           \
  1128.     );                                        \
  1129.     res;                                      \
  1130. })
  1131.  
  1132. // Log some info about the LTC reader setup. Usually just alias to a usart send function.
  1133.  
  1134. void ltc_log(const char* str){
  1135.   uart_send("LTC: ");
  1136.   uart_sendl(str);
  1137. }
  1138.  
  1139. void ltc_decoder_init(){
  1140.  
  1141.   ltc_bitperiod_threshold = ltc_bitperiod_longest - (ltc_bitperiod_shortest >> 1);
  1142.   ltc_max_bp = 0;
  1143.   ltc_min_bp = 0xFFFFUL;
  1144.   ltc_framerate_now = UNKNOWN;
  1145.   ltc_frametime_now = 0;
  1146.   ltc_short_wait_flag = false;
  1147.   ltc_goodframes = 0;
  1148.  
  1149.  
  1150.   ltc_gen_begin_jam(); // Basically just resets a bunch of stuff so we'll start jamming on good code.
  1151.  
  1152.   display_show("NO CODE");
  1153.  
  1154. }
  1155.  
  1156. void ltc_init(){
  1157.  
  1158.   ltc_log("Set up...");
  1159.   if(ltc_monotonic){
  1160.     ltc_log("Decoder: Monotonic");
  1161.   } else {
  1162.     ltc_log("Decoder: Wild");
  1163.   }
  1164.  
  1165.   ltc_init_calibrated(16000000);
  1166.  
  1167.   // Signal: PD7 AIN1 neg - arduino digital 7, ATmega328 pin 13
  1168.   // Signal ground: PD6 AINO pos - arduino digital 6, ATmega328 pin 12
  1169.  
  1170.   // Set up ports
  1171.  
  1172.   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
  1173.   PORTD &= ~((1<<7) | (1<<6)); // with pullup off
  1174.  
  1175.   // Stuff for LTC output. Set PD5 (OC0B) as output so that it can be toggled on compare match.
  1176.  
  1177.   DDRD |= (1 << 5);
  1178.  
  1179.  
  1180.   // Set up ADC/AC hardware
  1181.  
  1182.   ADCSRA &= ~(1<<ADEN); // Disable the ADC. All else is zeros. You'd write a 1 to ADSC to start an ADC conversion. Other bits enable conversion-complete interrupts etc.
  1183.   DIDR1 = (1<<AIN1D) | (1<AIN0D); // Disable the digital input buffer on the AIN1/0 pins to reduce current consumption
  1184.  
  1185.   // Analog comparator control and status register
  1186.  
  1187.   ACSR = (1<<ACIC); // Bits 3 and 2 - enable interrupt. ACIE - AC interrupt enable. ACIC - AC input capture enable. This is absolutely required for LTC decode.
  1188.                // Otherwise, most of what we want is zeroes:
  1189.                // ACD (7) = Analog Comparator Disable
  1190.                // ACBG (6) = use bandgap reference instead of positive input.
  1191.                // ACO (5) Read-only comparator output state
  1192.                // ACI (4) Interrupt flag. Can be cleared manually, so clear it here to avoid shenanigans.
  1193.                // ACIE (3) Interrupt enable. Don't actually need this; we go on the timer input capture interrupt, not the AC interrupt.
  1194.                // ACIS[1:0] Zeroed - comparator interrupt on output toggle. Don't use this as we rely on the timer input capture interrupt not the AC interrupt.
  1195.  
  1196.   // Set up timer 1
  1197.  
  1198.   TCCR1A = 0x00; // Explicitly zero the register to avoid shenanigans
  1199.   TCCR1A |= (1 << COM0B0); // Bits 5 and 4 of TCCR1A are COM0Bn, "compare output mode for channel B." Toggle OC0B on compare match = 0b01.
  1200.  
  1201.   // The below needs to stay off until we want to output jammed code.
  1202.   //TCCR1A |= (1 << WGM01);  // Bits 0 and 1 (WGM00, WGM01) set CTC mode. WGM02 is involved in other timer modes, but it's in TCCR1B and we don't need it.
  1203.   OCR1A = 1000000;
  1204.   TIMSK1 |= (1 << 1);
  1205.  
  1206.   // This is stuff used to decode LTC in EXT mode
  1207.  
  1208.   TCCR1B = 0x00; // Explicitly zero the register to avoid shenanigans
  1209.   TCCR1B |= ((1<<ICES1) | // Trip on rising edge first. This gets swapped a lot later.
  1210.              (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
  1211.              (0<<CS11) |  // Flip this to 1 for /64
  1212.              (0<<CS12));  // NB these are in reverse order.
  1213.              
  1214.   TIMSK1 = 0x00; // Explicitly zero the register to avoid shenanigans
  1215.   TIMSK1 |= (1<<ICIE1); // Enable input capture interrupt, which is the one used by the AC.
  1216.   TIMSK1 |= (1<<1);
  1217.  
  1218.   ltc_decoder_init();
  1219.  
  1220. }
  1221.  
  1222. void ltc_init_calibrated(uint32_t calibratedClockSpeed){
  1223.   ltc_bitperiod_longest = ((((calibratedClockSpeed/1000L)*1001L)/24L)/LTC_BITS_PER_FRAME) + ltc_legal_period_wiggle;
  1224.   ltc_bitperiod_shortest = ((calibratedClockSpeed/60L)/160L) - ltc_legal_period_wiggle;
  1225.   ltc_fr_23976_min = (((calibratedClockSpeed/1000L)*1001L)/24L) - (uint32_t)ltc_frame_duration_wiggle;
  1226.   ltc_fr_23976_max = (((calibratedClockSpeed/1000L)*1001L)/24L) + (uint32_t)ltc_frame_duration_wiggle;
  1227.   ltc_fr_24_min = (calibratedClockSpeed/24) - ltc_frame_duration_wiggle;
  1228.   ltc_fr_24_max = (calibratedClockSpeed/24) + ltc_frame_duration_wiggle;
  1229.   ltc_fr_25_min = (calibratedClockSpeed/25) - ltc_frame_duration_wiggle;
  1230.   ltc_fr_25_max = (calibratedClockSpeed/25) + ltc_frame_duration_wiggle;
  1231.   ltc_fr_2997_min = (((calibratedClockSpeed/1000L)*1001L)/30L) - (uint32_t)ltc_frame_duration_wiggle;
  1232.   ltc_fr_2997_max = (((calibratedClockSpeed/1000L)*1001L)/30L) + (uint32_t)ltc_frame_duration_wiggle;
  1233.   ltc_fr_30_min = (calibratedClockSpeed/30) - ltc_frame_duration_wiggle;
  1234.   ltc_fr_30_max = (calibratedClockSpeed/30) + ltc_frame_duration_wiggle;
  1235.   ltc_fr_50_min = (calibratedClockSpeed/50) - ltc_frame_duration_wiggle;
  1236.   ltc_fr_50_max = (calibratedClockSpeed/50) + ltc_frame_duration_wiggle;
  1237.   ltc_fr_5994_min = (((calibratedClockSpeed/1000L)*1001L)/60L) - (uint32_t)ltc_frame_duration_wiggle;
  1238.   ltc_fr_5994_max = (((calibratedClockSpeed/1000L)*1001L)/60L) + (uint32_t)ltc_frame_duration_wiggle;
  1239.   ltc_fr_60_min = (calibratedClockSpeed/60) - ltc_frame_duration_wiggle;
  1240.   ltc_fr_60_max = (calibratedClockSpeed/60) + ltc_frame_duration_wiggle;
  1241.   ltc_frame_timeout = ((calibratedClockSpeed/24)/LTC_BITS_PER_FRAME) * LTC_BITPERIOD_TIMEOUT_SAFETY_FACTOR;
  1242. }
  1243.  
  1244. smpte_framerate ltc_get_framerate(uint32_t frame_duration); // Prototype. Arduino IDE screws with enums for some reason
  1245. smpte_framerate ltc_get_framerate(uint32_t frame_duration){
  1246.  
  1247.   // FIXME: Should this deal with the concept of a user-selected framerate,
  1248.   // and showing some sort of error if the incoming code isn't at that rate?
  1249.  
  1250.   // TODO: Averaging for flaky signals?
  1251.  
  1252.   if(frame_duration > ltc_fr_23976_min && frame_duration < ltc_fr_23976_max){
  1253.     return R23976;
  1254.   } else if(frame_duration > ltc_fr_24_min && frame_duration < ltc_fr_24_max){
  1255.     return R24;
  1256.   } else if(frame_duration > ltc_fr_25_min && frame_duration < ltc_fr_25_max){
  1257.     return R25;
  1258.   } else if(frame_duration > ltc_fr_2997_min && frame_duration < ltc_fr_2997_max){
  1259.     return R2997;
  1260.   } else if(frame_duration > ltc_fr_30_min && frame_duration < ltc_fr_30_max){
  1261.     return R30;
  1262.   } else if(frame_duration > ltc_fr_50_min && frame_duration < ltc_fr_50_max){
  1263.     return R50;
  1264.   } else if(frame_duration > ltc_fr_5994_min && frame_duration < ltc_fr_5994_max){
  1265.     return R5994;
  1266.   } else if(frame_duration > ltc_fr_60_min && frame_duration < ltc_fr_60_max){
  1267.     return R60;
  1268.   } else {
  1269.     return UNKNOWN;
  1270.   }
  1271. }
  1272.  
  1273. void ltc_event_poll(){
  1274.  
  1275.   if(ltc_gen_needs_framedata){
  1276.     ltc_gen_setup_next_frame(); // This is required to kick things off
  1277.     smpte_log_code(&ltc_gen_tc_working);
  1278.   }
  1279.  
  1280.   if(ltc_frametime_now > 0){
  1281.     ltc_new_frame();
  1282.     ltc_frametime_now = 0;
  1283.   }
  1284.  
  1285.   if(ltc_goodframes < ltc_required_sequence) return;
  1286.   uint16_t duration;
  1287.   uint16_t last;
  1288.   ATOMIC_BLOCK(ATOMIC_RESTORESTATE){
  1289.     last = ltc_last_edge_time;
  1290.   }
  1291.  
  1292.   uint16_t now = TCNT1;
  1293.  
  1294.   if(now > last){
  1295.     duration = now - last;
  1296.   } else {
  1297.     duration = now + (0xFFFFUL - last);
  1298.   }
  1299.  
  1300.   if(duration > ltc_frame_timeout){
  1301.     ltc_desync();
  1302.   }
  1303.  
  1304. }
  1305.  
  1306. // *******
  1307. // Reader
  1308. // *******
  1309.  
  1310. void ltc_set_bitperiod_threshold(uint16_t this_edge_duration){
  1311.  
  1312.   if(ltc_monotonic){
  1313.  
  1314.     // TODO: Reset when changing FR?
  1315.  
  1316.     ltc_max_bp = ltc_max_bp > this_edge_duration ? ltc_max_bp : this_edge_duration;
  1317.     ltc_min_bp = ltc_min_bp < this_edge_duration ? ltc_min_bp : this_edge_duration;
  1318.     ltc_bitperiod_threshold = ltc_max_bp - ((ltc_max_bp - ltc_min_bp) >> 1);
  1319.    
  1320.   } else {
  1321.  
  1322.     // FIXME: None of this gets reset in init() but it doesn't matter much -
  1323.     // it just means it'll take fractionally (and really fractionally) longer
  1324.     // to lock up if the averages aren't right for the incoming framerate.
  1325.    
  1326.     if(ltc_bitperiod_avgcounter == LTC_BITPERIOD_AVG_SPACING){
  1327.       ltc_bitperiod_avgcounter = 0;
  1328.       ltc_bitperiods[ltc_bitperiod_avgindex] = this_edge_duration;
  1329.       ltc_bitperiod_sum += this_edge_duration;
  1330.       ltc_bitperiod_avgindex ++;
  1331.       if(ltc_bitperiod_avgindex == LTC_BITPERIOD_AVG_LEN){
  1332.         ltc_bitperiod_avgindex = 0;
  1333.       }
  1334.       ltc_bitperiod_sum -= ltc_bitperiods[ltc_bitperiod_avgindex];
  1335.       ltc_bitperiod_threshold = ltc_bitperiod_sum >> 6; // Divide number by value in LTC_BITPERIOD_AVG_LEN
  1336.       ltc_bitperiod_threshold *= LTC_BITPERIOD_AVG_ADJUST;
  1337.     } else {
  1338.       ltc_bitperiod_avgcounter ++;
  1339.     }
  1340.  
  1341.   }
  1342.  
  1343. }
  1344.  
  1345. ISR (TIMER1_COMPA_vect) {
  1346.   OCR1A = ltc_gen_get_next_transition() - 1; // Subtract one because the timers always runs one clock longer than the value sent.
  1347. }
  1348.  
  1349. ISR(TIMER1_CAPT_vect){
  1350.  
  1351.   // Flip looking for rising or falling edges
  1352.  
  1353.   TCCR1B ^= (1<<ICES1);
  1354.  
  1355.   // Figure out time since last edge
  1356.  
  1357.   uint16_t this_edge_duration;
  1358.  
  1359.   if(ICR1 > ltc_last_edge_time){
  1360.     this_edge_duration = ICR1 - ltc_last_edge_time;
  1361.   } else {
  1362.     ltc_frame_timer_overflows++; // TODO: If this overflows we're horrifically out of time and should bomb out
  1363.     this_edge_duration = ICR1 + (0xFFFFUL - ltc_last_edge_time);
  1364.   }
  1365.  
  1366.   if(ltc_jamming){
  1367.     if(ltc_jam_framecount == 0){
  1368.       // Begin a new jam
  1369.       ltc_jam_start_time = ICR1;
  1370.       ltc_jam_last_check = ICR1;
  1371.     } else {
  1372.       // We're in a jam (ho ho ho)
  1373.       if(ICR1 < ltc_jam_last_check){
  1374.         ltc_jam_timer_overflows ++;
  1375.       }
  1376.     }
  1377.   }
  1378.   ltc_jam_last_check = ICR1;
  1379.  
  1380.   if(this_edge_duration > ltc_bitperiod_longest || this_edge_duration < ltc_bitperiod_shortest){ // FIXME: Be more specific about per-framerate legal bit periods.
  1381.     // Reject this bit period as not part of a valid monotonic timecode signal (just noise, or a non-TC audio signal)
  1382.     ltc_desync();
  1383.     return;
  1384.   }
  1385.  
  1386.   ltc_last_edge_time = ICR1;
  1387.   ltc_jam_last_check = ICR1;
  1388.   ltc_set_bitperiod_threshold(this_edge_duration);
  1389.  
  1390.   // Figure out whether this was a long or short bitperiod
  1391.   // and if it was short, figure out if it's the second short
  1392.   // one in a row. Push the result to the buffer.
  1393.  
  1394.   if(this_edge_duration > ltc_bitperiod_threshold){
  1395.     // It's a zero. Zero the last bit in the buffer.
  1396.     ltc_writebuffer_ptr[9] &= ~(0x80);
  1397.     if(ltc_short_wait_flag){
  1398.       ltc_short_wait_flag = false; // Should never get a long after just one short
  1399.       ltc_desync();
  1400.       return;
  1401.     }
  1402.   } else {
  1403.     // It's possibly part of a 1
  1404.     if(ltc_short_wait_flag){
  1405.       // It's a one. Set the last bit in the buffer.
  1406.       ltc_writebuffer_ptr[9] |= 0x80;
  1407.       ltc_short_wait_flag = false;
  1408.     } else {
  1409.       // It's presmably the beginning of a one
  1410.       ltc_short_wait_flag = true;
  1411.       return;
  1412.     }
  1413.   }
  1414.  
  1415.   // Check to see if we've found a full frame
  1416.  
  1417.   if((ltc_writebuffer_ptr[8] == LTC_MAGIC_A && ltc_writebuffer_ptr[9] == LTC_MAGIC_B)
  1418.   || (ltc_writebuffer_ptr[0] == LTC_MAGIC_B_REV && ltc_writebuffer_ptr[1] == LTC_MAGIC_A_REV)){
  1419.  
  1420.     // Display the next TC as early as possible
  1421.  
  1422.     if(ltc_goodframes == ltc_required_sequence) display_latch();
  1423.  
  1424.     // Get an idea of how long it takes from the interrupt firing to get to here.
  1425.    
  1426.     ATOMIC_BLOCK(ATOMIC_RESTORESTATE){
  1427.       ltc_interrupt_delay = TCNT1;
  1428.     }
  1429.     if(ltc_interrupt_delay > ICR1){
  1430.       ltc_interrupt_delay -= ICR1;
  1431.     } else {
  1432.       ltc_interrupt_delay = ltc_interrupt_delay + (0xFFFFUL - ICR1);
  1433.     }
  1434.    
  1435.     // Calculate the precision frame duration
  1436.  
  1437.     ltc_frametime_now = 0xFFFFUL * ltc_frame_timer_overflows - ltc_frame_start_time + ICR1;
  1438.     ltc_frame_timer_overflows = 0;
  1439.     ltc_frame_start_time = ICR1;
  1440.  
  1441.     // If we've finished a jam, signal completion. If not, and we're jamming, increment the jam frame counter
  1442.     /*
  1443.  * At an appropriate instant, turn off the analog comparator+timer capture interrupt, turn on CTC mode, turn on output
  1444.  * pin toggling, zero the timer and get a new value for it from ltc_gen_get_next_transition. Set that
  1445.  * to be the CTC mode trip point, and in a new ISR keep calling ltc_gen_get_next_transition about 110
  1446.  * times a frame.
  1447.  *
  1448.   */
  1449.     if(ltc_jam_framecount == (1<<LTC_JAM_FRAMES_SHIFTFACTOR)){
  1450.       //TCCR1A |= (1 << WGM01);
  1451.       TCCR1B |= (1 << WGM12); // TODO this will need tweaking for proper phasing
  1452.       ltc_gen_tc_working = ltc_timecode_current;
  1453.       ltc_jamming = false;
  1454.       //uart_send("Ovf:");
  1455.       //uart_sendl(ltc_jam_timer_overflows);
  1456.       // FIXME: the addition of jam_timer_overflows is experimental as it seemed suspiciously close to the required kludge
  1457.       // It probably still counts as a kludge as we've no idea why we'd be that far out, but if it works... though we don't know it works yet.
  1458.       //ltc_jam_timer = 0xFFFFUL * ltc_jam_timer_overflows - ltc_jam_start_time + ICR1 + ltc_jam_timer_overflows;
  1459.       ltc_jam_timer = ((0xFFFFUL * ltc_jam_timer_overflows) - ltc_jam_start_time) + ICR1;
  1460.  
  1461.     } else {
  1462.       if(ltc_jamming) ltc_jam_framecount++;
  1463.     }
  1464.    
  1465.     // Swap buffers
  1466.  
  1467.     if (ltc_readbuffer_ptr == ltc_buf){
  1468.       ltc_readbuffer_ptr = ltc_buf2;
  1469.       ltc_writebuffer_ptr = ltc_buf;
  1470.     } else {
  1471.       ltc_readbuffer_ptr = ltc_buf;
  1472.       ltc_writebuffer_ptr = ltc_buf2;
  1473.     }
  1474.  
  1475.   }
  1476.  
  1477.   // Shuffle the buffer
  1478.  
  1479.   for(uint8_t i = 0; i < 10; i++){ // Remember we made an extra byte on the end we don't need?
  1480.     ltc_writebuffer_ptr[i] = (ltc_writebuffer_ptr[i] >> 1) | (ltc_writebuffer_ptr[i+1] << 7);
  1481.   }
  1482.  
  1483. }
  1484.  
  1485. void ltc_desync(){
  1486.  
  1487.   if(ltc_goodframes < ltc_required_sequence) return; // can't desync when not synced. This really just guards against multiple hits.
  1488.   if(ltc_monotonic) display_show("NO CODE");
  1489.   ltc_log("Unlocked");
  1490.   ltc_decoder_init();
  1491.   // TODO: some sort of function pointer for this "event?"
  1492.  
  1493. }
  1494.  
  1495. void ltc_sync(){
  1496.  
  1497.   uart_send("LTC: Lock: ");
  1498.   // TODO: some sort of function pointer for this "event?"
  1499.   // TODO: Should this be guarded against double calling? It never seems to be a problem.
  1500.   uart_send(smpte_framerate_names[ltc_timecode_current.framerate]);
  1501.   if(ltc_timecode_current.dropframe == true){
  1502.     uart_sendl(" DF");
  1503.   } else {
  1504.     if(ltc_timecode_current.framerate == R2997 ||
  1505.       ltc_timecode_current.framerate == R30 ||
  1506.       ltc_timecode_current.framerate == R5994 ||
  1507.       ltc_timecode_current.framerate == R60){
  1508.       uart_sendl(" ND");
  1509.     } else {
  1510.       uart_send("\r\n");
  1511.     }
  1512.   }
  1513.  
  1514. }
  1515.  
  1516. void ltc_reverse_buffer(uint8_t *buf){
  1517.  
  1518.   uint8_t revbuffer[10]; // This will hold the reversed data  
  1519.   for(uint8_t i = 0; i < 10; i++){
  1520.     revbuffer[i] = LTC_REV_BITS(buf[9-i]); // NB LTC_REV_BITS is known good
  1521.   }
  1522.   for(uint8_t j = 0; j < 10; j++){
  1523.     buf[j] = revbuffer[j];
  1524.   }
  1525.  
  1526. }
  1527.  
  1528. // FIXME: Note that this will always return timecode structs marked
  1529. // with the currently-detected framerate at the time of unpacking. This
  1530. // might easily not represent the framerate at which this specific
  1531. // LTC buffer was captured.
  1532.  
  1533. void ltc_unpack_frame(struct smpte_timecode *code, uint8_t *buf){ // FIXME: Needs "struct" due to Arduino strangeness
  1534.  
  1535.   code->hours = (10*(buf[7] & 0b00000011)) + (buf[6] & 0b00001111); // Other bits in hrs tens are reserved and binary group flag
  1536.   code->mins = (10*(buf[5] & 0b00000111)) + (buf[4] & 0b00001111); // Other bit in mins tens is binary group flag
  1537.   code->secs = (10*(buf[3] & 0b00000111)) + (buf[2] & 0b00001111); // Other bit in secs tens is biphase mark correction bit
  1538.   code->frames = (10*(buf[1] & 0b00000011)) + (buf[0] & 0b00001111); // Other bits in frames tens are drop frame and color frame flags
  1539.   code->dropframe = (buf[1] & 0b00000100) == 4;
  1540.   code->ubits[3] = ((buf[1] & 0b11110000)) | ((buf[0] & 0b11110000)>>4);
  1541.   code->ubits[2] = ((buf[3] & 0b11110000)) | ((buf[2] & 0b11110000)>>4);
  1542.   code->ubits[1] = ((buf[5] & 0b11110000)) | ((buf[4] & 0b11110000)>>4);
  1543.   code->ubits[0] = ((buf[7] & 0b11110000)) | ((buf[6] & 0b11110000)>>4);
  1544.   code->framerate = ltc_get_framerate(ltc_frametime_now);
  1545.   code->frametime = ltc_frametime_now;
  1546.  
  1547. }
  1548.  
  1549. void ltc_new_frame(){
  1550.  
  1551.   if(!ltc_jamming && ltc_jam_framecount == (1<<LTC_JAM_FRAMES_SHIFTFACTOR)){
  1552.     ltc_calc_gen_constants();
  1553.     ltc_jam_framecount = 0;
  1554.   }
  1555.  
  1556.   ltc_timecode_current.fwd = ltc_readbuffer_ptr[0] != LTC_MAGIC_B_REV || ltc_readbuffer_ptr[1] != LTC_MAGIC_A_REV;
  1557.  
  1558.   if(!ltc_timecode_current.fwd){
  1559.     ltc_reverse_buffer(ltc_readbuffer_ptr);
  1560.   }
  1561.  
  1562.   ltc_unpack_frame(&ltc_timecode_current, ltc_readbuffer_ptr);
  1563.  
  1564.   if(smpte_compare(&ltc_timecode_current, &ltc_timecode_previous)){
  1565.     if(ltc_goodframes < ltc_required_sequence) {
  1566.       ltc_goodframes ++;
  1567.       if(ltc_goodframes == ltc_required_sequence){
  1568.         ltc_sync();
  1569.       }
  1570.     }
  1571.   } else {
  1572.     ltc_desync(); // This will set goodframes to 0
  1573.   }
  1574.  
  1575.   smpte_increment(&ltc_timecode_current); // ltc_timecode_current now indicates the frame we're actually in as this function runs
  1576.   ltc_timecode_previous = ltc_timecode_current;
  1577.  
  1578.   if(ltc_monotonic || ltc_goodframes == ltc_required_sequence){
  1579.     // If we're monotonic, or if we're wild and we have synced code, load two-up and wait to latch on the next sync word
  1580.     smpte_increment(&ltc_timecode_current); // Increment again, so that when we get to the end of THIS frame, ltc_timecode_current will indicate the next frame.
  1581.     ltc_preload_display(&ltc_timecode_current);
  1582.   } else {
  1583.     // If we're wild (not-monotonic) and don't have synced code, display immediately, because it's all a bit up in the air.
  1584.     ltc_preload_display(&ltc_timecode_current);
  1585.     display_latch();
  1586.   }
  1587.  
  1588.   // FIXME: TEST: Every time we get a new frame, read out all the transitions for the one we've buffered in the generator for test.
  1589.   /*if(ltc_jam_timer > 0 && ltc_jamming == false){
  1590.     uart_sendl("Jam out:");
  1591.     smpte_log_code(&ltc_gen_tc_working);
  1592.     uart_send("\r\nTransitions: ");
  1593.     uint8_t transcount = 0;
  1594.     //uart_sendl(ltc_gen_needs_framedata);
  1595.     while(!ltc_gen_needs_framedata){
  1596.       ltc_gen_get_next_transition();
  1597.       transcount++;
  1598.     }
  1599.     uart_sendl(transcount); // STARTHERE: there's going to be some issue with swapping buffers, since we get an 80-period frame when we shouldn't have just sent all the 0s.
  1600.  
  1601.   }*/
  1602. }
  1603.  
  1604. void smpte_log_code(struct smpte_timecode *code){
  1605.   char tc[20];
  1606.   smpte_tostring(code,tc);
  1607.   uart_sendl(tc);
  1608. }
  1609.  
  1610. void ltc_preload_display(struct smpte_timecode *code){
  1611.  
  1612.   uint8_t preload_nums[8] = {0,};
  1613.  
  1614.   if(ltc_display_ubits){
  1615.    
  1616.     uart_array_to_hex(code->ubits, 4, preload_nums);
  1617.     for(uint8_t i = 0; i< 8; i++){
  1618.       preload_nums[i] = pgm_read_byte_near(display_alpha + (preload_nums[i] - 48));
  1619.     }
  1620.  
  1621.   } else {
  1622.  
  1623.     preload_nums[0] = pgm_read_byte_near(display_alpha + (code->hours / 10));
  1624.     preload_nums[1] = pgm_read_byte_near(display_alpha + (code->hours % 10)) | 0b00000010;
  1625.     preload_nums[2] = pgm_read_byte_near(display_alpha + (code->mins / 10));
  1626.     preload_nums[3] = pgm_read_byte_near(display_alpha + (code->mins % 10)) | 0b00000010;
  1627.     preload_nums[4] = pgm_read_byte_near(display_alpha + (code->secs / 10));
  1628.     preload_nums[5] = pgm_read_byte_near(display_alpha + (code->secs % 10)) | 0b00000010;
  1629.     preload_nums[6] = pgm_read_byte_near(display_alpha + (code->frames / 10));
  1630.     preload_nums[7] = pgm_read_byte_near(display_alpha + (code->frames % 10));
  1631.    
  1632.   }
  1633.  
  1634.   display_load_raw(preload_nums);
  1635.  
  1636. }
  1637.  
  1638. // **********
  1639. // Generator
  1640. // **********
  1641.  
  1642. // FIXME? ltc_pack_frame does no checking on the hours tens or minutes tens.
  1643. // if there are more than 2 hours tens or more than 5 minutes tens, this will
  1644. // overwrite junk into the bit flags or generically produce drivel.
  1645. // This can be fixed by more correct masking.
  1646.  
  1647. // FIXME?: We set the biphase mark correction bit to 1 if there's an odd number
  1648. // of ones in the buffer, zero otherwise. It will work either way as a way of stopping
  1649. // the phase of the waveform from toggling, but we're not sure if this is actually
  1650. // to spec. Setting it to zero with an odd number of ones, and one otherwise, would
  1651. // have the same effect. It almost certainly doesn't matter.
  1652.  
  1653. void ltc_pack_frame(struct smpte_timecode *code, uint8_t *buf){
  1654.  
  1655.   buf[0] = (code->ubits[3] & 0b00001111) << 4 | (code->frames % 10);
  1656.   buf[1] = (code->ubits[3] & 0b11110000) | (code->frames / 10);
  1657.   buf[2] = (code->ubits[2] & 0b00001111) << 4 | (code->secs % 10);
  1658.   buf[3] = (code->ubits[2] & 0b11110000) | (code->secs / 10);
  1659.   buf[4] = (code->ubits[1] & 0b00001111) << 4 | (code->mins % 10);
  1660.   buf[5] = (code->ubits[1] & 0b11110000) | (code->mins / 10);
  1661.   buf[6] = (code->ubits[0] & 0b00001111) << 4 | (code->hours % 10);
  1662.   buf[7] = (code->ubits[0] & 0b11110000) | (code->hours / 10);
  1663.   buf[8] = LTC_MAGIC_A;
  1664.   buf[9] = LTC_MAGIC_B;
  1665.  
  1666.   if(code->dropframe) buf[1] |= 0b00000100;
  1667.  
  1668.   if(ltc_use_biphase_mark_flag && ltc_get_ones_in_buffer(buf) & 1){
  1669.     buf[3] |= 0b00010000;
  1670.   }
  1671.  
  1672.   // Behaviour as designed: we do not set bits 43 and 59, because
  1673.   // these are intended to indicate the character set of user bit
  1674.   // data. This is almost never used, and various sources recommend
  1675.   // leaving them at zero which means "no user bits format specified."
  1676.   // Setting them to 1 may cause problems with bad readers which
  1677.   // assume the minutes-tens and hours-tens values, respectively,
  1678.   // are 4 bits wide. Values other than 0 and 1 are formally reserved.
  1679.  
  1680.   // Also, we do not set bit 11 which indicates whether the timecode
  1681.   // is supposed to be synchronised to a colour field sequence, which
  1682.   // is obsolete, irrelevant in the context of almost all modern timecode
  1683.   // applications, and may interfere with the decoding of frames-tens
  1684.   // value with bad readers. It's trivial to add to buf[1] if we need it.
  1685.  
  1686.   // Bit 58 is formally reserved.
  1687.  
  1688.   // FIXME: It's possible that some of this has changed in the
  1689.   // 50- and 60-frame revisions but we don't know that at the moment.
  1690.   // In any case, any receiver would be mad not to support the old version.
  1691.  
  1692. }
  1693.  
  1694. uint8_t ltc_get_ones_in_buffer(uint8_t *buf){
  1695.  
  1696.   uint8_t count = 0;
  1697.   uint8_t n = 0;
  1698.   for(uint8_t i = 0; i < 10; i++){
  1699.     n = buf[i];
  1700.     while (n){
  1701.       count += n & 1;
  1702.       n >>= 1;
  1703.     }
  1704.   }
  1705.   //uart_sendl(count);
  1706.   return count;
  1707.  
  1708. }
  1709.  
  1710. uint16_t ltc_gen_get_next_transition(){
  1711.  
  1712.   uint16_t val;
  1713.   if(ltc_gen_short_wait_flag){
  1714.  
  1715.     val = ltc_gen_one_length_2;
  1716.     ltc_gen_short_wait_flag = false;
  1717.     ltc_gen_bitidx ++;
  1718.   } else {
  1719.  
  1720.     if((ltc_gen_buf_rptr[ltc_gen_bitidx >> 3] & (1<<(ltc_gen_bitidx & 7)))){ // 1<< or 128>>
  1721.       // One
  1722.       val = ltc_gen_one_length_1;
  1723.       ltc_gen_short_wait_flag = true;
  1724.       //if(ltc_gen_bitidx==79)ltc_gen_bitidx --; // Make sure we actually get called once more to finish off the short ending transition.
  1725.     } else {
  1726.       // Zero
  1727.       val = ltc_gen_zero_length;
  1728.           ltc_gen_bitidx ++;
  1729.     }
  1730.  
  1731.     // Dither goes here because we only put dither once per bit period,
  1732.     // so we don't want dither on both halves of a pair of short transitions
  1733.  
  1734.     uint8_t last_dither_accu = ltc_gen_dither_accumulator;
  1735.     ltc_gen_dither_accumulator += ltc_gen_dither_adds;
  1736.     if(ltc_gen_dither_accumulator < last_dither_accu){ // we rolled over
  1737.       if(ltc_gen_dither_counter < ltc_gen_dither_qty){
  1738.         val++;
  1739.         ltc_gen_dither_counter ++;
  1740.       }
  1741.     }
  1742.  
  1743.  
  1744.  
  1745.     // If we've got to the end of this frame, flip the buffers
  1746.     // This assumes that the next frame data was packed into
  1747.     // the other buffer by ltc_gen_setup_next_frame() while
  1748.     // we were sending out this one
  1749.    
  1750.  
  1751.   }
  1752.     if(ltc_gen_bitidx == LTC_BITS_PER_FRAME){
  1753.       //uart_send(LTC_BITS_PER_FRAME);
  1754.       ltc_gen_flip_buffers();
  1755.       ltc_gen_bitidx = 0;
  1756.       ltc_gen_needs_framedata = true;
  1757.     }
  1758.   return val;
  1759.  
  1760. }
  1761.  
  1762. void ltc_gen_flip_buffers(){
  1763.  
  1764.   if(ltc_gen_buf_wptr == ltc_gen_buf_1){
  1765.     ltc_gen_buf_wptr = ltc_gen_buf_2;
  1766.     ltc_gen_buf_rptr = ltc_gen_buf_1;
  1767.   } else {
  1768.     ltc_gen_buf_wptr = ltc_gen_buf_1;
  1769.     ltc_gen_buf_rptr = ltc_gen_buf_2;
  1770.   }
  1771.  
  1772. }
  1773.  
  1774. // NB assumes the frame we want is the frame subsequent to ltc_gen_tc_working
  1775. // and will increment before packing. Writes to wptr while active. Output frame
  1776. // ends up in rptr (for reading by other code) while wptr is freed up for
  1777. // building the next frame.
  1778.  
  1779. void ltc_gen_setup_next_frame(){
  1780.  
  1781.   if(ltc_gen_group_count == (1<<LTC_JAM_FRAMES_SHIFTFACTOR)){
  1782.     ltc_gen_dither_accumulator = 0;
  1783.     ltc_gen_dither_counter = 0;
  1784.     ltc_gen_group_count = 0;
  1785.   } else {
  1786.     ltc_gen_group_count ++;
  1787.   }
  1788.  
  1789.   smpte_increment(&ltc_gen_tc_working);
  1790.   ltc_pack_frame(&ltc_gen_tc_working, ltc_gen_buf_wptr);
  1791.   ltc_gen_needs_framedata = false;
  1792.   ltc_gen_flip_buffers();
  1793.  
  1794. }
  1795.  
  1796. void ltc_calc_gen_constants(){ // gets called once from new_frame.
  1797.  
  1798.   uint16_t total_transitions = (1<<LTC_JAM_FRAMES_SHIFTFACTOR)*LTC_BITS_PER_FRAME;
  1799.  
  1800.   //ltc_jam_timer += 680; // Now we add on the number of jam timer overflows in the ISR. No idea how great it is. Trying.
  1801.  
  1802.   ltc_gen_zero_length = ltc_jam_timer / total_transitions; // ltc_jam_timer is total sysclocks per n frames, something like 34 million over 64 frames at 30fps
  1803.   ltc_gen_one_length_1 = ltc_gen_zero_length >> 1;
  1804.   ltc_gen_one_length_2 = ltc_gen_one_length_1;
  1805.   if(ltc_gen_zero_length % 2 != 0) ltc_gen_one_length_2 ++; // Handles odd-numbered long tick counts
  1806.  
  1807.   ltc_gen_group_count = 0;
  1808.   ltc_gen_dither_counter = 0;
  1809.   ltc_gen_needs_framedata = false;
  1810.   ltc_gen_dither_qty = ltc_jam_timer % total_transitions;
  1811.   ltc_gen_setup_next_frame();
  1812.  
  1813.   // NB version below will always ceil() the resulting value so we don't run out of bitperiods to add dither to
  1814.   ltc_gen_dither_adds = (((256UL * ltc_gen_dither_qty) + (total_transitions/2)) / total_transitions); //((256UL * ltc_gen_dither_qty) / total_transitions);
  1815.  
  1816.   uart_send("Jammed: ");
  1817.   uart_send((uint32_t)ltc_gen_zero_length);
  1818.   uart_send("; s: ");
  1819.   uart_send((uint32_t)ltc_gen_one_length_1);
  1820.   uart_send("/");
  1821.   uart_send((uint32_t)ltc_gen_one_length_2);
  1822.   uart_send("; d: ");
  1823.   uart_send((uint32_t)ltc_gen_dither_qty);
  1824.   uart_send("; adds: ");
  1825.   uart_sendl((uint32_t)ltc_gen_dither_adds);
  1826.  
  1827. }
  1828.    
  1829. void ltc_gen_begin_jam(){
  1830.  
  1831.   ltc_jam_timer = 0;
  1832.   ltc_jam_timer_overflows = 0;
  1833.   ltc_jamming = true;
  1834.   ltc_jam_framecount = 0; // Will already be 0 if we've jammed before
  1835.   ltc_jam_last_check = 0;
  1836.   ltc_jam_start_time = 0;
  1837.  
  1838. }
  1839.  
  1840. /*
  1841.  * To jam LTC:
  1842.  *
  1843.  * call ltc_gen_begin_jam. This (among other things) sets ltc_jamming to true so the decoder ISR
  1844.  * will begin accumulating timing data. NB: This type of background jamming starts
  1845.  * happening on reception of good code, because ltc_decoder_init calls ltc_gen_begin_jam, and
  1846.  * ltc_desync calls ltc_decoder_init so we're set up to go the second we sync again.
  1847.  *
  1848.  * When the jam timing is done, ltc_jamming is set to false but ltc_framecount will contain
  1849.  * the number of frames in the jam period. When ltc_event_poller sees ltc_frametime_now != 0,
  1850.  * it calls new_frame, and the combination of ltc_jamming==false and a full ltc_framecount will
  1851.  * be interpreted as indicating the jam timing is complete and generate a subsequent call to
  1852.  * ltc_calc_gen_constants.
  1853.  *  
  1854.  * To update the generator constants again, call ltc_gen_begin_jam and wait until framecount ==
  1855.  * requested jam period and jamming is false.
  1856.  *
  1857.  * When you want to actually start outputting jammed code, put the start timecode in
  1858.  * ltc_gen_tc_working, possibly something like this:
  1859.  *
  1860.  * ltc_gen_tc_working = ltc_timecode_current;
  1861.  *
  1862.  * That TC will be incremented once by setup_next_frame() before it's output, so bear that in mind.
  1863.  *
  1864.  * At an appropriate instant, turn off the analog comparator+timer capture interrupt, turn on CTC mode, turn on output
  1865.  * pin toggling, zero the timer and get a new value for it from ltc_gen_get_next_transition. Set that
  1866.  * to be the CTC mode trip point, and in a new ISR keep calling ltc_gen_get_next_transition about 110
  1867.  * times a frame.
  1868.  *
  1869.  * Be careful about the fact that CTC mode seems to go 1 sysclk longer than you'd think.
  1870.  *
  1871.  * When ltc_gen_get_next_transition hits the end of a frame, it flips wptr/rptr on the assumption
  1872.  * that the other buffer, pointed to by wptr, has had new frame data packed into it. It then sets
  1873.  * ltc_gen_needs_frame_data to true.
  1874.  *
  1875.  * ltc_event_poll will read ltc_gen_needs_frame_data and call
  1876.  * ltc_gen_setup_next_frame() as required. This works on the wptr, which is not currently
  1877.  * being used by anyone.
  1878.  *
  1879.  * Repeat until wrap.
  1880.  *
  1881.  */
  1882.  
  1883. // ******************************************
  1884. //
  1885. // SPI stuff
  1886. //
  1887. // ******************************************
  1888.  
  1889. bool spi_started = false; // Just used to squelch the "glitch" message on startup
  1890.  
  1891. typedef struct{
  1892.  
  1893.   uint8_t pin;
  1894.   volatile uint8_t *port;
  1895.   volatile uint8_t *ddr;
  1896.   bool activeHigh;
  1897.  
  1898. }spi_device;
  1899.  
  1900. // Declare SPI devices for this project:
  1901. // Syntax: pin on port, port, active hi/low
  1902. // Each SPI device also needs a uint8_t called something like SPI_DEVICE_WHATEVER identifying the order
  1903. // in which it appears here.
  1904.  
  1905. // Where is the hardware connected?
  1906.  
  1907. spi_device spi_devices[] = {
  1908.  {
  1909.    .pin = NRF_CSN_PIN,
  1910.    .port = &NRF_PORT,
  1911.    .ddr = &NRF_PORT_DIR,
  1912.    .activeHigh = false
  1913.  },
  1914.  {
  1915.    .pin = DSPLY_CS_PIN,
  1916.    .port = &DSPLY_PORT,
  1917.    .ddr = &DSPLY_PORT_DIR,
  1918.    .activeHigh = true
  1919.  }
  1920. };
  1921.  
  1922. uint8_t spi_currently_selected = 255;
  1923.  
  1924. void spi_init(){
  1925.  
  1926.   // Set /SS, MOSI and SCK as output
  1927.   // /SS is PB2, MOSI is PB3, SCK is PB5
  1928.   // NB most applications will also need at least a chip select set as output
  1929.  
  1930.   DDRB |= (1<<DDB5) | (1<<DDB3) | (1<<DDB2);
  1931.  
  1932.   // Set SPE (SPI Enable) and MSTR (use clock rate/16) of the SPCR register
  1933.  
  1934.   // Go fairly fast. This yields an SPI clock of 1MHz at F_CPU 16MHz.
  1935.  
  1936.   // SPCR |= (1<<SPE) | (1<<MSTR) | (1<<SPR0);
  1937.  
  1938.   // Go really fast; SPI clock is 8MHz at F_CPU 16MHz. Does this work with the nRF?
  1939.  
  1940.   SPCR |= (1<<SPE) | (1<<MSTR);
  1941.   SPSR |= (1<<SPI2X);
  1942.  
  1943.   // Do not enable SPI interrupt, since we're only supporting master mode operation
  1944.  
  1945.   // Prepare chip select pins and ports for the required IO work
  1946.  
  1947.   for(uint8_t i = 0; i < sizeof(spi_devices) / sizeof(spi_device); i++){
  1948.     spi_devices[i].pin = (1<<spi_devices[i].pin); // Convert it to a bitmask as that's how we'll always use it.
  1949.     *spi_devices[i].ddr |= spi_devices[i].pin;
  1950.   }
  1951.  
  1952. }
  1953.  
  1954. // FIXME: Make async? At least optionally, for non timing critical stuff?
  1955.  
  1956. uint8_t spi_transact(uint8_t data){ // Single bytes
  1957.  
  1958.   SPDR = data;
  1959.   while(!(SPSR & (1<<SPIF)));
  1960.   return SPDR;
  1961.  
  1962. }
  1963.  
  1964. void spi_transact(uint8_t * data, uint8_t len, uint8_t* response){ // Multi bytes
  1965.   for(uint8_t i = 0; i < len; i++){
  1966.     response[i] = spi_transact(data[i]);
  1967.   }
  1968. }
  1969.  
  1970. void spi_select(uint8_t dev){
  1971.  
  1972.   if(spi_currently_selected != 255){
  1973.    
  1974.     uart_sendl("Glitch. Attempted to select SPI device when already selected.");
  1975.     return;
  1976.   }
  1977.  
  1978.   if(spi_devices[dev].activeHigh){
  1979.     *spi_devices[dev].port |= spi_devices[dev].pin;
  1980.   } else {
  1981.     *spi_devices[dev].port &= ~spi_devices[dev].pin;
  1982.   }
  1983.  
  1984.   spi_currently_selected = dev;
  1985.  
  1986. }
  1987.  
  1988. void spi_deselect(){
  1989.  
  1990.   if(spi_currently_selected == 255 && spi_started == true){
  1991.     uart_sendl("Glitch. Attempted to deselect SPI device when none selected.");
  1992.     return;
  1993.   }
  1994.   spi_started = true;
  1995.   if(spi_devices[spi_currently_selected].activeHigh){
  1996.     *spi_devices[spi_currently_selected].port &= ~spi_devices[spi_currently_selected].pin;
  1997.   } else {
  1998.     *spi_devices[spi_currently_selected].port |= spi_devices[spi_currently_selected].pin;
  1999.   }
  2000.  
  2001.   spi_currently_selected = 255;
  2002.  
  2003. }
  2004.  
  2005. int main(void){
  2006.  
  2007.   uart_init();
  2008.   spi_init();
  2009.   nrf_init();
  2010.  
  2011.   //nrf_read_status(); // This uses a crapton of RAM for all the strings
  2012.   display_init();
  2013.   ltc_init();
  2014.   sei();
  2015.   while(1){
  2016.     uart_async_send_poll();
  2017.     ltc_event_poll();
  2018.   }
  2019. }
  2020.  
  2021. // Prints out a load of status information about the nRF24L01 attached.
  2022.  
  2023. void nrf_read_status(){
  2024.  
  2025.   uint8_t gpreg; // General-purpose variable to hold registers we won't need twice
  2026.   uart_sendl("nRF24L01 configuration\r\n");
  2027.  
  2028.   uart_sendl("  Radio setup:");
  2029.  
  2030.   uart_send("    Freq: ");
  2031.   gpreg = nrf_getreg(RF_CH);
  2032.   int freq = gpreg + 2400;
  2033.   uart_send(freq);
  2034.   uart_send("MHz; ");
  2035.   uint8_t configRegister = nrf_getreg(CONFIG);
  2036.   gpreg = nrf_getreg(RF_SETUP);
  2037.   uart_send("; RF output: ");
  2038.   uart_send(18 - (((gpreg & 0x06) >> 1) * 6)); // 00 = -18, 01 = -12, 10 = 06, 11 = 0.
  2039.   uart_send("dBm; ");
  2040.   uart_send("Mode: ");
  2041.   uart_send(configRegister & (1 << PRIM_RX) ? "RX; " : "TX; ");
  2042.   uart_send("\r\n    TX addr: ");
  2043.   uint8_t txaddr[5];
  2044.   nrf_getreg(TX_ADDR, 5, txaddr);
  2045.   uart_send(txaddr, 5);
  2046.   uart_send("\r\n    RX addr P0: ");
  2047.   nrf_getreg(RX_ADDR_P0, 5, txaddr);
  2048.   uart_send(txaddr, 5);
  2049.   uart_send("\r\n    (XP) RF ambient >-64dBm: ");
  2050.   uart_send(nrf_getreg(RPD) & 0x1); // RPD will be 1 if there's >-64dBm of signal at this freq
  2051.   uart_send("; Radio power-up: ");
  2052.   uart_send(configRegister & 1<<PWR_UP ? 1 : 0);
  2053.   uart_send("; Bitrate: ");
  2054.   if(gpreg & 1 << RF_DR_LOW){
  2055.     uart_send("250Kbps");
  2056.   } else {
  2057.     if(gpreg & 1 << RF_DR_HIGH){
  2058.       uart_send("2Mbps");
  2059.     } else {
  2060.       uart_send("1Mbps");
  2061.     }
  2062.   }
  2063.   uart_send("; TX carrier?: ");
  2064.   uart_send(gpreg & 1 << CONT_WAVE ? 1 : 0);
  2065.   uart_sendl("");
  2066.  
  2067.  
  2068.   gpreg = nrf_getreg(OBSERVE_TX);
  2069.   uart_send("    Total lost pkts: ");
  2070.   uart_send((int)(gpreg >> 4));// Get the upper 4 bits, 7:4
  2071.   uart_send("; Retransmitted this pkt: ");
  2072.   uart_send((int)(gpreg & 0xF));// Get the lower 4 bits, 3:0
  2073.  
  2074.   uart_sendl("\r\n\r\n  Packet configuration:");
  2075.  
  2076.   uart_send("    Use CRC: ");
  2077.   uart_send(configRegister & 1<<PWR_UP ? 1 : 0);
  2078.   uart_send("; CRC len: ");
  2079.   uart_send(configRegister & 1 << CRCO ? "2 " : "1 ");
  2080.   uart_send("; IRQ masked? RX_DR ");
  2081.   uart_send(configRegister & 1<<MASK_RX_DR ? 1 : 0);
  2082.   uart_send("; TX_DS ");
  2083.   uart_send(configRegister & 1<<MASK_TX_DS ? 1 : 0);
  2084.   uart_send("; MAX_RT: ");
  2085.   uart_send(configRegister & 1<<MASK_MAX_RT ? 1 : 0);
  2086.   uart_sendl("");
  2087.  
  2088.   gpreg = nrf_getreg(SETUP_RETR);
  2089.   uart_send("    Retry delay: ");
  2090.   uart_send((int)(((gpreg >> 4)+1) * 250));// Get the upper 4 bits, 7:4 in nordic nomenclature; 250ms per code value
  2091.   uart_send("us; max retries: ");
  2092.   uart_send(gpreg & 0xF); // Get the lower 4 bits; this represents the 0-16 retry count directly.
  2093.   uart_send("; Addr len: ");
  2094.   uart_send(nrf_getreg(SETUP_AW) + 2);
  2095.   uart_send(" bytes; ");
  2096.  
  2097.   gpreg = nrf_getreg(FEATURE);
  2098.   uart_send("\r\n    Enable dyn payload len: ");
  2099.   uart_send(gpreg & 1<<EN_DPL ? 1 : 0);
  2100.   uart_send("; Enable acknowledge payload:  ");
  2101.   uart_send(gpreg & 1<<EN_ACK_PAY ? 1 : 0);
  2102.   uart_send("; Enable tx of no-ack pkts: ");
  2103.   uart_send(gpreg & 1<<EN_DYN_ACK ? 1 : 0);
  2104.  
  2105.   uart_sendl("\r\n");
  2106.  
  2107.   uart_sendl("  Current status:");
  2108.   gpreg = nrf_getreg(STATUS);
  2109.   uart_send("    RX Data Rdy: ");
  2110.   uart_send(gpreg & 1<<RX_DR ? 1 : 0);
  2111.   uart_send("; Pkt Ackn'd: ");
  2112.   uart_send(gpreg & 1<<TX_DS ? 1 : 0);
  2113.   uart_send("; TX fifo full: ");
  2114.   uart_send(gpreg & 1<<TX_FULL ? 1 : 0);
  2115.   uart_send("\r\n    Data avail on pipe: ");
  2116.     uint8_t rxPVal = (gpreg & 0xE)>>1;
  2117.   if(rxPVal > 6){
  2118.     uart_sendl("None");  
  2119.   } else {
  2120.     uart_sendl(rxPVal);
  2121.   }
  2122.  
  2123.   gpreg = nrf_getreg(FIFO_STATUS);
  2124.  
  2125.   uart_send("    Reuse TX payload: ");
  2126.   uart_send(gpreg & 1<<TX_REUSE ? 1 : 0);
  2127.   uart_send("; TX fifo full: ");
  2128.   uart_send(gpreg & 1<<FIFO_FULL ? 1 : 0);
  2129.   uart_send("; TX fifo empty: ");
  2130.   uart_send(gpreg & 1<<TX_EMPTY ? 1 : 0);
  2131.   uart_send("; RX fifo full: ");
  2132.   uart_send(gpreg & 1<<RX_FULL ? 1 : 0);
  2133.   uart_send("; RX fifo empty: ");
  2134.   uart_send(gpreg & 1<<RX_EMPTY ? 1 : 0);
  2135.   uart_sendl("");
  2136.  
  2137.   uint8_t enaa = nrf_getreg(EN_AA);
  2138.   uint8_t enrxaddr = nrf_getreg(EN_RXADDR);
  2139.   uint8_t enDynPlLen = nrf_getreg(DYNPD);
  2140.  
  2141.   uart_sendl("\r\n  Per-pipe configuration:\r\n\tRX_ADDR\tEN_AA\tERX\tDPL\tRX_PW");
  2142.  
  2143.   for(uint8_t i = 0; i < 6; i++){
  2144.     uart_send("    ");
  2145.     uart_send(i);
  2146.     uart_send(":\t");
  2147.     uart_send_hex(nrf_getreg(RX_ADDR_P0 + i));
  2148.     uart_send("\t");
  2149.     uart_send(enaa & 1<<i ? 1 : 0);
  2150.     uart_send("\t");
  2151.     uart_send(enrxaddr & 1<<i ? 1 : 0);
  2152.     uart_send("\t");
  2153.     uart_send(enDynPlLen & 1<<i ? 1 : 0);
  2154.     uart_send("\t");
  2155.     uart_sendl(nrf_getreg(RX_PW_P0 + i));
  2156.   }
  2157.   uart_sendl("\r\nEnd of nRF24L01 configuration\r\n");
  2158.  
  2159. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement