I am new for QT C++ and am trying to write a program, which could continuous read data from Serial Port. My Program works sometimes smoothly but sometimes it read the wrong data. I have run debug and here is what I got:
"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"
Someway QTSerialPort didn't read all data. And here is my code, where data should be read and display.
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"));
}
I think the problem came from QT, not the microcontroller because I also run debug with my microcontroller and it worked very well.
Here is the code in my 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...");
}
}
Please help me to solve this problem. Thanks in advance.
The problem is the synchronization of the information since it cannot be detected when the information starts and ends. A simple solution is to use a character like the 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());
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.