RFM69 hat library Part4B

Transmit Basic: iwanders/plainRFM69

My first Arduino client was based on the plainRFM69 library which looks fairly lightweight (it has in memory message queues). I started by adapting the plainRFM69 “Minimal” sample.

/*
 *  Copyright (c) 2014, Ivor Wanders
 *  MIT License, see the LICENSE.md file in the root folder.
*/
#include <SPI.h>
#include <plainRFM69.h>

// slave select pin.
#define SLAVE_SELECT_PIN 10     

// connected to the reset pin of the RFM69.
#define RESET_PIN 9

// tie this pin down on the receiver.
#define SENDER_DETECT_PIN 4

/*
    This is very minimal, it does not use the interrupt.

    Using the interrupt is recommended.
*/

plainRFM69 rfm = plainRFM69(SLAVE_SELECT_PIN);

void sender(){

    uint32_t start_time = millis();

    uint32_t counter = 0; // the counter which we are going to send.

    while(true){
        rfm.poll(); // run poll as often as possible.

        if (!rfm.canSend()){
            continue; // sending is not possible, already sending.
        }
        if ((millis() - start_time) > 500){ // every 500 ms. 
            start_time = millis();

            // be a little bit verbose.
            Serial.print("Send:");Serial.println(counter);

//            rfm.dumpRegisters(Serial);

            // send the number of bytes equal to that set with setPacketLength.
            // read those bytes from memory where counter starts.
            rfm.send(&counter);
            
            counter++; // increase the counter.
        }
    }
}

void receiver(){
    uint32_t counter = 0; // to count the messages.

    while(true){

        rfm.poll(); // poll as often as possible.

        while(rfm.available()){ // for all available messages:

            uint32_t received_count = 0; // temporary for the new counter.
            uint8_t len = rfm.read(&received_count); // read the packet into the new_counter.

            // print verbose output.
            Serial.print("Packet ("); Serial.print(len); Serial.print("): "); Serial.println(received_count);

            if (counter+1 != received_count){
                // if the increment is larger than one, we lost one or more packets.
                Serial.println("Packetloss detected!");
            }

            // assign the received counter to our counter.
            counter = received_count;
        }
    }
}

void setup(){
    Serial.begin(9600);
    SPI.begin();

    bareRFM69::reset(RESET_PIN); // sent the RFM69 a hard-reset.

    rfm.setRecommended(); // set recommended paramters in RFM69.
    rfm.setPacketType(false, false); // set the used packet type.

    rfm.setBufferSize(2);   // set the internal buffer size.
    rfm.setPacketLength(4); // set the packet length.
    rfm.setFrequency((uint32_t) 915*1000*1000); // set the frequency.

    // baudrate is default, 4800 bps now.
    rfm.dumpRegisters(Serial);
    
    rfm.receive();
    // set it to receiving mode.

    pinMode(SENDER_DETECT_PIN, INPUT_PULLUP);
    delay(5);
}

void loop(){
    if (digitalRead(SENDER_DETECT_PIN) == LOW){
        Serial.println("Going Receiver!");
        receiver(); 
        // this function never returns and contains an infinite loop.
    } else {
        Serial.println("Going sender!");
        sender();
        // idem.
    }
}
Arduino RFM69HCW Client in receive mode

I added code to dump the all the Arduino Nano Radio Shield RFM69/95 registers so I could compare it with my Adafruit RFM69HCW Radio Bonnet configuration. I also modified the code to set the three frequency registers so they matched the sample values based on the calculation in the RFM69HCW datasheet. I spent a lot of time manually configuring individual registers on the Adafruit bonnet (ignoring registers like 0x24 RegRssiValue).

void bareRFM69::dumpRegisters(Stream& out)
{
  for (int i = 0; i <= 0x3d; i++) {
    out.print("0x");
    out.print(i, HEX);
    out.print(": 0x");
    out.println(this->readRegister(i), HEX);
  }
}

void plainRFM69::setFrequency(uint32_t freq){
     uint64_t frf = ((uint64_t)freq << 19) / 32000000;
    this->setFrf(frf);
}

After much “trial and error” I found that my Arduino device would only receive messages from my Windows 10 IoT Core device when a third Arduino device was transmitting.

