I'm using MKRZero to send data to other board (MKR GSM 1400 )through serial1 (both boards have rf module).
I'm sending the data using struct, both code for recieving and sending have the exact struct.
Sometimes I get the massege correct but sometimes I don't, and I honestly don't know why..
The code for receiving the struct:
int incomingData;
enum msg_type {AskForSend, Ack, Data, Error, Stop};
struct header_S
{
byte sendRecieve;
byte gatewayID;
byte sensorID;
msg_type msgType;
byte msgSize;
int Data;
};
void setup() {
delay(2000);
Serial.begin(9600);
Serial1.begin(9600);
}
void loop () {
if (Serial1.available() > 0)
{
incomingData = Serial1.available();
Serial.print("byte we need to recieve : ");
Serial.println(incomingData);
HandleGatewayMsg();
}
}
void HandleGatewayMsg()
{
header_S hdr;
byte *hdr_ptr;
hdr_ptr = (byte *)&hdr;
Serial.println("Msg recieved...");
Serial1.readBytes(hdr_ptr, sizeof(header_S));
Serial.println(hdr_ptr[0]);
Serial.println(hdr_ptr[1]);
Serial.println(hdr_ptr[2]);
Serial.println(hdr_ptr[3]);
Serial.print("MsgType: ");
Serial.println(hdr.msgType);
switch(hdr.msgType)
{
/*case AskForSend:
Serial.print("Got a request from gateway..");
SendAck(hdr.gatewayID); //send ack msg
break; */
case Data:
Serial.println("Recieved data from gateway..");
Serial.print("temp = ");
Serial.println(hdr.Data);
break;
}
}
The code for sending the massage :
#include "Adafruit_Sensor.h"
#include "Adafruit_AM2320.h"
Adafruit_AM2320 am2320 = Adafruit_AM2320();
#pragma pack (1)
unsigned int start_time;
int timeoutMeasure = 2*60*1000;
int temp; // Global variable
enum msg_type {AskForSend, Ack, Data, Error, Stop};
struct header_S
{
byte sendRecieve;
byte gatewayID;
byte sensorID;
msg_type msgType;
byte msgSize;
int Data;
};
void setup() {
Serial.begin(9600);
Serial1.begin(9600);
while (!Serial) {
delay(10); // hang out until serial port opens
}
am2320.begin();
}
void loop() {
if (millis() - start_time > timeoutMeasure)
{
HandleSensorData();
start_time = millis();
}
}
void HandleSensorData(){
Serial.println("Getting data from sensors");
temp = am2320.readTemperature();
Serial.print("temp = ");
Serial.println(temp);
sendDataToMaster();
}
void sendDataToMaster( )
{
Serial.println("Sending Data to master...");
Serial.print("Numbers of bytes on the msg : ");
Serial.println(sizeof(header_S));
header_S hdrSend;
hdrSend.sendRecieve = 1;
hdrSend.gatewayID = 1;
hdrSend.sensorID = 1;
hdrSend.msgType = Data;
hdrSend.msgSize = sizeof(int);
hdrSend.Data = temp ;
Serial1.write((byte*)&hdrSend, sizeof(header_S));
Serial.println(((byte*)&hdrSend)[0]);
Serial.println(((byte*)&hdrSend)[1]);
Serial.println(((byte*)&hdrSend)[2]);
Serial.println(((byte*)&hdrSend)[3]);
}
This the serial monitor on the MKR GSM 1400 (The board that should receive the data) :