我是QT C ++的新手,正在尝试编写一个程序,该程序可以连续从串行端口读取数据。我的程序有时运行顺利,但有时会读取错误的数据。我已经运行了调试,这就是我得到的:
"61\x00\x00"
"61\x00\x00"
"61\x00\x00"
"62\x00\x00"
"62\x00\x00"
"62\x00\x00"
"62\x00\x00"
"63\x00\x00"
"63\x00\x00"
"5"
"3\x00\x00"
"5"
"2\x00\x00"
"5"
"2\x00\x00"
"54\x00\x00"
"54\x00\x00"
"54\x00\x00"
"55\x00\x00"
"54\x00\x00"
"54\x00\x00"
"55\x00\x00"
"55\x00\x00"
"5"
"1\x00\x00"
"51"
"\x00\x00"
"5"
"2\x00\x00"
"5"
"1\x00\x00"
"5"
"1\x00\x00"
有时QTSerialPort无法读取所有数据。这是我的代码,应该在其中读取和显示数据。
if(serial->isOpen() && serial->isReadable()){
QByteArray receivedData;
receivedData = serial->readAll();
qDebug()<<receivedData;
ui->lcdDistance->display(receivedData.toInt());
}else{
QMessageBox::critical(this, tr("Error"), tr("Doesn't receive data"));
}
我认为问题出在QT,而不是微控制器,因为我也使用微控制器运行调试,并且效果很好。
这是我的uC STM32中的代码
while (1) {
HAL_UART_Receive(&huart2, rxData, 1, 1000);
if (rxData[0] == '1') { //RUN
HAL_GPIO_WritePin(GPIOA, GPIO_PIN_5, SET);
lcd_clear();
lcd_put_cur(0, 0);
lcd_send_string("LOADING...");
HAL_Delay(1000);
lcd_clear();
int i = 40;
//HAL_Delay(1000);
while (i < 100) {
htim2.Instance->CCR1 = i;
sensor_time = hcsr04_read();
distance = sensor_time * .034 / 2;
sprintf(str_distance,"%lu", distance);
lcd_clear();
lcd_put_cur(1, 0);
lcd_send_string(str_distance);
sendDistanceStatus = HAL_UART_Transmit(&huart2, str_distance, sizeof(str_distance),
100);
if (sendDistanceStatus == HAL_OK) {
i++;
HAL_Delay(300);
}
}
HAL_Delay(1000);
} else { //STOP
HAL_GPIO_WritePin(GPIOA, GPIO_PIN_5, RESET);
lcd_clear();
lcd_put_cur(0, 0);
lcd_send_string("STOP...");
}
}
请帮助我解决此问题。预先感谢。
答案 0 :(得分:0)
问题是信息的同步,因为在信息开始和结束时无法检测到它。一个简单的解决方案是使用像endline(\n
)这样的字符:
sprintf(str_distance,"%lu\n", distance);
if(serial->isOpen() && serial->isReadable()){
while(serial->canReadLine()){
QByteArray ba = serial->readLine();
ba = ba.replace('\0', QByteArray());
qDebug() << ba;
ui->lcdDistance->display(ba.toInt());
}
}