Help with bytes management in C++

I'm working on some remote temperature sensors. I'm using RadioHead and cheap ASK radios (FS1000A and XY-MK-5V) and developing on Nano clones, will port to Digisparks when the prototype is working.

I'd like to send a small message size; one byte to indicate one of 14 stations, and two bytes to carry an Arduino platform int value (which is stored in two bytes according to the doc). The int is just exactly what I pull from an analogRead() with the default 10bit resolution.

My weakness is in the language itself and how to manage these bytes accurately. Could someone knowledgeable in C++ take a peek and tell me what may be wrong?

The output I'm receiving is looking like:

Received bytes: 
1 B B 
Station called: 1
Measurement: 2297
Total packets received: 9

Received bytes: 
1 17 17 
Station called: 1
Measurement: 2297
Total packets received: 10

Received bytes: 
1 CA CA 
Station called: 1
Measurement: 2297
Total packets received: 11
...

The problems you can see are:

  1. The 2nd and third bytes are always the same!
  2. My reconstitution of the two bytes back into an int on the other side is not working, either.

Sender:

#include <RH_ASK.h>

#if defined ( ARDUINO_AVR_NANO )
  int rxPin = 11;
  int txPin = 12;
  int pttPin = 10;
  int thermistor = A1;

#elif defined ( ARDUINO_AVR_DIGISPARK )
  int rxPin = PB2; // unused
  int txPin = PB0; 
  int pttPin = PB1;
  int thermistor = PB3;

#endif

RH_ASK rf_driver;

void setup() {

  rf_driver = RH_ASK( 2000, rxPin, txPin, pttPin, false );
  Serial.begin( 9600 );
  
  if ( rf_driver.init() ) {
    Serial.print( "Radio initialized. Max message lenth: " );
    Serial.println( rf_driver.maxMessageLength() );
  
    // initialise thermistor circuit
    pinMode( thermistor, INPUT );
    
    // I'm alive
    pinMode( LED_BUILTIN, OUTPUT );
    digitalWrite( LED_BUILTIN, HIGH );
    delay( 500 );
    digitalWrite( LED_BUILTIN, LOW );
    delay( 500 );
  }
  
}

void loop() {

  // The solution will have fewer than 255 telemetry sending stations
  const uint8_t STATION = 1;
  
  int thermistorReading = analogRead( thermistor ); // 10 bit value stored in a 2-byte int
  Serial.println( thermistorReading, DEC );
  
  const uint8_t LENGTH = 3;
  uint8_t message[ LENGTH ];
  message[0] = STATION;
  message[1] = thermistorReading & 0b0000000011111111; // first byte of this int
  message[2] = thermistorReading & 0b1111111100000000 >> 8; // second byte of this int
  
  // send message
  // TODO set Digispark clock to 8MHz
  digitalWrite( LED_BUILTIN, HIGH );
  // rf_driver.send( ( uint8_t * ) msg, strlen( msg ) );
  if ( rf_driver.send( message, LENGTH ) ) {
    rf_driver.waitPacketSent();
  }
  digitalWrite( LED_BUILTIN, LOW );


  // To be replaced with power saving delay feature
  delay( 1000 );
  
}

Receiver:


#include <RH_ASK.h>

#if defined ( ARDUINO_AVR_NANO )
  int rxPin = 11;
  int txPin = 12;
  int pttPin = 10;
  int thermistor = A1;

#elif defined ( ARDUINO_AVR_DIGISPARK )
  int rxPin = PB2; // unused
  int txPin = PB0; 
  int pttPin = PB1;
  int thermistor = PB3;

#endif

RH_ASK rf_driver;

void setup()
{
    rf_driver = RH_ASK( 2000, rxPin, txPin, pttPin, false );
    if ( ! rf_driver.init() ){
      pinMode( LED_BUILTIN, OUTPUT );
      while ( true ) {
        digitalWrite( LED_BUILTIN, HIGH );
        delay( 1000 );
        digitalWrite( LED_BUILTIN, LOW );
        delay( 1000 );
      }
    }

    // Setup Serial Monitor
    Serial.begin( 57600 );
    Serial.println( "Listening with serial 57600" );
}
 
void loop()
{
    
    // Set buffer to size of expected message
    uint8_t buf[ 3 ];
    uint8_t buflen = sizeof( buf );
    memset( buf, '\0', sizeof( buf ) );
    
    // A well-formed packet has been received
    if ( rf_driver.recv( buf, &buflen ) )
    {

      rf_driver.printBuffer( "Received bytes: ", buf, buflen );

      uint8_t station = buf[0];
      uint8_t m[2] = { '\0', '\0' };
      m[0] = buf[1];
      m[1] = buf[2];
      int measurement = (int) m; // reconstitute two bytes into an int value

      Serial.print( "Station called: " );
      Serial.println( station, DEC );
      Serial.print( "Measurement: " );
      Serial.println( measurement, DEC );
      
      Serial.print( "Total packets received: " );
      Serial.println( rf_driver.rxGood(), DEC );
      Serial.println();
    }
}

In case anyone is curious why I'm sending a raw analogRead() result, it's because I will need to keep the final sending program very small. I will calibrate all these sensors at once, and just produce a lookup table which will be processed on the receiving end.

Something like:

  • Station 1: multiply by 1.22 and subtract 523
  • Station 2: multiply by 1.23 and subtract 560
    etc.

Oh, I think I may have solved the first problem with:

  const uint8_t LENGTH = 3;
  uint8_t message[ LENGTH ];
  message[0] = STATION;
  message[1] = highByte( thermistorReading );
  message[2] = lowByte( thermistorReading );

If you're unsure of operator precedence (no, me neither), use parentheses

I would prefer to see this as

uint16_t m[2] = { 0, 0 };
..
uint16_t measurement = m[0] & (m[1]<<8);

That way you are not relying on whatever 'endian' convention the hardware architecture is using and it will be clearer when you come to maintain later.

EDIT: As point out later, this should be a logical OR or a +

uint16_t measurement = m[0] | (m[1]<<8);

https://en.cppreference.com/w/cpp/language/operator_precedence

And now?

I am now pulling plausible looking values by using the following code on the receiving side:

      uint8_t station = buf[0];
      int measurement = ( buf[1] <<8 ) + buf[2];

Thank you for the inputs here. I also found the solution on the following Stackoverflow link: c - Convert 2 bytes into an integer - Stack Overflow

I think the whole point of the forum (or at least, the whole gist of my question) is that I am trying to use C++ without fully understanding it. I do not think writing correct C++ is a matter of just quickly looking up a syntax, and then getting to work. (like you could with Python or Java)

I tried to study how to manage strings earlier this evening, and just about had a stroke reading the simplified Arduino doc.

I can recognise it would take years to master this language. Whereas, we in Arduino-land are just hacking things together.

Well they are the same because

0b1111111100000000 >> 8

is

0b0000000011111111

Oh! And that is the utility of the parentheses, then :). Thank you for explaining it.

Marco, I don't fully understand. If I pull them apart in the same order that I put them back together, where does endian-ness come into play? I also don't understand what we gain by using a 16 bit data type in the m temporary array.

Oh, I see. Yes, in the future I will be sending from Digispark and receiving on Nano. So I will have to be ready to manage platform endian-ness.

Actually you were not putting them together again at all. You were relying on the order in memory and promoting to an int (which is itself not the same size on every platform). If you care about the size of the variable in bytes then you should use the guaranteed consistent types uintn_t and intn_t where n is 8, 16 or 32 and u is the unsigned integer.

I also don't understand what we gain by using a 16 bit data type

You can fall into the problem that the operands are evaluated as uint8_t and then promoted to 16 bits at the end of the calculation. So taking an 8 bit value, shifting by 8 bits left results in zero. An alternative to having the temporary uint16_t array is to promote the operands of the sum to be uint16_t so that this does not happen.

And with respect to operator precedence, I am with AWOL. It kills me that so many bugs are caused by the omission of brackets when they are so cheap and make things abundantly clear to the reader and the compiler. Relying on remembering arcane precedence rules is just looking for problems - be clear in your intention and you (and others) will thank your past self when you come to do maintenance on the software.

Bitwise-and?

You could just put all the data into a struct, instead of breaking the int into individual bytes.


  struct {
    uint8_t station;
    int     thermReading;
  } message;

  message.station = STATION;
  message.thermReading = thermistorReading;
  
  // send message
  // TODO set Digispark clock to 8MHz
  digitalWrite( LED_BUILTIN, HIGH );
  if ( rf_driver.send( (byte*)&message, sizeof(message) ) ) {
    rf_driver.waitPacketSent();
  }
  digitalWrite( LED_BUILTIN, LOW );

Then the receive code would be something like this (untested):

void loop()
{

  // Set buffer to size of expected message
  struct {
    uint8_t station;
    int     thermReading;
  } buf;

  uint8_t buflen = sizeof( buf );

  // A well-formed packet has been received
  if ( rf_driver.recv( (byte*)&buf, &buflen ) )
  {

    rf_driver.printBuffer( "Received bytes: ", (byte*)&buf,  buflen );

    uint8_t station = buf.station;
    int measurement = buf.thermReading;

    Serial.print( "Station called: " );
    Serial.println( station, DEC );
    Serial.print( "Measurement: " );
    Serial.println( measurement, DEC );

    Serial.print( "Total packets received: " );
    Serial.println( rf_driver.rxGood(), DEC );
    Serial.println();
  }
}

Mind endiannness, int type size and struct layout optimization…

I'd code that as:

  message[1] = thermistorReading & 0xFF; // first byte of this int
  message[2] = (thermistorReading >> 8) & 0xFF; // second byte of this int

Shifting before masking is much more commonly done, then the byte masks are all the same - easier to read, less chance of mistakes, compiles to more efficient code too.

Using hex constants rather than binary constants for byte masks makes it less error-prone - would you immediately detect 0b111111111 is the wrong value (much easier to spot 0x1FF as different from 0xFF, than 0b111111111 from 0b11111111....)

As message is an array of uint8_t, there is no need for the mask. The C++ specs states that the LSB will be copied over in such an assignment. So you can simply do:

message[1] = thermistorReading;      // LSB
message[2] = thermistorReading >> 8; // MSB

(and for the sake of defining the size of an int, thermistorReading could be defined as a uint16_t)

True, the different board packages for the Nano and the DigiSpark may end up with different struct size, but it is not clear form the OP's initial post whether he will have a mix of processors, or just a single type. The bit shifting would be better in a mixed-endian environment since that does not require any knowledge of how the actual int is stored, or how many bytes an int actually occupies (as long as it is at least two bytes).

My project will use sending units controlled by ATTINY85 controllers on Digispark boards. The receiving unit will use a Nano clone with an ATMega328p.

I thought on such simple devices, all of the "endianness" is a matter for the compilers rather than the hardware.

Actually I had an idea to do this without relying on endianness at all.

  1. My starting number is between 0 and 1023. Divide that number by 255.
  2. Send the uint8_t quotient in position 1
  3. Send the uint8_t remainder in position 2
    The downside of this is the CPU cycles and power usage of integer division.

On the other hand, I can do the bit operation and it if works for my hardware, there be it (or I can reverse the endianness in an #ifdef block)

At the end of the day I really only need this to work, but as it is a learning opportunity and a new language for me, I'd like to do it nicely: avoid buffer overflows, integer overflows, poor style, wastage of resources, etc.