I'm trying to send some data with LoRa but I only receive single chars (line by line) or float, int, byte...
I want to send "msg" like a string.
I have:
struct DATA {
char msg = "";
int valor;
};
DATA MyData;
.
.
.
void loop() {
if (Serial.available() > 0) {
MyData.msg = Serial.read();
MyData.valor = 10;
Transceiver.SendStruct((uint8_t*) &MyData, (uint8_t) sizeof(MyData));
Serial.print("Sending: "); Serial.println(MyData.msg); Serial.println(MyData.valor);
}
}
it works but if I send: "hello world", I will receive:
h
10
e
10
l
10
.
.
.
So I tried to make an aux variable:
if (Serial.available() > 0) {
char aux = Serial.read();
MyData.msg += aux;
MyData.valor = 10;
Transceiver.SendStruct((uint8_t*) &MyData, (uint8_t) sizeof(MyData));
Serial.print("Sending: "); Serial.println(MyData.msg); Serial.println(MyData.valor);
}
But I receive only unrecognized chars.
PS1: If I change struct char with a String, I receive only unrecognized chars.
PS2: I tried to make a "for" with the sizeof on receive to join the chars to make a string, but it doesn't work either.
Thanks in advance.
MyData.msg
is defined as a char
which is a single character instead of an array[]
. You need to define your struct as:#define MAX_STR_LENGTH 20
typedef struct {
char msg[MAX_STR_LENGTH] = '\0'; // an array of char
int valor = 0;
} Data_t;
Data_t Mydata;
\n
. You can read in the whole string by checking with the received char is an \n
and only send the struct then.void loop() {
static int i = 0;
while (Serial.available() > 0) {
char c = Serial.read();
if (c != '\n') {
MyData.msg[i] = c;
i++;
}
else {
// terminate the array with NULL terminator and send the struct
MyData.msg[i] = '\0';
MyData.valor = 10;
Transceiver.SendStruct((uint8_t*) &MyData, (uint8_t) sizeof(MyData));
Serial.print("Sending: ");
Serial.println(MyData.msg);
Serial.println(MyData.valor);
i = 0;
}
}
}
Further reading: