Advertisement
Cookins

Untitled

Mar 31st, 2018
198
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 27.46 KB | None | 0 0
  1. sketch from author
  2. http://www.diygoodies.org.ua/?p=1540
  3. // RF22.cpp
  4. //
  5. // Copyright (C) 2011 Mike McCauley
  6. // $Id: RF22.cpp,v 1.19 2014/04/01 05:06:44 mikem Exp mikem $
  7.  
  8. #include <RF22.h>
  9. #if defined MPIDE
  10. #include <peripheral/int.h>
  11. #define memcpy_P memcpy
  12. #define ATOMIC_BLOCK_START unsigned int __status = INTDisableInterrupts(); {
  13. #define ATOMIC_BLOCK_END } INTRestoreInterrupts(__status);
  14. #elif defined ARDUINO
  15. #define ATOMIC_BLOCK_START noInterrupts()
  16. #define ATOMIC_BLOCK_END interrupts()
  17. /*#include <util/atomic.h>
  18. #define ATOMIC_BLOCK_START     ATOMIC_BLOCK(ATOMIC_RESTORESTATE) {
  19. #define ATOMIC_BLOCK_END }*/
  20. #endif
  21.  
  22. // Interrupt vectors for the 2 Arduino interrupt pins
  23. // Each interrupt can be handled by a different instance of RF22, allowing you to have
  24. // 2 RF22s per Arduino
  25. RF22* RF22::_RF22ForInterrupt[RF22_NUM_INTERRUPTS] = {0, 0, 0};
  26.  
  27. // These are indexed by the values of ModemConfigChoice
  28. // Canned modem configurations generated with
  29. // http://www.hoperf.com/upload/rf/RF22B%2023B%2031B%2042B%2043B%20Register%20Settings_RevB1-v5.xls
  30. // Stored in flash (program) memory to save SRAM
  31. PROGMEM static const RF22::ModemConfig MODEM_CONFIG_TABLE[] =
  32. {
  33.    { 0x2b, 0x03, 0xf4, 0x20, 0x41, 0x89, 0x00, 0x36, 0x40, 0x0a, 0x1d, 0x80, 0x60, 0x10, 0x62, 0x2c, 0x00, 0x08 }, // Unmodulated carrier
  34.    { 0x2b, 0x03, 0xf4, 0x20, 0x41, 0x89, 0x00, 0x36, 0x40, 0x0a, 0x1d, 0x80, 0x60, 0x10, 0x62, 0x2c, 0x33, 0x08 }, // FSK, PN9 random modulation, 2, 5
  35.  
  36.    // All the following enable FIFO with reg 71
  37.    //  1c,   1f,   20,   21,   22,   23,   24,   25,   2c,   2d,   2e,   58,   69,   6e,   6f,   70,   71,   72
  38.    // FSK, No Manchester, Max Rb err <1%, Xtal Tol 20ppm
  39.    { 0x2b, 0x03, 0xf4, 0x20, 0x41, 0x89, 0x00, 0x36, 0x40, 0x0a, 0x1d, 0x80, 0x60, 0x10, 0x62, 0x2c, 0x22, 0x08 }, // 2, 5
  40.    { 0x1b, 0x03, 0x41, 0x60, 0x27, 0x52, 0x00, 0x07, 0x40, 0x0a, 0x1e, 0x80, 0x60, 0x13, 0xa9, 0x2c, 0x22, 0x3a }, // 2.4, 36
  41.    { 0x1d, 0x03, 0xa1, 0x20, 0x4e, 0xa5, 0x00, 0x13, 0x40, 0x0a, 0x1e, 0x80, 0x60, 0x27, 0x52, 0x2c, 0x22, 0x48 }, // 4.8, 45
  42.    { 0x1e, 0x03, 0xd0, 0x00, 0x9d, 0x49, 0x00, 0x45, 0x40, 0x0a, 0x20, 0x80, 0x60, 0x4e, 0xa5, 0x2c, 0x22, 0x48 }, // 9.6, 45
  43.    { 0x2b, 0x03, 0x34, 0x02, 0x75, 0x25, 0x07, 0xff, 0x40, 0x0a, 0x1b, 0x80, 0x60, 0x9d, 0x49, 0x2c, 0x22, 0x0f }, // 19.2, 9.6
  44.    { 0x02, 0x03, 0x68, 0x01, 0x3a, 0x93, 0x04, 0xd5, 0x40, 0x0a, 0x1e, 0x80, 0x60, 0x09, 0xd5, 0x0c, 0x22, 0x1f }, // 38.4, 19.6
  45.    { 0x06, 0x03, 0x45, 0x01, 0xd7, 0xdc, 0x07, 0x6e, 0x40, 0x0a, 0x2d, 0x80, 0x60, 0x0e, 0xbf, 0x0c, 0x22, 0x2e }, // 57.6. 28.8
  46.    { 0x8a, 0x03, 0x60, 0x01, 0x55, 0x55, 0x02, 0xad, 0x40, 0x0a, 0x50, 0x80, 0x60, 0x20, 0x00, 0x0c, 0x22, 0xc8 }, // 125, 125
  47.  
  48.    { 0x2b, 0x03, 0xa1, 0xe0, 0x10, 0xc7, 0x00, 0x09, 0x40, 0x0a, 0x1d,  0x80, 0x60, 0x04, 0x32, 0x2c, 0x22, 0x04 }, // 512 baud, FSK, 2.5 Khz fd for POCSAG compatibility
  49.    { 0x27, 0x03, 0xa1, 0xe0, 0x10, 0xc7, 0x00, 0x06, 0x40, 0x0a, 0x1d,  0x80, 0x60, 0x04, 0x32, 0x2c, 0x22, 0x07 }, // 512 baud, FSK, 4.5 Khz fd for POCSAG compatibility
  50.  
  51.    // GFSK, No Manchester, Max Rb err <1%, Xtal Tol 20ppm
  52.    // These differ from FSK only in register 71, for the modulation type
  53.    { 0x2b, 0x03, 0xf4, 0x20, 0x41, 0x89, 0x00, 0x36, 0x40, 0x0a, 0x1d, 0x80, 0x60, 0x10, 0x62, 0x2c, 0x23, 0x08 }, // 2, 5
  54.    { 0x1b, 0x03, 0x41, 0x60, 0x27, 0x52, 0x00, 0x07, 0x40, 0x0a, 0x1e, 0x80, 0x60, 0x13, 0xa9, 0x2c, 0x23, 0x3a }, // 2.4, 36
  55.    { 0x1d, 0x03, 0xa1, 0x20, 0x4e, 0xa5, 0x00, 0x13, 0x40, 0x0a, 0x1e, 0x80, 0x60, 0x27, 0x52, 0x2c, 0x23, 0x48 }, // 4.8, 45
  56.    { 0x1e, 0x03, 0xd0, 0x00, 0x9d, 0x49, 0x00, 0x45, 0x40, 0x0a, 0x20, 0x80, 0x60, 0x4e, 0xa5, 0x2c, 0x23, 0x48 }, // 9.6, 45
  57.    { 0x2b, 0x03, 0x34, 0x02, 0x75, 0x25, 0x07, 0xff, 0x40, 0x0a, 0x1b, 0x80, 0x60, 0x9d, 0x49, 0x2c, 0x23, 0x0f }, // 19.2, 9.6
  58.    { 0x02, 0x03, 0x68, 0x01, 0x3a, 0x93, 0x04, 0xd5, 0x40, 0x0a, 0x1e, 0x80, 0x60, 0x09, 0xd5, 0x0c, 0x23, 0x1f }, // 38.4, 19.6
  59.    { 0x06, 0x03, 0x45, 0x01, 0xd7, 0xdc, 0x07, 0x6e, 0x40, 0x0a, 0x2d, 0x80, 0x60, 0x0e, 0xbf, 0x0c, 0x23, 0x2e }, // 57.6. 28.8
  60.    { 0x8a, 0x03, 0x60, 0x01, 0x55, 0x55, 0x02, 0xad, 0x40, 0x0a, 0x50, 0x80, 0x60, 0x20, 0x00, 0x0c, 0x23, 0xc8 }, // 125, 125
  61.  
  62.    // OOK, No Manchester, Max Rb err <1%, Xtal Tol 20ppm
  63.    { 0x51, 0x03, 0x68, 0x00, 0x3a, 0x93, 0x01, 0x3d, 0x2c, 0x11, 0x28, 0x80, 0x60, 0x09, 0xd5, 0x2c, 0x21, 0x08 }, // 1.2, 75
  64.    { 0xc8, 0x03, 0x39, 0x20, 0x68, 0xdc, 0x00, 0x6b, 0x2a, 0x08, 0x2a, 0x80, 0x60, 0x13, 0xa9, 0x2c, 0x21, 0x08 }, // 2.4, 335
  65.    { 0xc8, 0x03, 0x9c, 0x00, 0xd1, 0xb7, 0x00, 0xd4, 0x29, 0x04, 0x29, 0x80, 0x60, 0x27, 0x52, 0x2c, 0x21, 0x08 }, // 4.8, 335
  66.    { 0xb8, 0x03, 0x9c, 0x00, 0xd1, 0xb7, 0x00, 0xd4, 0x28, 0x82, 0x29, 0x80, 0x60, 0x4e, 0xa5, 0x2c, 0x21, 0x08 }, // 9.6, 335
  67.    { 0xa8, 0x03, 0x9c, 0x00, 0xd1, 0xb7, 0x00, 0xd4, 0x28, 0x41, 0x29, 0x80, 0x60, 0x9d, 0x49, 0x2c, 0x21, 0x08 }, // 19.2, 335
  68.    { 0x98, 0x03, 0x9c, 0x00, 0xd1, 0xb7, 0x00, 0xd4, 0x28, 0x20, 0x29, 0x80, 0x60, 0x09, 0xd5, 0x0c, 0x21, 0x08 }, // 38.4, 335
  69.    { 0x98, 0x03, 0x96, 0x00, 0xda, 0x74, 0x00, 0xdc, 0x28, 0x1f, 0x29, 0x80, 0x60, 0x0a, 0x3d, 0x0c, 0x21, 0x08 }, // 40, 335
  70.  
  71. };
  72.  
  73. RF22::RF22(uint8_t slaveSelectPin, uint8_t interrupt, GenericSPIClass *spi)
  74. {
  75.    _slaveSelectPin = slaveSelectPin;
  76.    _interrupt = interrupt;
  77.    _idleMode = RF22_XTON; // Default idle state is READY mode
  78.    _mode = RF22_MODE_IDLE; // We start up in idle mode
  79.    _rxGood = 0;
  80.    _rxBad = 0;
  81.    _txGood = 0;
  82.    _spi = spi;
  83.    _polynomial = CRC_16_IBM; // Historical
  84. }
  85.  
  86. boolean RF22::init()
  87. {
  88.    // Wait for RF22 POR (up to 16msec)
  89.    delay(16);
  90.  
  91.    // Initialise the slave select pin
  92.    pinMode(_slaveSelectPin, OUTPUT);
  93.    digitalWrite(_slaveSelectPin, HIGH);
  94.  
  95.    // start the SPI library:
  96.    // Note the RF22 wants mode 0, MSB first and default to 1 Mbps
  97.    _spi->begin();
  98.    _spi->setDataMode(SPI_MODE0);
  99.    _spi->setBitOrder(MSBFIRST);
  100.    _spi->setClockDivider(SPI_CLOCK_DIV128);  // (16 Mhz / 16) = 1 MHz
  101.    delay(100);
  102.  
  103.    // Software reset the device
  104.    reset();
  105.  
  106.    // Get the device type and check it
  107.    // This also tests whether we are really connected to a device
  108.    _deviceType = spiRead(RF22_REG_00_DEVICE_TYPE);
  109.    if (   _deviceType != RF22_DEVICE_TYPE_RX_TRX
  110.        && _deviceType != RF22_DEVICE_TYPE_TX)
  111. return false;
  112.  
  113.    // Set up interrupt handler
  114.    // Use FALLING instead of LOW for Uno32 compatibility, where LOW is not implemented
  115.    if (_interrupt == 0)
  116.    {
  117. _RF22ForInterrupt[0] = this;
  118. attachInterrupt(0, RF22::isr0, FALLING);
  119.    }
  120.    else if (_interrupt == 1)
  121.    {
  122. _RF22ForInterrupt[1] = this;
  123. attachInterrupt(1, RF22::isr1, FALLING);  
  124.    }
  125.    else if (_interrupt == 2)
  126.    {
  127. _RF22ForInterrupt[2] = this;
  128. attachInterrupt(2, RF22::isr2, FALLING);  
  129.    }
  130.    else
  131. return false;
  132.  
  133.    clearTxBuf();
  134.    clearRxBuf();
  135.  
  136.    // Most of these are the POR default
  137.    spiWrite(RF22_REG_7D_TX_FIFO_CONTROL2, RF22_TXFFAEM_THRESHOLD);
  138.    spiWrite(RF22_REG_7E_RX_FIFO_CONTROL,  RF22_RXFFAFULL_THRESHOLD);
  139.    spiWrite(RF22_REG_30_DATA_ACCESS_CONTROL, RF22_ENPACRX | RF22_ENPACTX | RF22_ENCRC | (_polynomial & RF22_CRC));
  140.  
  141.    // Configure the message headers
  142.    // Here we set up the standard packet format for use by the RF22 library
  143.    // 8 nibbles preamble
  144.    // 2 SYNC words 2d, d4
  145.    // Header length 4 (to, from, id, flags)
  146.    // 1 octet of data length (0 to 255)
  147.    // 0 to 255 octets data
  148.    // 2 CRC octets as CRC16(IBM), computed on the header, length and data
  149.    // On reception the to address is check for validity against RF22_REG_3F_CHECK_HEADER3
  150.    // or the broadcast address of 0xff
  151.    // If no changes are made after this, the transmitted
  152.    // to address will be 0xff, the from address will be 0xff
  153.    // and all such messages will be accepted. This permits the out-of the box
  154.    // RF22 config to act as an unaddresed, unreliable datagram service
  155.    spiWrite(RF22_REG_32_HEADER_CONTROL1, RF22_BCEN_HEADER3 | RF22_HDCH_HEADER3);
  156.    spiWrite(RF22_REG_33_HEADER_CONTROL2, RF22_HDLEN_4 | RF22_SYNCLEN_2);
  157.  
  158.    setPreambleLength(8);
  159.    uint8_t syncwords[] = { 0x2d, 0xd4 };
  160.    setSyncWords(syncwords, sizeof(syncwords));
  161.    setPromiscuous(false);
  162.    // Check the TO header against RF22_DEFAULT_NODE_ADDRESS
  163.    spiWrite(RF22_REG_3F_CHECK_HEADER3, RF22_DEFAULT_NODE_ADDRESS);
  164.    // Set the default transmit header values
  165.    setHeaderTo(RF22_DEFAULT_NODE_ADDRESS);
  166.    setHeaderFrom(RF22_DEFAULT_NODE_ADDRESS);
  167.    setHeaderId(0);
  168.    setHeaderFlags(0);
  169.  
  170.    // Ensure the antenna can be switched automatically according to transmit and receive
  171.    // This assumes GPIO0(out) is connected to TX_ANT(in) to enable tx antenna during transmit
  172.    // This assumes GPIO1(out) is connected to RX_ANT(in) to enable rx antenna during receive
  173. #if 1
  174.    spiWrite(RF22_REG_0B_GPIO_CONFIGURATION0, 0x12) ; // TX state
  175.    spiWrite(RF22_REG_0C_GPIO_CONFIGURATION1, 0x15) ; // RX state
  176. #else
  177.    // Reversed for HAB-RFM22B-BOA HAB-RFM22B-BO, also Si4432 sold by Dorji.com via Tindie.com.
  178.    spiWrite(RF22_REG_0B_GPIO_CONFIGURATION0, 0x15) ; // RX state
  179.    spiWrite(RF22_REG_0C_GPIO_CONFIGURATION1, 0x12) ; // TX state
  180. #endif
  181.  
  182.    // Enable interrupts
  183.    spiWrite(RF22_REG_05_INTERRUPT_ENABLE1, RF22_ENTXFFAEM | RF22_ENRXFFAFULL | RF22_ENPKSENT | RF22_ENPKVALID | RF22_ENCRCERROR | RF22_ENFFERR);
  184.    spiWrite(RF22_REG_06_INTERRUPT_ENABLE2, RF22_ENPREAVAL);
  185.  
  186.    // Set some defaults. An innocuous ISM frequency, and reasonable pull-in
  187.    setFrequency(434.0, 0.05);
  188. //    setFrequency(900.0);
  189.    // Some slow, reliable default speed and modulation
  190.    setModemConfig(FSK_Rb2_4Fd36);
  191.    //setModemConfig(OOK_Rb1_2Bw75);
  192.  
  193.    // Lowish power
  194.    setTxPower(RF22_TXPOW_20DBM);//RF22_TXPOW_8DBM
  195.  
  196.    return true;
  197. }
  198.  
  199. // C++ level interrupt handler for this instance
  200. void RF22::handleInterrupt()
  201. {
  202.    uint8_t _lastInterruptFlags[2];
  203.    // Read the interrupt flags which clears the interrupt
  204.    spiBurstRead(RF22_REG_03_INTERRUPT_STATUS1, _lastInterruptFlags, 2);
  205.  
  206. #if 0
  207.    // Caution: Serial printing in this interrupt routine can cause mysterious crashes
  208.    Serial.print("interrupt ");
  209.    Serial.print(_lastInterruptFlags[0], HEX);
  210.    Serial.print(" ");
  211.    Serial.println(_lastInterruptFlags[1], HEX);
  212.    if (_lastInterruptFlags[0] == 0 && _lastInterruptFlags[1] == 0)
  213. Serial.println("FUNNY: no interrupt!");
  214. #endif
  215.  
  216. #if 0
  217.    // TESTING: fake an RF22_IFFERROR
  218.    static int counter = 0;
  219.    if (_lastInterruptFlags[0] & RF22_IPKSENT && counter++ == 10)
  220.    {
  221. _lastInterruptFlags[0] = RF22_IFFERROR;
  222. counter = 0;
  223.    }
  224. #endif
  225.  
  226.    if (_lastInterruptFlags[0] & RF22_IFFERROR)
  227.    {
  228. resetFifos(); // Clears the interrupt
  229. if (_mode == RF22_MODE_TX)
  230.    restartTransmit();
  231. else if (_mode == RF22_MODE_RX)
  232.    clearRxBuf();
  233. // Serial.println("IFFERROR");  
  234.    }
  235.    // Caution, any delay here may cause a FF underflow or overflow
  236.    if (_lastInterruptFlags[0] & RF22_ITXFFAEM)
  237.    {
  238. // See if more data has to be loaded into the Tx FIFO
  239. sendNextFragment();
  240. // Serial.println("ITXFFAEM");  
  241.    }
  242.    if (_lastInterruptFlags[0] & RF22_IRXFFAFULL)
  243.    {
  244. // Caution, any delay here may cause a FF overflow
  245. // Read some data from the Rx FIFO
  246. readNextFragment();
  247. // Serial.println("IRXFFAFULL");
  248.    }
  249.    if (_lastInterruptFlags[0] & RF22_IEXT)
  250.    {
  251. // This is not enabled by the base code, but users may want to enable it
  252. handleExternalInterrupt();
  253. // Serial.println("IEXT");
  254.    }
  255.    if (_lastInterruptFlags[1] & RF22_IWUT)
  256.    {
  257. // This is not enabled by the base code, but users may want to enable it
  258. handleWakeupTimerInterrupt();
  259. // Serial.println("IWUT");
  260.    }
  261.    if (_lastInterruptFlags[0] & RF22_IPKSENT)
  262.    {
  263. // Serial.println("IPKSENT");  
  264. _txGood++;
  265. // Transmission does not automatically clear the tx buffer.
  266. // Could retransmit if we wanted
  267. // RF22 transitions automatically to Idle
  268. _mode = RF22_MODE_IDLE;
  269.    }
  270.    if (_lastInterruptFlags[0] & RF22_IPKVALID)
  271.    {
  272. uint8_t len = spiRead(RF22_REG_4B_RECEIVED_PACKET_LENGTH);
  273. // Serial.println("IPKVALID");  
  274. // Serial.println(len);  
  275. // Serial.println(_bufLen);  
  276.  
  277. // May have already read one or more fragments
  278. // Get any remaining unread octets, based on the expected length
  279. // First make sure we dont overflow the buffer in the case of a stupid length
  280. // or partial bad receives
  281. if (   len >  RF22_MAX_MESSAGE_LEN
  282.    || len < _bufLen)
  283. {
  284.    _rxBad++;
  285.    _mode = RF22_MODE_IDLE;
  286.    clearRxBuf();
  287.    return; // Hmmm receiver buffer overflow.
  288. }
  289.  
  290. spiBurstRead(RF22_REG_7F_FIFO_ACCESS, _buf + _bufLen, len - _bufLen);
  291. _rxGood++;
  292. _bufLen = len;
  293. _mode = RF22_MODE_IDLE;
  294. _rxBufValid = true;
  295.    }
  296.    if (_lastInterruptFlags[0] & RF22_ICRCERROR)
  297.    {
  298. // Serial.println("ICRCERR");  
  299. _rxBad++;
  300. clearRxBuf();
  301. resetRxFifo();
  302. _mode = RF22_MODE_IDLE;
  303. setModeRx(); // Keep trying
  304.    }
  305.    if (_lastInterruptFlags[1] & RF22_IPREAVAL)
  306.    {
  307. // Serial.println("IPREAVAL");  
  308. _lastRssi = spiRead(RF22_REG_26_RSSI);
  309. resetRxFifo();
  310. clearRxBuf();
  311.    }
  312. }
  313.  
  314. // These are low level functions that call the interrupt handler for the correct
  315. // instance of RF22.
  316. // 2 interrupts allows us to have 2 different devices
  317. void RF22::isr0()
  318. {
  319.    if (_RF22ForInterrupt[0])
  320. _RF22ForInterrupt[0]->handleInterrupt();
  321. }
  322. void RF22::isr1()
  323. {
  324.    if (_RF22ForInterrupt[1])
  325. _RF22ForInterrupt[1]->handleInterrupt();
  326. }
  327. void RF22::isr2()
  328. {
  329.    if (_RF22ForInterrupt[2])
  330. _RF22ForInterrupt[2]->handleInterrupt();
  331. }
  332.  
  333. void RF22::reset()
  334. {
  335.    spiWrite(RF22_REG_07_OPERATING_MODE1, RF22_SWRES);
  336.    // Wait for it to settle
  337.    delay(1); // SWReset time is nominally 100usec
  338. }
  339.  
  340. uint8_t RF22::spiRead(uint8_t reg)
  341. {
  342.    uint8_t val;
  343.  
  344.    ATOMIC_BLOCK_START;
  345.    digitalWrite(_slaveSelectPin, LOW);
  346.    _spi->transfer(reg & ~RF22_SPI_WRITE_MASK); // Send the address with the write mask off
  347.    val = _spi->transfer(0); // The written value is ignored, reg value is read
  348.    digitalWrite(_slaveSelectPin, HIGH);
  349.    ATOMIC_BLOCK_END;
  350.    return val;
  351. }
  352.  
  353. void RF22::spiWrite(uint8_t reg, uint8_t val)
  354. {
  355.    ATOMIC_BLOCK_START;
  356.    digitalWrite(_slaveSelectPin, LOW);
  357.    _spi->transfer(reg | RF22_SPI_WRITE_MASK); // Send the address with the write mask on
  358.    _spi->transfer(val); // New value follows
  359.    digitalWrite(_slaveSelectPin, HIGH);
  360.    ATOMIC_BLOCK_END;
  361. }
  362.  
  363. void RF22::spiBurstRead(uint8_t reg, uint8_t* dest, uint8_t len)
  364. {
  365.    ATOMIC_BLOCK_START;
  366.    digitalWrite(_slaveSelectPin, LOW);
  367.    _spi->transfer(reg & ~RF22_SPI_WRITE_MASK); // Send the start address with the write mask off
  368.    while (len--)
  369. *dest++ = _spi->transfer(0);
  370.    digitalWrite(_slaveSelectPin, HIGH);
  371.    ATOMIC_BLOCK_END;
  372. }
  373.  
  374. void RF22::spiBurstWrite(uint8_t reg, const uint8_t* src, uint8_t len)
  375. {
  376.    ATOMIC_BLOCK_START;
  377.    digitalWrite(_slaveSelectPin, LOW);
  378.    _spi->transfer(reg | RF22_SPI_WRITE_MASK); // Send the start address with the write mask on
  379.    while (len--)
  380. _spi->transfer(*src++);
  381.    digitalWrite(_slaveSelectPin, HIGH);
  382.    ATOMIC_BLOCK_END;
  383. }
  384.  
  385. uint8_t RF22::statusRead()
  386. {
  387.    return spiRead(RF22_REG_02_DEVICE_STATUS);
  388. }
  389.  
  390. uint8_t RF22::adcRead(uint8_t adcsel,
  391.                      uint8_t adcref ,
  392.                      uint8_t adcgain,
  393.                      uint8_t adcoffs)
  394. {
  395.    uint8_t configuration = adcsel | adcref | (adcgain & RF22_ADCGAIN);
  396.    spiWrite(RF22_REG_0F_ADC_CONFIGURATION, configuration | RF22_ADCSTART);
  397.    spiWrite(RF22_REG_10_ADC_SENSOR_AMP_OFFSET, adcoffs);
  398.  
  399.    // Conversion time is nominally 305usec
  400.    // Wait for the DONE bit
  401.    while (!(spiRead(RF22_REG_0F_ADC_CONFIGURATION) & RF22_ADCDONE))
  402. ;
  403.    // Return the value  
  404.    return spiRead(RF22_REG_11_ADC_VALUE);
  405. }
  406.  
  407. uint8_t RF22::temperatureRead(uint8_t tsrange, uint8_t tvoffs)
  408. {
  409.    spiWrite(RF22_REG_12_TEMPERATURE_SENSOR_CALIBRATION, tsrange | RF22_ENTSOFFS);
  410.    spiWrite(RF22_REG_13_TEMPERATURE_VALUE_OFFSET, tvoffs);
  411.    return adcRead(RF22_ADCSEL_INTERNAL_TEMPERATURE_SENSOR | RF22_ADCREF_BANDGAP_VOLTAGE);
  412. }
  413.  
  414. uint16_t RF22::wutRead()
  415. {
  416.    uint8_t buf[2];
  417.    spiBurstRead(RF22_REG_17_WAKEUP_TIMER_VALUE1, buf, 2);
  418.    return ((uint16_t)buf[0] << 8) | buf[1]; // Dont rely on byte order
  419. }
  420.  
  421. // RFM-22 doc appears to be wrong: WUT for wtm = 10000, r, = 0, d = 0 is about 1 sec
  422. void RF22::setWutPeriod(uint16_t wtm, uint8_t wtr, uint8_t wtd)
  423. {
  424.    uint8_t period[3];
  425.  
  426.    period[0] = ((wtr & 0xf) << 2) | (wtd & 0x3);
  427.    period[1] = wtm >> 8;
  428.    period[2] = wtm & 0xff;
  429.    spiBurstWrite(RF22_REG_14_WAKEUP_TIMER_PERIOD1, period, sizeof(period));
  430. }
  431.  
  432. // Returns true if centre + (fhch * fhs) is within limits
  433. // Caution, different versions of the RF22 support different max freq
  434. // so YMMV
  435. boolean RF22::setFrequency(float centre, float afcPullInRange)
  436. {
  437.    uint8_t fbsel = RF22_SBSEL;
  438.    uint8_t afclimiter;
  439.    if (centre < 240.0 || centre > 960.0) // 930.0 for early silicon
  440. return false;
  441.    if (centre >= 480.0)
  442.    {
  443. if (afcPullInRange < 0.0 || afcPullInRange > 0.318750)
  444.    return false;
  445. centre /= 2;
  446. fbsel |= RF22_HBSEL;
  447. afclimiter = afcPullInRange * 1000000.0 / 1250.0;
  448.    }
  449.    else
  450.    {
  451. if (afcPullInRange < 0.0 || afcPullInRange > 0.159375)
  452.    return false;
  453. afclimiter = afcPullInRange * 1000000.0 / 625.0;
  454.    }
  455.    centre /= 10.0;
  456.    float integerPart = floor(centre);
  457.    float fractionalPart = centre - integerPart;
  458.  
  459.    uint8_t fb = (uint8_t)integerPart - 24; // Range 0 to 23
  460.    fbsel |= fb;
  461.    uint16_t fc = fractionalPart * 64000;
  462.    spiWrite(RF22_REG_73_FREQUENCY_OFFSET1, 0);  // REVISIT
  463.    spiWrite(RF22_REG_74_FREQUENCY_OFFSET2, 0);
  464.    spiWrite(RF22_REG_75_FREQUENCY_BAND_SELECT, fbsel);
  465.    spiWrite(RF22_REG_76_NOMINAL_CARRIER_FREQUENCY1, fc >> 8);
  466.    spiWrite(RF22_REG_77_NOMINAL_CARRIER_FREQUENCY0, fc & 0xff);
  467.    spiWrite(RF22_REG_2A_AFC_LIMITER, afclimiter);
  468.    return !(statusRead() & RF22_FREQERR);
  469. }
  470.  
  471. // Step size in 10kHz increments
  472. // Returns true if centre + (fhch * fhs) is within limits
  473. boolean RF22::setFHStepSize(uint8_t fhs)
  474. {
  475.    spiWrite(RF22_REG_7A_FREQUENCY_HOPPING_STEP_SIZE, fhs);
  476.    return !(statusRead() & RF22_FREQERR);
  477. }
  478.  
  479. // Adds fhch * fhs to centre frequency
  480. // Returns true if centre + (fhch * fhs) is within limits
  481. boolean RF22::setFHChannel(uint8_t fhch)
  482. {
  483.    spiWrite(RF22_REG_79_FREQUENCY_HOPPING_CHANNEL_SELECT, fhch);
  484.    return !(statusRead() & RF22_FREQERR);
  485. }
  486.  
  487. uint8_t RF22::rssiRead()
  488. {
  489.    return spiRead(RF22_REG_26_RSSI);
  490. }
  491.  
  492. uint8_t RF22::ezmacStatusRead()
  493. {
  494.    return spiRead(RF22_REG_31_EZMAC_STATUS);
  495. }
  496.  
  497. void RF22::setMode(uint8_t mode)
  498. {
  499.    spiWrite(RF22_REG_07_OPERATING_MODE1, mode);
  500. }
  501.  
  502. void RF22::setModeIdle()
  503. {
  504.    if (_mode != RF22_MODE_IDLE)
  505.    {
  506. setMode(_idleMode);
  507. _mode = RF22_MODE_IDLE;
  508.    }
  509. }
  510.  
  511. void RF22::setModeRx()
  512. {
  513.    if (_mode != RF22_MODE_RX)
  514.    {
  515. setMode(_idleMode | RF22_RXON);
  516. _mode = RF22_MODE_RX;
  517.    }
  518. }
  519.  
  520. void RF22::setModeTx()
  521. {
  522.    if (_mode != RF22_MODE_TX)
  523.    {
  524. setMode(_idleMode | RF22_TXON);
  525. _mode = RF22_MODE_TX;
  526. // Hmmm, if you dont clear the RX FIFO here, then it appears that going
  527. // to transmit mode in the middle of a receive can corrupt the
  528. // RX FIFO
  529. resetRxFifo();
  530.    }
  531. }
  532.  
  533. uint8_t  RF22::mode()
  534. {
  535.    return _mode;
  536. }
  537.  
  538. void RF22::setTxPower(uint8_t power)
  539. {
  540.    spiWrite(RF22_REG_6D_TX_POWER, power);
  541. }
  542.  
  543. // Sets registers from a canned modem configuration structure
  544. void RF22::setModemRegisters(const ModemConfig* config)
  545. {
  546.    spiWrite(RF22_REG_1C_IF_FILTER_BANDWIDTH,                    config->reg_1c);
  547.    spiWrite(RF22_REG_1F_CLOCK_RECOVERY_GEARSHIFT_OVERRIDE,      config->reg_1f);
  548.    spiBurstWrite(RF22_REG_20_CLOCK_RECOVERY_OVERSAMPLING_RATE, &config->reg_20, 6);
  549.    spiBurstWrite(RF22_REG_2C_OOK_COUNTER_VALUE_1,              &config->reg_2c, 3);
  550.    spiWrite(RF22_REG_58_CHARGE_PUMP_CURRENT_TRIMMING,           config->reg_58);
  551.    spiWrite(RF22_REG_69_AGC_OVERRIDE1,                          config->reg_69);
  552.    spiBurstWrite(RF22_REG_6E_TX_DATA_RATE1,                    &config->reg_6e, 5);
  553. }
  554.  
  555. // Set one of the canned FSK Modem configs
  556. // Returns true if its a valid choice
  557. boolean RF22::setModemConfig(ModemConfigChoice index)
  558. {
  559.    if (index > (sizeof(MODEM_CONFIG_TABLE) / sizeof(ModemConfig)))
  560.        return false;
  561.  
  562.    RF22::ModemConfig cfg;
  563.    memcpy_P(&cfg, &MODEM_CONFIG_TABLE[index], sizeof(RF22::ModemConfig));
  564.    setModemRegisters(&cfg);
  565.  
  566.    return true;
  567. }
  568.  
  569. // REVISIT: top bit is in Header Control 2 0x33
  570. void RF22::setPreambleLength(uint8_t nibbles)
  571. {
  572.    spiWrite(RF22_REG_34_PREAMBLE_LENGTH, nibbles);
  573. }
  574.  
  575. // Caution doesnt set sync word len in Header Control 2 0x33
  576. void RF22::setSyncWords(const uint8_t* syncWords, uint8_t len)
  577. {
  578.    spiBurstWrite(RF22_REG_36_SYNC_WORD3, syncWords, len);
  579. }
  580.  
  581. void RF22::clearRxBuf()
  582. {
  583.    ATOMIC_BLOCK_START;
  584.    _bufLen = 0;
  585.    _rxBufValid = false;
  586.    ATOMIC_BLOCK_END;
  587. }
  588.  
  589. boolean RF22::available()
  590. {
  591.    if (!_rxBufValid)
  592. setModeRx(); // Make sure we are receiving
  593.    return _rxBufValid;
  594. }
  595.  
  596. // Blocks until a valid message is received
  597. void RF22::waitAvailable()
  598. {
  599.    while (!available())
  600. ;
  601. }
  602.  
  603. // Blocks until a valid message is received or timeout expires
  604. // Return true if there is a message available
  605. // Works correctly even on millis() rollover
  606. bool RF22::waitAvailableTimeout(uint16_t timeout)
  607. {
  608.    unsigned long starttime = millis();
  609.    while ((millis() - starttime) < timeout)
  610.        if (available())
  611.           return true;
  612.    return false;
  613. }
  614.  
  615. void RF22::waitPacketSent()
  616. {
  617.    while (_mode == RF22_MODE_TX)
  618. ; // Wait for any previous transmit to finish
  619. }
  620.  
  621. bool RF22::waitPacketSent(uint16_t timeout)
  622. {
  623.    unsigned long starttime = millis();
  624.    while ((millis() - starttime) < timeout)
  625.        if (_mode != RF22_MODE_TX) // Any previous transmit finished?
  626.           return true;
  627.    return false;
  628. }
  629.  
  630. // Diagnostic help
  631. void RF22::printBuffer(const char* prompt, const uint8_t* buf, uint8_t len)
  632. {
  633. #ifdef RF22_HAVE_SERIAL
  634.    uint8_t i;
  635.  
  636.    Serial.println(prompt);
  637.    for (i = 0; i < len; i++)
  638.    {
  639. if (i % 16 == 15)
  640.    Serial.println(buf[i], HEX);
  641. else
  642. {
  643.    Serial.print(buf[i], HEX);
  644.    Serial.print(' ');
  645. }
  646.    }
  647.    Serial.println(' ');
  648. #endif
  649. }
  650.  
  651. boolean RF22::recv(uint8_t* buf, uint8_t* len)
  652. {
  653.    if (!available())
  654. return false;
  655.  
  656.    ATOMIC_BLOCK_START;
  657.    if (*len > _bufLen)
  658. *len = _bufLen;
  659.    memcpy(buf, _buf, *len);
  660.    clearRxBuf();
  661.    ATOMIC_BLOCK_END;
  662. //    printBuffer("recv:", buf, *len);
  663.    return true;
  664. }
  665.  
  666. void RF22::clearTxBuf()
  667. {
  668.    ATOMIC_BLOCK_START;
  669.    _bufLen = 0;
  670.    _txBufSentIndex = 0;
  671.    ATOMIC_BLOCK_END;
  672. }
  673.  
  674. void RF22::startTransmit()
  675. {
  676.    sendNextFragment(); // Actually the first fragment
  677.    spiWrite(RF22_REG_3E_PACKET_LENGTH, _bufLen); // Total length that will be sent
  678.    setModeTx(); // Start the transmitter, turns off the receiver
  679. }
  680.  
  681. // Restart the transmission of a packet that had a problem
  682. void RF22::restartTransmit()
  683. {
  684.    _mode = RF22_MODE_IDLE;
  685.    _txBufSentIndex = 0;
  686. //    Serial.println("Restart");
  687.    startTransmit();
  688. }
  689.  
  690. boolean RF22::send(const uint8_t* data, uint8_t len)
  691. {
  692.    boolean ret = true;
  693.    waitPacketSent();
  694.    ATOMIC_BLOCK_START;
  695.    if (!fillTxBuf(data, len))
  696. ret = false;
  697.    else
  698. startTransmit();
  699.    ATOMIC_BLOCK_END;
  700. //    printBuffer("send:", data, len);
  701.    return ret;
  702. }
  703.  
  704. boolean RF22::fillTxBuf(const uint8_t* data, uint8_t len)
  705. {
  706.    clearTxBuf();
  707.    if (!len)
  708. return false;
  709.    return appendTxBuf(data, len);
  710. }
  711.  
  712. boolean RF22::appendTxBuf(const uint8_t* data, uint8_t len)
  713. {
  714.    if (((uint16_t)_bufLen + len) > RF22_MAX_MESSAGE_LEN)
  715. return false;
  716.    ATOMIC_BLOCK_START;
  717.    memcpy(_buf + _bufLen, data, len);
  718.    _bufLen += len;
  719.    ATOMIC_BLOCK_END;
  720. //    printBuffer("txbuf:", _buf, _bufLen);
  721.    return true;
  722. }
  723.  
  724. // Assumption: there is currently <= RF22_TXFFAEM_THRESHOLD bytes in the Tx FIFO
  725. void RF22::sendNextFragment()
  726. {
  727.    if (_txBufSentIndex < _bufLen)
  728.    {
  729. // Some left to send?
  730. uint8_t len = _bufLen - _txBufSentIndex;
  731. // But dont send too much
  732. if (len > (RF22_FIFO_SIZE - RF22_TXFFAEM_THRESHOLD - 1))
  733.    len = (RF22_FIFO_SIZE - RF22_TXFFAEM_THRESHOLD - 1);
  734. spiBurstWrite(RF22_REG_7F_FIFO_ACCESS, _buf + _txBufSentIndex, len);
  735. // printBuffer("frag:", _buf  + _txBufSentIndex, len);
  736. _txBufSentIndex += len;
  737.    }
  738. }
  739.  
  740. // Assumption: there are at least RF22_RXFFAFULL_THRESHOLD in the RX FIFO
  741. // That means it should only be called after a RXFFAFULL interrupt
  742. void RF22::readNextFragment()
  743. {
  744.    if (((uint16_t)_bufLen + RF22_RXFFAFULL_THRESHOLD) > RF22_MAX_MESSAGE_LEN)
  745. return; // Hmmm receiver overflow. Should never occur
  746.  
  747.    // Read the RF22_RXFFAFULL_THRESHOLD octets that should be there
  748.    spiBurstRead(RF22_REG_7F_FIFO_ACCESS, _buf + _bufLen, RF22_RXFFAFULL_THRESHOLD);
  749.    _bufLen += RF22_RXFFAFULL_THRESHOLD;
  750. }
  751.  
  752. // Clear the FIFOs
  753. void RF22::resetFifos()
  754. {
  755.    spiWrite(RF22_REG_08_OPERATING_MODE2, RF22_FFCLRRX | RF22_FFCLRTX);
  756.    spiWrite(RF22_REG_08_OPERATING_MODE2, 0);
  757. }
  758.  
  759. // Clear the Rx FIFO
  760. void RF22::resetRxFifo()
  761. {
  762.    spiWrite(RF22_REG_08_OPERATING_MODE2, RF22_FFCLRRX);
  763.    spiWrite(RF22_REG_08_OPERATING_MODE2, 0);
  764. }
  765.  
  766. // CLear the TX FIFO
  767. void RF22::resetTxFifo()
  768. {
  769.    spiWrite(RF22_REG_08_OPERATING_MODE2, RF22_FFCLRTX);
  770.    spiWrite(RF22_REG_08_OPERATING_MODE2, 0);
  771. }
  772.  
  773. // Default implmentation does nothing. Override if you wish
  774. void RF22::handleExternalInterrupt()
  775. {
  776. }
  777.  
  778. // Default implmentation does nothing. Override if you wish
  779. void RF22::handleWakeupTimerInterrupt()
  780. {
  781. }
  782.  
  783. void RF22::setHeaderTo(uint8_t to)
  784. {
  785.    spiWrite(RF22_REG_3A_TRANSMIT_HEADER3, to);
  786. }
  787.  
  788. void RF22::setHeaderFrom(uint8_t from)
  789. {
  790.    spiWrite(RF22_REG_3B_TRANSMIT_HEADER2, from);
  791. }
  792.  
  793. void RF22::setHeaderId(uint8_t id)
  794. {
  795.    spiWrite(RF22_REG_3C_TRANSMIT_HEADER1, id);
  796. }
  797.  
  798. void RF22::setHeaderFlags(uint8_t flags)
  799. {
  800.    spiWrite(RF22_REG_3D_TRANSMIT_HEADER0, flags);
  801. }
  802.  
  803. uint8_t RF22::headerTo()
  804. {
  805.    return spiRead(RF22_REG_47_RECEIVED_HEADER3);
  806. }
  807.  
  808. uint8_t RF22::headerFrom()
  809. {
  810.    return spiRead(RF22_REG_48_RECEIVED_HEADER2);
  811. }
  812.  
  813. uint8_t RF22::headerId()
  814. {
  815.    return spiRead(RF22_REG_49_RECEIVED_HEADER1);
  816. }
  817.  
  818. uint8_t RF22::headerFlags()
  819. {
  820.    return spiRead(RF22_REG_4A_RECEIVED_HEADER0);
  821. }
  822.  
  823. uint8_t RF22::lastRssi()
  824. {
  825.    return _lastRssi;
  826. }
  827.  
  828. void RF22::setPromiscuous(boolean promiscuous)
  829. {
  830.    spiWrite(RF22_REG_43_HEADER_ENABLE3, promiscuous ? 0x00 : 0xff);
  831. }
  832.  
  833. boolean RF22::setCRCPolynomial(CRCPolynomial polynomial)
  834. {
  835.    if (polynomial >= CRC_CCITT &&
  836. polynomial <= CRC_Biacheva)
  837.    {
  838. _polynomial = polynomial;
  839. return true;
  840.    }
  841.    else
  842. return false;
  843. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement