The following code works on a range of Arduino's but not on ESP. It returns random data for ID and Pin. The other two fields are always empty.
I use the Arduino IDE for both the ESP and the Arduino's. It looks like the ESP has it's own idea when it comes to struct.
#include <RH_ASK.h>
#include <SPI.h>
#define BAUD 2000
#define RX 2
#define TX 5
RH_ASK driver(BAUD, RX, TX);
struct data {
int id;
int pin;
int value1;
int value2;
} myData;
void setup()
{
Serial.begin(9600);
Serial.println("Starting..");
if (!driver.init())
Serial.println("init failed");
}
void loop()
{
uint8_t buf[RH_ASK_MAX_MESSAGE_LEN];
uint8_t buflen = sizeof(buf);
if (driver.recv(buf, &buflen)) {
memcpy(&myData, buf, buflen);
Serial.print("ID: ");
Serial.println(myData.id);
Serial.print("Pin: ");
Serial.println(myData.pin);
Serial.print("Value1: ");
Serial.println(myData.value1);
Serial.print("Value2: ");
Serial.println(myData.value2);
Serial.println("");
}
yield;
}
Bad Data
ID: 263145
Pin: 18350364
Value1: 0
Value2: 0
Should be
ID: 1001
Pin: 4
Value1: 267
Value2: 843
1 Answer 1
The issue is that Arduino boards (8 bit ones at least), an int
is 16 bits, where as the ESP's (8266 and 32) and possibly other non-arduino hardware, an int is 32bits
The safest way to declare structs in any case is to use variable types with known sizes, in your case, for signed 16bit ints
struct data {
int16_t id;
int16_t pin;
int16_t value1;
int16_t value2;
} myData;
or for unsigned 16bit ints
struct data {
uint16_t id;
uint16_t pin;
uint16_t value1;
uint16_t value2;
} myData;
Note: there's also short int
which I believe is "guaranteed" to be 16bit (and "long int" is always 32 bit) - but having the bit size in the declaration is a far better (future proof) solution
short int
instead ofint
in the struct (looks like int's are 32bit in esp8266 and 16bit in arduino boards? perhaps? - For portability use uint16_t and int16_t for ints - github.com/mysensors/MySensors/issues/223