21:10:50.819 -> 0x0: 0x0
21:10:50.819 -> 0x1: 0x4
21:10:50.852 -> 0x2: 0x0
21:10:50.852 -> 0x3: 0x1A
21:10:50.852 -> 0x4: 0xB
21:10:50.886 -> 0x5: 0x0
21:10:50.886 -> 0x6: 0x52
21:10:50.886 -> 0x7: 0xE4
21:10:50.920 -> 0x8: 0xC0
21:10:50.920 -> 0x9: 0x0
21:10:50.920 -> 0xA: 0x41
21:10:50.954 -> 0xB: 0x40
21:10:50.954 -> 0xC: 0x2
21:10:50.954 -> 0xD: 0x92
21:10:50.988 -> 0xE: 0xF5
21:10:50.988 -> 0xF: 0x20
21:10:50.988 -> 0x10: 0x24
21:10:51.022 -> 0x11: 0x9F
21:10:51.022 -> 0x12: 0x9
21:10:51.056 -> 0x13: 0x1A
21:10:51.056 -> 0x14: 0x40
21:10:51.056 -> 0x15: 0xB0
21:10:51.089 -> 0x16: 0x7B
21:10:51.089 -> 0x17: 0x9B
21:10:51.089 -> 0x18: 0x88
21:10:51.124 -> 0x19: 0x55
21:10:51.124 -> 0x1A: 0x8B
21:10:51.124 -> 0x1B: 0x40
21:10:51.157 -> 0x1C: 0x80
21:10:51.157 -> 0x1D: 0x6
21:10:51.157 -> 0x1E: 0x10
21:10:51.191 -> 0x1F: 0x0
21:10:51.191 -> 0x20: 0x0
21:10:51.191 -> 0x21: 0x0
21:10:51.226 -> 0x22: 0x0
21:10:51.226 -> 0x23: 0x2
21:10:51.226 -> 0x24: 0xFF
21:10:51.260 -> 0x25: 0x0
21:10:51.260 -> 0x26: 0x5
21:10:51.293 -> 0x27: 0x80
21:10:51.293 -> 0x28: 0x0
21:10:51.293 -> 0x29: 0xFF
21:10:51.328 -> 0x2A: 0x0
21:10:51.328 -> 0x2B: 0x0
21:10:51.328 -> 0x2C: 0x0
21:10:51.363 -> 0x2D: 0x3
21:10:51.363 -> 0x2E: 0x98
21:10:51.363 -> 0x2F: 0x1
21:10:51.363 -> 0x30: 0x1
21:10:51.397 -> 0x31: 0x1
21:10:51.397 -> 0x32: 0x1
21:10:51.397 -> 0x33: 0x0
21:10:51.432 -> 0x34: 0x0
21:10:51.432 -> 0x35: 0x0
21:10:51.466 -> 0x36: 0x0
21:10:51.466 -> 0x37: 0x50
21:10:51.466 -> 0x38: 0x4
21:10:51.500 -> 0x39: 0x0
21:10:51.500 -> 0x3A: 0x0
21:10:51.500 -> 0x3B: 0x0
21:10:51.535 -> 0x3C: 0x1
21:10:51.535 -> 0x3D: 0x0
21:10:51.535 -> Going Receiver!
21:10:51.672 -> Packet (4): 27
21:10:51.672 -> Packetloss detected!
21:10:52.151 -> Packet (4): 28
21:10:52.665 -> Packet (4): 29
21:10:53.182 -> Packet (4): 30
21:10:53.664 -> Packet (4): 31
21:10:54.665 -> Packet (4): 33
21:10:54.699 -> Packetloss detected!
21:10:55.178 -> Packet (4): 34
21:10:56.177 -> Packet (4): 36
21:10:56.177 -> Packetloss detected!
21:10:56.660 -> Packet (4): 37
21:10:57.180 -> Packet (4): 38
21:10:57.666 -> Packet (4): 39
21:10:58.151 -> Packet (4): 40
21:10:58.669 -> Packet (4): 41
21:10:59.186 -> Packet (4): 42
21:10:59.668 -> Packet (4): 43
21:11:00.191 -> Packet (4): 44
21:11:00.666 -> Packet (4): 45
21:11:01.182 -> Packet (4): 46
21:11:01.664 -> Packet (4): 47
21:11:02.183 -> Packet (4): 48
21:11:02.664 -> Packet (4): 49
21:11:03.182 -> Packet (4): 50
21:11:03.664 -> Packet (4): 51

I think the interoperability problem was caused by timing differences caused by the plainRFM69 library using AutoMode (see datasheet section 4.4) to sequence the transmit process rather than manually changing the mode etc.

AutoMode option looks promising and warrants further investigation but interoperability will be an issue.

void plainRFM69::sendPacket(void* buffer, uint8_t len){
    /*
        Just like with Receive mode, the automode is used.

        First, Rx mode is disabled by going into standby.
        Then the automode is set to start transmitting when FIFO level is above
        the thresshold, it stops transmitting after PacketSent is asserted.

        This results in a minimal Tx time and packetSent can be detected when
        automode is left again.
        
    */
    this->setMode(RFM69_MODE_SEQUENCER_ON | RFM69_MODE_STANDBY);
    this->setAutoMode(RFM69_AUTOMODE_ENTER_RISING_FIFOLEVEL, RFM69_AUTOMODE_EXIT_RISING_PACKETSENT, RFM69_AUTOMODE_INTERMEDIATEMODE_TRANSMITTER);
    // perhaps RFM69_AUTOMODE_ENTER_RISING_FIFONOTEMPTY is faster?
    
    // set it into automode for transmitting

    // p22 - Turn on the high power boost registers in transmitting mode.
    if (this->tx_power_boosted)
    {
        this->setPa13dBm1(true);
        this->setPa13dBm2(true);
    }

    // write the fifo.
    this->state = RFM69_PLAIN_STATE_SENDING; // set the state to sending.
    this->writeFIFO(buffer, len);
}

Looks like I need to investigate some of the other Arduino library options.

RFM69 hat library Part4A

Transmit Basic Client Selection

My first milestone was to get my Adafruit RFM69HCW Radio Bonnet 433/868/915MHz sending packets to a program running on an Arduino device.

On GitHub there were quite a few RFM69 libraries, many of which were “based on”/”inspired by” the library by Felix Rusu from lowerPowerLab. (I have a number of LowPwerLab devices and they are pretty robust and reliable)

https://github.com/LowPowerLab/RFM69
https://github.com/dltech/RFM69
https://github.com/UKHASnet/ukhasnet-rfm69
https://github.com/jdesbonnet/RFM69_LPC812_firmware
https://github.com/grilletjesus
https://github.com/SamClarke2012/RFM69-AVR
https://github.com/boti7/RFM69-driver
https://github.com/ahessling/RFM69-STM32
https://github.com/tanchgen/wl_light
https://github.com/floxo/rfm69
https://github.com/JohnOH/raspirf
https://github.com/jgromes/RadioLib
https://github.com/flok99/RFM69
https://github.com/noearchimede/RFM69
https://gitlab.com/sedgwickcharles/RFM69
https://github.com/j54n1n/rfm69
https://github.com/DeltaNova/RFM69W
https://github.com/shaunhey/rfm69-elster
https://github.com/ivan-kralik/rfm69
https://github.com/rasmatic
https://github.com/iwanders/plainRFM69
https://www.hoperf.com/data/upload/back/20181204/RFM69-LCD-Listen-mode-code.rar

I was looking for something like the Arduino-LoRa library by Sandeep Mistry which was a fairly lightweight wrapper for the HopeRF RFM9X family of devices. I was looking for a library that didn’t change many of the default settings, have any in memory buffering or an implementation which included retries or transmit power adjustments.

The first version of the code to send packets was based on the example in part3.

public sealed class StartupTask : IBackgroundTask
{
    private const int ChipSelectLine = 1;
    private const int ResetLine = 25;
    private Rfm69HcwDevice rfm69Device = new Rfm69HcwDevice(ChipSelectLine, ResetLine);

    const double RH_RF6M9HCW_FXOSC = 32000000.0;
    const double RH_RFM69HCW_FSTEP = RH_RF6M9HCW_FXOSC / 524288.0;

    const byte NetworkID = 100;
    const byte NodeAddressFrom = 0x03;
    const byte NodeAddressTo = 0x02;


    public void Run(IBackgroundTaskInstance taskInstance)
    {
        rfm69Device.RegisterDump();

        // regOpMode standby
        rfm69Device.RegisterWriteByte(0x01, 0b00000100);

        // BitRate MSB/LSB
        rfm69Device.RegisterWriteByte(0x03, 0x34);
        rfm69Device.RegisterWriteByte(0x04, 0x00);

        // Frequency deviation
        rfm69Device.RegisterWriteByte(0x05, 0x02);
        rfm69Device.RegisterWriteByte(0x06, 0x3d);

        // Calculate the frequency according to the datasheett
        byte[] bytes = BitConverter.GetBytes((uint)(915000000.0 / RH_RFM69HCW_FSTEP));
        Debug.WriteLine("Byte Hex 0x{0:x2} 0x{1:x2} 0x{2:x2} 0x{3:x2}", bytes[0], bytes[1], bytes[2], bytes[3]);
        rfm69Device.RegisterWriteByte(0x07, bytes[2]);
        rfm69Device.RegisterWriteByte(0x08, bytes[1]);
        rfm69Device.RegisterWriteByte(0x09, bytes[0]);

        rfm69Device.RegisterWriteByte(0x38, 0x04);

        rfm69Device.RegisterDump();

        while (true)
        {
            // Standby mode while loading message into FIFO
            rfm69Device.RegisterWriteByte(0x01, 0b00000100);
            byte[] messageBuffer = BitConverter.GetBytes((uint)0);
            rfm69Device.RegisterWrite(0x0, messageBuffer);

            // Transmit mode once FIFO loaded
            rfm69Device.RegisterWriteByte(0x01, 0b00001100);

            // Wait until send done, no timeouts in PoC
            Debug.WriteLine("Send-wait");
            byte IrqFlags = rfm69Device.RegisterReadByte(0x28); // RegIrqFlags2
            while ((IrqFlags & 0b00001000) == 0)  // wait until TxDone cleared
            {
                Task.Delay(10).Wait();
                IrqFlags = rfm69Device.RegisterReadByte(0x28); // RegIrqFlags
                Debug.Write(".");
            }
            Debug.WriteLine("");

            // Standby mode while sleeping
            rfm69Device.RegisterWriteByte(0x01, 0b00000100);
            Debug.WriteLine($"{DateTime.Now.ToShortTimeString()}Send-Done");

            Task.Delay(5000).Wait();
        }
    }
}

For testing my client device was an Easy Sensors Arduino Nano Radio Shield RFM69/95

EasySensors Arduino Nano Shield

I could see bytes getting put in the send buffer and the PacketSent bit flag in RegIrqFlags2 register was getting sent which was positive.

RFM69 hat library Part3

Initially I tried to used the RegisterManager code from my RFM9XIoTCore library but will have to make some modifications to cope with the different Reset pin timings for the RFM69HCW device and the Reset pin not being connected on the Seegle Systeme RaspyFRM.

When I first ran the test harness I found the 3 frequency registers (RegFrfMsb, RegFrfMid, RegFrfLsb) were not getting set as I expected.

RFM69HCW reset timing diagram

After re-reading the RFM69HCW datasheet I noticed “should be pulled low for a hundred microseconds”, whereas the RFM95 datasheet had “should be pulled high for a hundred microseconds”.

RFM9X Reset timing diagram

After updating the reset GPIO pin code I could successfully set the frequency to 868MHz and then read it back

Register dump
Register 0x00 - Value 0X00 - Bits 00000000
Register 0x01 - Value 0X04 - Bits 00000100
Register 0x02 - Value 0X00 - Bits 00000000
Register 0x03 - Value 0X1a - Bits 00011010
Register 0x04 - Value 0X0b - Bits 00001011
Register 0x05 - Value 0X00 - Bits 00000000
Register 0x06 - Value 0X52 - Bits 01010010
Register 0x07 - Value 0Xe4 - Bits 11100100
Register 0x08 - Value 0Xc0 - Bits 11000000
Register 0x09 - Value 0X00 - Bits 00000000
Register 0x0a - Value 0X41 - Bits 01000001
Register 0x0b - Value 0X40 - Bits 01000000
Register 0x0c - Value 0X02 - Bits 00000010
Register 0x0d - Value 0X92 - Bits 10010010
Register 0x0e - Value 0Xf5 - Bits 11110101
Register 0x0f - Value 0X20 - Bits 00100000
Register 0x10 - Value 0X24 - Bits 00100100
Register 0x11 - Value 0X9f - Bits 10011111
Register 0x12 - Value 0X09 - Bits 00001001
Register 0x13 - Value 0X1a - Bits 00011010
Register 0x14 - Value 0X40 - Bits 01000000
Register 0x15 - Value 0Xb0 - Bits 10110000
Register 0x16 - Value 0X7b - Bits 01111011
Register 0x17 - Value 0X9b - Bits 10011011
Register 0x18 - Value 0X08 - Bits 00001000
Register 0x19 - Value 0X86 - Bits 10000110
Register 0x1a - Value 0X8a - Bits 10001010
Register 0x1b - Value 0X40 - Bits 01000000
Register 0x1c - Value 0X80 - Bits 10000000
Register 0x1d - Value 0X06 - Bits 00000110
Register 0x1e - Value 0X10 - Bits 00010000
Register 0x1f - Value 0X00 - Bits 00000000
Register 0x20 - Value 0X00 - Bits 00000000
Register 0x21 - Value 0X00 - Bits 00000000
Register 0x22 - Value 0X00 - Bits 00000000
Register 0x23 - Value 0X02 - Bits 00000010
Register 0x24 - Value 0Xff - Bits 11111111
Register 0x25 - Value 0X00 - Bits 00000000
Register 0x26 - Value 0X05 - Bits 00000101
Register 0x27 - Value 0X80 - Bits 10000000
Register 0x28 - Value 0X00 - Bits 00000000
Register 0x29 - Value 0Xff - Bits 11111111
Register 0x2a - Value 0X00 - Bits 00000000
Register 0x2b - Value 0X00 - Bits 00000000
Register 0x2c - Value 0X00 - Bits 00000000
Register 0x2d - Value 0X03 - Bits 00000011
Register 0x2e - Value 0X98 - Bits 10011000
Register 0x2f - Value 0X00 - Bits 00000000
Register 0x30 - Value 0X00 - Bits 00000000
Register 0x31 - Value 0X00 - Bits 00000000
Register 0x32 - Value 0X00 - Bits 00000000
Register 0x33 - Value 0X00 - Bits 00000000
Register 0x34 - Value 0X00 - Bits 00000000
Register 0x35 - Value 0X00 - Bits 00000000
Register 0x36 - Value 0X00 - Bits 00000000
Register 0x37 - Value 0X10 - Bits 00010000
Register 0x38 - Value 0X40 - Bits 01000000
Register 0x39 - Value 0X00 - Bits 00000000
Register 0x3a - Value 0X00 - Bits 00000000
Register 0x3b - Value 0X00 - Bits 00000000
Register 0x3c - Value 0X0f - Bits 00001111
Register 0x3d - Value 0X02 - Bits 00000010
Read RegOpMode (read byte)
Reg OpMode 0x04
Byte Hex 0x00 0x00 0xd9 0x00
Register dump
Register 0x00 - Value 0X00 - Bits 00000000
Register 0x01 - Value 0X04 - Bits 00000100
Register 0x02 - Value 0X00 - Bits 00000000
Register 0x03 - Value 0X1a - Bits 00011010
Register 0x04 - Value 0X0b - Bits 00001011
Register 0x05 - Value 0X00 - Bits 00000000
Register 0x06 - Value 0X52 - Bits 01010010
Register 0x07 - Value 0Xd9 - Bits 11011001
Register 0x08 - Value 0X00 - Bits 00000000
Register 0x09 - Value 0X00 - Bits 00000000
Register 0x0a - Value 0X41 - Bits 01000001
Register 0x0b - Value 0X40 - Bits 01000000
Register 0x0c - Value 0X02 - Bits 00000010
Register 0x0d - Value 0X92 - Bits 10010010
Register 0x0e - Value 0Xf5 - Bits 11110101
Register 0x0f - Value 0X20 - Bits 00100000
Register 0x10 - Value 0X24 - Bits 00100100
Register 0x11 - Value 0X9f - Bits 10011111
Register 0x12 - Value 0X09 - Bits 00001001
Register 0x13 - Value 0X1a - Bits 00011010
Register 0x14 - Value 0X40 - Bits 01000000
Register 0x15 - Value 0Xb0 - Bits 10110000
Register 0x16 - Value 0X7b - Bits 01111011
Register 0x17 - Value 0X9b - Bits 10011011
Register 0x18 - Value 0X08 - Bits 00001000
Register 0x19 - Value 0X86 - Bits 10000110
Register 0x1a - Value 0X8a - Bits 10001010
Register 0x1b - Value 0X40 - Bits 01000000
Register 0x1c - Value 0X80 - Bits 10000000
Register 0x1d - Value 0X06 - Bits 00000110
Register 0x1e - Value 0X10 - Bits 00010000
Register 0x1f - Value 0X00 - Bits 00000000
Register 0x20 - Value 0X00 - Bits 00000000
Register 0x21 - Value 0X00 - Bits 00000000
Register 0x22 - Value 0X00 - Bits 00000000
Register 0x23 - Value 0X02 - Bits 00000010
Register 0x24 - Value 0Xff - Bits 11111111
Register 0x25 - Value 0X00 - Bits 00000000
Register 0x26 - Value 0X05 - Bits 00000101
Register 0x27 - Value 0X80 - Bits 10000000
Register 0x28 - Value 0X00 - Bits 00000000
Register 0x29 - Value 0Xff - Bits 11111111
Register 0x2a - Value 0X00 - Bits 00000000
Register 0x2b - Value 0X00 - Bits 00000000
Register 0x2c - Value 0X00 - Bits 00000000
Register 0x2d - Value 0X03 - Bits 00000011
Register 0x2e - Value 0X98 - Bits 10011000
Register 0x2f - Value 0X00 - Bits 00000000
Register 0x30 - Value 0X00 - Bits 00000000
Register 0x31 - Value 0X00 - Bits 00000000
Register 0x32 - Value 0X00 - Bits 00000000
Register 0x33 - Value 0X00 - Bits 00000000
Register 0x34 - Value 0X00 - Bits 00000000
Register 0x35 - Value 0X00 - Bits 00000000
Register 0x36 - Value 0X00 - Bits 00000000
Register 0x37 - Value 0X10 - Bits 00010000
Register 0x38 - Value 0X40 - Bits 01000000
Register 0x39 - Value 0X00 - Bits 00000000
Register 0x3a - Value 0X00 - Bits 00000000
Register 0x3b - Value 0X00 - Bits 00000000
Register 0x3c - Value 0X0f - Bits 00001111
Register 0x3d - Value 0X02 - Bits 00000010

The next step is to extract the SPI register access functionality into a module and configure the bare minimum of settings required to get the RFM69 to transmit.

RFM69 shield library Part1

Register Read

After building an RFM95 Windows 10 IoT Core C# library I wanted to see if I could source a couple of RFM69HCW hats and write another library. For some applications the RFM69HCW with the variety and number of low-power client devices available plus, its built in payload encryption and addressing make it a better option. For the RFM9X library I purchased several RM9X Raspberry PI Hats but I can only find a couple (May 2019) of suitable RFM69HCW ones.

  • Adafruit RFM69HCW Radio Bonnet 433/868/915MHz USD19.95
  • Seegel Systeme RaspyRFMII EUR17.90

I wanted a lightweight RFM69HCW library which didn’t try to hide how the chip functioned, and in the future could be configured to work with other vendors’ shields.

AdaFruit LoRa 9X/RFM69HCW Radio Bonnet
Seegel Systeme RaspyRFM-II

The first step was to build a basic universal windows platform (UWP) background task to confirm that I could reliably communicate with the AdaFruit shield over the SPI bus by reading a single register value (RegVersion the silicon version specified in the vendor datasheet).

/*
    Copyright ® 2019 May devMobile Software, All Rights Reserved
 
    MIT License

    Permission is hereby granted, free of charge, to any person obtaining a copy
    of this software and associated documentation files (the "Software"), to deal
    in the Software without restriction, including without limitation the rights
    to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
    copies of the Software, and to permit persons to whom the Software is
    furnished to do so, subject to the following conditions:

    The above copyright notice and this permission notice shall be included in all
    copies or substantial portions of the Software.

    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
    AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
    OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
    SOFTWARE

	 CS : CE1
	 RST : GPIO25
	 IRQ : GPIO22 (DIO0)
	 Unused : GPIO23 (DIO1)
	 Unused : GPIO24 (DIO2)
 */
namespace devMobile.IoT.Rfm69hcw.AdafruitSPI
{
	using System;
	using System.Diagnostics;
	using System.Threading;
	using Windows.ApplicationModel.Background;
	using Windows.Devices.Spi;

	public sealed class StartupTask : IBackgroundTask
	{
		private const byte RegVersion = 0x10;

		public void Run(IBackgroundTaskInstance taskInstance)
		{
			SpiController spiController = SpiController.GetDefaultAsync().AsTask().GetAwaiter().GetResult();
			var settings = new SpiConnectionSettings(1)
			{
				ClockFrequency = 500000,
				Mode = SpiMode.Mode0,
			};

			SpiDevice Device = spiController.GetDevice(settings);

			while (true)
			{
				byte[] writeBuffer = new byte[] { RegVersion }; // RegVersion
				byte[] readBuffer = new byte[1];

				Device.TransferSequential(writeBuffer, readBuffer);

				byte registerValue = readBuffer[0];
				Debug.WriteLine("Register 0x{0:x2} - Value 0X{1:x2} - Bits {2}", RegVersion, registerValue, Convert.ToString(registerValue, 2).PadLeft(8, '0'));

				Thread.Sleep(10000);
			}
		}
	}
}

The AdaFruit hat uses chip select 1

/*
    Copyright ® 2019 May devMobile Software, All Rights Reserved
 
    MIT License

    Permission is hereby granted, free of charge, to any person obtaining a copy
    of this software and associated documentation files (the "Software"), to deal
    in the Software without restriction, including without limitation the rights
    to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
    copies of the Software, and to permit persons to whom the Software is
    furnished to do so, subject to the following conditions:

    The above copyright notice and this permission notice shall be included in all
    copies or substantial portions of the Software.

    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
    AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
    OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
    SOFTWARE

    The RaspyRFM is plugged into the Raspberry PI of pin 17-26.

    From the docs for the dual RFM69 mini 
    17 -> 3,3 V
    18 (GPIO 24) -> DIO1 bei Einzelmodul, DIO0 Slave bei Doppelmodul
    19 (MOSI) -> MOSI
    20 -> GND
    21 (MISO) ->MISO
    22 (GPIO 25) -> DIO0
    23 (SCK) -> SCK
    24 (CE0) -> NSS Master
    25 -> GND
    26 (CE1) -> DIO2 bei Einzelmodul, NSS Slave bei Doppelmodul
 */
namespace devMobile.IoT.Rfm69hcw.SeegelSpi
{
	using System;
	using System.Diagnostics;
	using System.Threading;
	using Windows.ApplicationModel.Background;
	using Windows.Devices.Spi;

	public sealed class StartupTask : IBackgroundTask
	{
		private const byte RegVersion = 0x10;

		public void Run(IBackgroundTaskInstance taskInstance)
		{
			SpiController spiController = SpiController.GetDefaultAsync().AsTask().GetAwaiter().GetResult();
			var settings = new SpiConnectionSettings(0)
			{
				ClockFrequency = 500000,
				Mode = SpiMode.Mode0,
			};

			SpiDevice Device = spiController.GetDevice(settings);

			while (true)
			{
				byte[] writeBuffer = new byte[] { RegVersion }; // RegVersion
				byte[] readBuffer = new byte[1];

				Device.TransferSequential(writeBuffer, readBuffer);

				byte registerValue = readBuffer[0];
				Debug.WriteLine("Register 0x{0:x2} - Value 0X{1:x2} - Bits {2}", RegVersion, registerValue, Convert.ToString(registerValue, 2).PadLeft(8, '0'));

				Thread.Sleep(10000);
			}
		}
	}
}

The Seegel hat uses chip select 0

Based on the datasheet the RegVersion (0x10) register the value (ox24) returned by both hats was correct.

'backgroundTaskHost.exe' (CoreCLR: CoreCLR_UWP_Domain): Loaded 'C:\Data\Programs\WindowsApps\Microsoft.NET.CoreFramework.Debug.2.2_2.2.27505.2_arm__8wekyb3d8bbwe\System.Threading.Thread.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
Register 0x10 - Value 0X24 - Bits 00100100
Register 0x10 - Value 0X24 - Bits 00100100
Register 0x10 - Value 0X24 - Bits 00100100

Next step is to dump all the registers of the HopeRF module

RFM9X.IoTCore Adafruit LoRa Radio Bonnet support

The RFM9X chip select line on the Adafruit LoRa Radio Bonnet 868 or 915MHz with OLED RFM95W is connected to pin 26(CS1), the reset line to pin 22(GPIO25) and the interrupt line to pin 15(GPIO22).

When I ran the RFM9XLoRaDeviceClient from my RFM9X.IoTCore library with the following configuration

#if ADAFRUIT_RADIO_BONNET
	private const byte ResetLine = 25;
	private const byte InterruptLine = 22;
	private Rfm9XDevice rfm9XDevice = new Rfm9XDevice(ChipSelectPin.CS1, ResetLine, InterruptLine);
#endif

public void Run(IBackgroundTaskInstance taskInstance)
{
	rfm9XDevice.Initialise(Frequency, paBoost: true, rxPayloadCrcOn : true);
#if DEBUG
	rfm9XDevice.RegisterDump();
#endif
	rfm9XDevice.OnReceive += Rfm9XDevice_OnReceive;
#if ADDRESSED_MESSAGES_PAYLOAD
	rfm9XDevice.Receive(UTF8Encoding.UTF8.GetBytes(Environment.MachineName));
#else
	rfm9XDevice.Receive();
#endif
	rfm9XDevice.OnTransmit += Rfm9XDevice_OnTransmit;

	Task.Delay(10000).Wait();

	while (true)
	{
		string messageText = string.Format("Hello from {0} ! {1}", Environment.MachineName, MessageCount);
		MessageCount -= 1;

		byte[] messageBytes = UTF8Encoding.UTF8.GetBytes(messageText);
		Debug.WriteLine("{0:HH:mm:ss}-TX {1} byte message {2}", DateTime.Now, messageBytes.Length, messageText);
#if ADDRESSED_MESSAGES_PAYLOAD
		this.rfm9XDevice.Send(UTF8Encoding.UTF8.GetBytes("AddressHere"), messageBytes);
#else
		this.rfm9XDevice.Send(messageBytes);
#endif
		Task.Delay(10000).Wait();
	}
}
#endif

I could see messages being sent and received in the debug output

Register 0x3e - Value 0X00 - Bits 00000000
Register 0x3f - Value 0X00 - Bits 00000000
Register 0x40 - Value 0X00 - Bits 00000000
Register 0x41 - Value 0X00 - Bits 00000000
Register 0x42 - Value 0X12 - Bits 00010010
...
The thread 0xec4 has exited with code 0 (0x0).
The thread 0x868 has exited with code 0 (0x0).
22:21:47-RX PacketSnr 9.8 Packet RSSI -80dBm RSSI -122dBm = 59 byte message "�LoRaIoT1Maduino2at 62.8,ah 77,wsa 1,wsg 3,wd 34.88,r 0.00,"
22:21:52-TX 31 byte message Hello from AdaFruitIOLoRa ! 255
22:21:52-TX Done
The thread 0xbf8 has exited with code 0 (0x0).
The program '[3380] backgroundTaskHost.exe' has exited with code -1 (0xffffffff).

Next step modify my Adafruit IO and Azure IoT Hub/Central field gateways.

Adafruit LoRa Radio Bonnet with OLED – RadioFruit

Today a package arrived from Adafruit which contained an Adafruit LoRa Radio Bonnet 868 or 915MHz with OLED RFM95W.

The shield has a small OLED screen and 3 buttons connected to General Purpose Input Output(GPIO) pins.

The first step was to check the pin assignments of the 3 buttons.

/*
    Copyright ® 2019 Feb devMobile Software, All Rights Reserved
 
    MIT License

    Permission is hereby granted, free of charge, to any person obtaining a copy
    of this software and associated documentation files (the "Software"), to deal
    in the Software without restriction, including without limitation the rights
    to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
    copies of the Software, and to permit persons to whom the Software is
    furnished to do so, subject to the following conditions:

    The above copyright notice and this permission notice shall be included in all
    copies or substantial portions of the Software.

    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
    AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
    OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
    SOFTWARE

	 Adafruit documentation page
	 https://learn.adafruit.com/adafruit-radio-bonnets/pinouts

    Button 1: GPIO 5 
    Button 2: GPIO 6
    Button 3: GPIO 12 

 */
namespace devMobile.IoT.Rfm9x.AdafruitButtons
{
	using System;
	using System.Diagnostics;
	using Windows.ApplicationModel.Background;
	using Windows.Devices.Gpio;

	public sealed class StartupTask : IBackgroundTask
    {
		private BackgroundTaskDeferral backgroundTaskDeferral = null;
		private GpioPin InterruptGpioPin1 = null;
		private GpioPin InterruptGpioPin2 = null;
		private GpioPin InterruptGpioPin3 = null;
		private const int InterruptPinNumber1 = 5;
		private const int InterruptPinNumber2 = 6;
		private const int InterruptPinNumber3 = 12;
		private readonly TimeSpan debounceTimeout = new TimeSpan(0, 0, 15);


