我将RF24库的数据结构从一个节点发送到另一个节点。这个结构包含两个字符串和一个浮点数。
当我使用发射器发送结构并将其打印到串行输出时,我得到了这个:
El sensor PIR situat en Menjador te el valor 1.00
当我将它打印到串行输出时,我在接收器中看到了这一点:
El sensor œ>U situat en Üߧŋ>r te el valor 1.00
为什么两个字符串发生了变化(" PIR"和#34; Menjador")?
结构如下:
struct sensorData {
String sensorType;
String sensorLocation;
float sensorValue;
} PIR1, sensor;
这是我把它写到收音机的方式:
radio.write( &PIR1, sizeof(PIR1) ));
这就是我从广播中读到的内容:
radio.read( &sensor, sizeof(sensor));
这就是我将它打印到接收器中的串行输出的方式:
void printOutData(sensorData* data) {
Serial.print("El sensor ");
Serial.print(data->sensorType);
Serial.print(" situat en ");
Serial.print(data->sensorLocation);
Serial.print(" te el valor ");
Serial.println(data->sensorValue);
}
谢谢!
答案 0 :(得分:0)
String
类型实际上不包含传感器类型和位置的字节;它指向到字节。您基本上是发送这些字节的内存地址,而不是字节本身。
您需要更改数据结构,以便包含结构内的字节,使用" C字符串" aka" char数组":
static const uint8_t SENSOR_TYPE_SIZE = 4;
static const uint8_t SENSOR_LOC_SIZE = 12;
struct sensorData {
char sensorType[ SENSOR_TYPE_SIZE ];
char sensorLocation[ SENSOR_LOC_SIZE ];
float sensorValue;
} PIR1, sensor;
当然,您必须更改设置这些成员值的方式。如果没有完整的草图,我只能提供一些可能性:
void setup()
{
Serial.begin( 9600 );
// Set to a constant value (i.e., a double-quoted string literal)
strncpy( PIR1.sensorType, "TMP", sizeof(PIR.sensorType)-1 );
PIR1.sensorType[ sizeof(PIR.sensorType)-1 ] = '\0'; // NUL-terminate
// Set to characters received over Serial, up to size-1 chars *or* a newline
// (This blocks until the line is entered! Nothing else will happen
// until the line has been completely received.)
size_t count = Serial.readBytesUntil( '\n', PIR1.sensorType, sizeof(PIR.sensorType)-1 );
PIR.sensorType[ count ] = '\0'; // NUL-terminate
}
void loop()
{
// Non-blocking receive of a line. Other things can be performed
// while we're waiting for the newline to arrive.
if (Serial.available()) {
// A char finally came in!
char c = Serial.read();
// end-of-line?
if (c == '\n') {
// Pressed ENTER, send what we have now
PIR.sensorLocation[ count ] = '\0'; // NUL-terminate the C string
radio.write( &PIR1, sizeof(PIR1) ));
// Reset for next time
count = 0;
} else { // not end-of-line, save another char (if there's room)
if (count < sizeof(PIR.sensorLocation)-1) {
PIR.sensorLocation[ count++ ] = c;
}
}
}
// Do some other things here... maybe check some buttons?
}
有许多理由可以避免String
,因此从长远来看,切换到char
数组实际上会得到回报。