使用 Arduino,我打印一个整数和一个 float ,如下所示(我在循环中执行):
delay(500);
Serial.print(tempSensor);
delay(500);
Serial.print(LDRSensor);
另一方面,我使用 Qt 的“QSerialPort”从串行读取,如下所示:
serial.setPortName("COM3");
serial.open(QIODevice::ReadWrite);
serial.setBaudRate(QSerialPort::Baud9600);
serial.setDataBits(QSerialPort::Data8);
serial.setParity(QSerialPort::NoParity);
serial.setStopBits(QSerialPort::OneStop);
serial.setFlowControl(QSerialPort::NoFlowControl);
while(!serial.isOpen()) serial.open(QIODevice::ReadWrite);
if (serial.isOpen() && serial.isWritable()){
QByteArray input, input1;
std::chrono::seconds interval(1);
for (int i = 0; i < 3; ++i){ \\Read from serial for 3 seconds
serial.waitForBytesWritten(250);
serial.waitForReadyRead(250);
Sleep(490);
input = serial.readAll(); \\First value
}
serial.waitForBytesWritten(250);
serial.waitForReadyRead(250);
Sleep(490);
input1 = serial.readAll(); \\Second value
}
问题是“阅读器”有时会先读取“tempSensor”,然后再读取“LDRSensor”,有时反之亦然。我可以将“QSerialPort”设置为始终先接收 tempSensor 然后再接收 LDRSensor,以便我可以将它们分别保存在不同的数组中吗?
最佳答案
我会让它变得非常简单。你可以尝试在发送方做这样的事情:
Serial.print('T'); //start of the temperature message
Serial.print(tempSensor); //temp value
Serial.print('\n'); //end of line
Serial.print('L'); //start of the LDR message
Serial.print(LDRSensor); //LDR value
Serial.print('\n'); //end of line
delay(1000);
在接收方:
while (your condition)
{
while (serial.canReadLine())
{
QString message = serial.readLine();
message = message.trimmed(); //remove the end of line character
QString strVal = message.mid(1); //remove the first character
int value = strVal.toInt(); //convert to int
if (message.startsWith("T"))
{
// Temp received
}
else if (message.startsWith("L"))
{
// LDR received
}
}
Sleep(10);
}
但我绝对建议您不要循环阅读,而应使用信号。
关于c++ - 分别读取序列值和保存值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43228343/