		public void Run(IBackgroundTaskInstance taskInstance)
        {
			Debug.WriteLine("Application startup");

			try
			{
				GpioController gpioController = GpioController.GetDefault();

				InterruptGpioPin1 = gpioController.OpenPin(InterruptPinNumber1);
				InterruptGpioPin1.SetDriveMode(GpioPinDriveMode.InputPullUp);
				InterruptGpioPin1.ValueChanged += InterruptGpioPin_ValueChanged; ;

				InterruptGpioPin2 = gpioController.OpenPin(InterruptPinNumber2);
				InterruptGpioPin2.SetDriveMode(GpioPinDriveMode.InputPullUp);
				InterruptGpioPin2.ValueChanged += InterruptGpioPin_ValueChanged; ;

				InterruptGpioPin3 = gpioController.OpenPin(InterruptPinNumber3);
				InterruptGpioPin3.SetDriveMode(GpioPinDriveMode.InputPullUp);
				InterruptGpioPin3.ValueChanged += InterruptGpioPin_ValueChanged; ;

				Debug.WriteLine("Digital Input Interrupt configuration success");
			}
			catch (Exception ex)
			{
				Debug.WriteLine($"Digital Input Interrupt configuration failed " + ex.Message);
				return;
			}

			//enable task to continue running in background
			backgroundTaskDeferral = taskInstance.GetDeferral();
		}

		private void InterruptGpioPin_ValueChanged(GpioPin sender, GpioPinValueChangedEventArgs args)
		{
			Debug.WriteLine($"Digital Input Interrupt {sender.PinNumber} triggered {args.Edge}");
		}
	}
}

When I ran the application it produced the following output when I pressed the three buttons (left->right) which confirmed I had the correct GPIO pins configuration.

Application startup
'backgroundTaskHost.exe' (CoreCLR: CoreCLR_UWP_Domain): Loaded 'C:\Data\Programs\WindowsApps\Microsoft.NET.CoreFramework.Debug.2.2_2.2.27129.1_arm__8wekyb3d8bbwe\System.Runtime.WindowsRuntime.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
Digital Input Interrupt configuration success
Digital Input Interrupt 5 triggered FallingEdge
Digital Input Interrupt 5 triggered RisingEdge
Digital Input Interrupt 6 triggered FallingEdge
Digital Input Interrupt 6 triggered RisingEdge
Digital Input Interrupt 12 triggered FallingEdge
Digital Input Interrupt 12 triggered RisingEdge

The next step was to get the Serial Peripheral Interface (SPI) interface for the module working.

/*
    Copyright ® 2019 Feb devMobile Software, All Rights Reserved
 
    MIT License

    Permission is hereby granted, free of charge, to any person obtaining a copy
    of this software and associated documentation files (the "Software"), to deal
    in the Software without restriction, including without limitation the rights
    to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
    copies of the Software, and to permit persons to whom the Software is
    furnished to do so, subject to the following conditions:

    The above copyright notice and this permission notice shall be included in all
    copies or substantial portions of the Software.

    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
    AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
    OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
    SOFTWARE

	 Adafruit documentation page
	 https://learn.adafruit.com/adafruit-radio-bonnets/pinouts

	 CS : CE1
	 RST : GPIO25
	 IRQ : GPIO22 (DIO0)
	 Unused : GPIO23 (DIO1)
	 Unused : GPIO24 (DIO2)
 */
namespace devMobile.IoT.Rfm9x.AdafruitSPI
{
	using System;
	using System.Diagnostics;
	using System.Threading;
	using Windows.ApplicationModel.Background;
	using Windows.Devices.Spi;

	public sealed class StartupTask : IBackgroundTask
	{
		public void Run(IBackgroundTaskInstance taskInstance)
		{
			SpiController spiController = SpiController.GetDefaultAsync().AsTask().GetAwaiter().GetResult();
			var settings = new SpiConnectionSettings(1)
			{
				ClockFrequency = 500000,
				Mode = SpiMode.Mode0,   // From SemTech docs pg 80 CPOL=0, CPHA=0
			};

			SpiDevice Device = spiController.GetDevice(settings);

			while (true)
			{
				byte[] writeBuffer = new byte[] { 0x42 }; // RegVersion
				byte[] readBuffer = new byte[1];

				Device.TransferSequential(writeBuffer, readBuffer);

				byte registerValue = readBuffer[0];
				Debug.WriteLine("Register 0x{0:x2} - Value 0X{1:x2} - Bits {2}", 0x42, registerValue, Convert.ToString(registerValue, 2).PadLeft(8, '0'));

				Thread.Sleep(10000);
			}
		}
	}
}

The output confirm the code worked

'backgroundTaskHost.exe' (CoreCLR: CoreCLR_UWP_Domain): Loaded 'C:\Data\Programs\WindowsApps\Microsoft.NET.CoreFramework.Debug.2.2_2.2.27129.1_arm__8wekyb3d8bbwe\System.Threading.Thread.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
Register 0x42 - Value 0X12 - Bits 00010010
Register 0x42 - Value 0X12 - Bits 00010010

The next step is to build support for this shield into my RFM9X.IoTCore library and get the OLED working.

Adafruit.IO LoRa Field Gateway BCD Addressing

After some testing with more client devices, especially the Easy Sensors Arduino Nano radio shield RFM69/95 or NRF24L01+ I have decided to move to non text addresses for devices and the LoRa field gateway.

THIS IS A BREAKING CHANGE

The unique identifier provided by the SHA204A crypto and authentication chip on the EasySensors shield highlighted this issue. The Binary Coded Decimal(BCD) version of the 72 bit identifier was too long to fit in the from address.

My later Arduino based sample clients have some helper functions to populate the message header, add values, and prepare the message payload for reuse.

On the server side I have added code to log the build version and Raspbery PI shield type

// Log the Application build, shield information etc.
LoggingFields appllicationBuildInformation = new LoggingFields();
#if DRAGINO
   appllicationBuildInformation.AddString("Shield", "DraginoLoRaGPSHat");
#endif
…
#if UPUTRONICS_RPIPLUS_CS1
   appllicationBuildInformation.AddString("Shield", "UputronicsPiPlusLoRaExpansionBoardCS1");
#endif
appllicationBuildInformation.AddString("Timezone", TimeZoneSettings.CurrentTimeZoneDisplayName);
appllicationBuildInformation.AddString("OSVersion", Environment.OSVersion.VersionString);
appllicationBuildInformation.AddString("MachineName", Environment.MachineName);

// This is from the application manifest 
Package package = Package.Current;
PackageId packageId = package.Id;
PackageVersion version = packageId.Version;

appllicationBuildInformation.AddString("ApplicationVersion", string.Format($"{version.Major}.{version.Minor}.{version.Build}.{version.Revision}"));
this.loggingChannel.LogEvent("Application starting", appllicationBuildInformation, LoggingLevel.Information);

Then when the message payload is populated the from address byte array is converted to BCD

private async void Rfm9XDevice_OnReceive(object sender, Rfm9XDevice.OnDataReceivedEventArgs e)
{
   string addressBcdText;
   string messageBcdText;
   string messageText = "";
   char[] sensorReadingSeparator = new char[] { ',' };
   char[] sensorIdAndValueSeparator = new char[] { ' ' };

   addressBcdText = BitConverter.ToString(e.Address);

   messageBcdText = BitConverter.ToString(e.Data);
   try
   {
      messageText = UTF8Encoding.UTF8.GetString(e.Data);
   }
   catch (Exception)
   {
      this.loggingChannel.LogMessage("Failure converting payload to text", LoggingLevel.Error);
   return;
   }

#if DEBUG
    Debug.WriteLine(@"{0:HH:mm:ss}-RX From {1} PacketSnr {2:0.0} Packet RSSI {3}dBm RSSI {4}dBm = {5} byte message ""{6}""", DateTime.Now, addressBcdText, e.PacketSnr, e.PacketRssi, e.Rssi, e.Data.Length, messageText);
#endif
   LoggingFields messagePayload = new LoggingFields();
   messagePayload.AddInt32("AddressLength", e.Address.Length);
   messagePayload.AddString("Address-BCD", addressBcdText);
   messagePayload.AddInt32("Message-Length", e.Data.Length);
   messagePayload.AddString("Message-BCD", messageBcdText);
   messagePayload.AddString("Nessage-Unicode", messageText);
   messagePayload.AddDouble("Packet SNR", e.PacketSnr);
   messagePayload.AddInt32("Packet RSSI", e.PacketRssi);
   messagePayload.AddInt32("RSSI", e.Rssi);
   this.loggingChannel.LogEvent("Message Data", messagePayload, LoggingLevel.Verbose);

			
   // Check the address is not to short/long 
   if (e.Address.Length < AddressLengthMinimum)
   {
      this.loggingChannel.LogMessage("From address too short", LoggingLevel.Warning);
      return;
   }

   if (e.Address.Length > MessageLengthMaximum)
   {
      this.loggingChannel.LogMessage("From address too long", LoggingLevel.Warning);
      return;
   }

   // Check the payload is not too short/long 
   if (e.Data.Length < MessageLengthMinimum)
   {
      this.loggingChannel.LogMessage("Message too short to contain any data", LoggingLevel.Warning);
      return;
   }

   if (e.Data.Length > MessageLengthMaximum)
   {
      this.loggingChannel.LogMessage("Message too long to contain valid data", LoggingLevel.Warning);
      return;
   }

   // Adafruit IO is case sensitive & only does lower case ?
   string deviceId = addressBcdText.ToLower();

   // Chop up the CSV text payload
   string[] sensorReadings = messageText.Split(sensorReadingSeparator, StringSplitOptions.RemoveEmptyEntries);
   if (sensorReadings.Length == 0)
   {
      this.loggingChannel.LogMessage("Payload contains no sensor readings", LoggingLevel.Warning);
      return;
   }

   Group_feed_data groupFeedData = new Group_feed_data();

   LoggingFields sensorData = new LoggingFields();
   sensorData.AddString("DeviceID", deviceId);

   // Chop up each sensor reading into an ID & value
   foreach (string sensorReading in sensorReadings)
   {
      string[] sensorIdAndValue = sensorReading.Split(sensorIdAndValueSeparator, StringSplitOptions.RemoveEmptyEntries);

      // Check that there is an id & value
      if (sensorIdAndValue.Length != 2)
      {
         this.loggingChannel.LogMessage("Sensor reading invalid format", LoggingLevel.Warning);
         return;
      }

      string sensorId = sensorIdAndValue[0].ToLower();
      string value = sensorIdAndValue[1];

      // Construct the sensor ID from SensordeviceID & Value ID
      groupFeedData.Feeds.Add(new Anonymous2() { Key = string.Format("{0}{1}", deviceId, sensorId), Value = value });

      sensorData.AddString(sensorId, value);

      Debug.WriteLine(" Sensor {0}{1} Value {2}", deviceId, sensorId, value);
   }
   this.loggingChannel.LogEvent("Sensor readings", sensorData, LoggingLevel.Verbose);

   try
   {
      Debug.WriteLine(" CreateGroupDataAsync start");
      await this.adaFruitIOClient.CreateGroupDataAsync(this.applicationSettings.AdaFruitIOUserName,
this.applicationSettings.AdaFruitIOGroupName.ToLower(), groupFeedData);
      Debug.WriteLine(" CreateGroupDataAsync finish");
   }
   catch (Exception ex)
   {
      Debug.WriteLine(" CreateGroupDataAsync failed {0}", ex.Message);
				this.loggingChannel.LogMessage("CreateGroupDataAsync failed " + ex.Message, LoggingLevel.Error);
   }
}
AfaFruit.IO Data Display

This does mean longer field names but I usually copy n paste them from the Arduino serial monitor or the Event Tracing For Windows (ETW) logging.

AdaFruit.IO Field gateway ETW Logging