[英]Qt serial port does not read the string well
我在Ubuntu Gnome 14.04 LTS上使用Qt 5.4從串行端口讀取字符串行。 一切正常,但是當我重新安裝Ubuntu Gnome 14.04和Qt 5.4時,我的串行端口代碼無法正常工作。 當Arduino發送“ 0”時,Qt的代碼將以“ ...”的形式讀取它,而其他通過串行方式發送的數字則以Qt的字母和符號來讀取。 我認為我的Qt的unicode問題。 我的ubuntu的unicode是en.US.UTF-8,而QT unicode設置為“ system”。 請幫助我:(這是我的代碼,可從串行端口讀取數據:
QByteArray input;
if (serial->canReadLine()) //chect if data line is ready
input.clear();
input = serial->readLine(); //read data line from sreial port
ui->label->setText(input);
qDebug ()<<input<<endl;
Arduino的此代碼可與CuteCom和Arduino串行監視器一起正常工作
const int analogInPin = A0;
unsigned int sensorValue = 0; // value read from the pot
void setup() {
Serial.begin(19200);
}
void loop() {
Serial.print("\n");
Serial.print("#");
for (int i=0; i < 5; i++) {
// read the analog in value:
sensorValue = analogRead(analogInPin);
Serial.print(sensorValue);
Serial.print("#");
};
sensorValue = analogRead(analogInPin);
Serial.print(sensorValue);
Serial.print("# \n");
}
對不起我的英語不好
如果奇偶校驗或數據/停止位參數不同,您仍然可以寫入和讀取,但是會得到類似於上面顯示的“有趣”輸出,這不是unicode設置的問題(特別是不是'0 ',這是ASCII集的字符)。
在開始通信之前,嘗試在兩端顯式設置相同的端口參數。
有幾個問題:
您沒有發布足夠的代碼來了解如何使用它的上下文。 我假設您以附加到readyRead
信號的方法處理數據。
您只讀一行,應該讀一行直到沒有更多可用。 可以發出任意數量的字節以讀取readyRead
信號,以供讀取:這些字節可能不完整,也可能不完整! 如果在沒有更多可用數據之前不繼續讀取數據,那么您將嚴重落后於輸入數據。
您正在使用隱式QByteArray
到QString
轉換。 這些是不好的代碼氣味。 明確一點。
您有相當冗長的代碼。 您不需要在設置QByteArray
值之前清除它。 您還應該在使用時聲明它。 更好的是,使用C ++ 11帶來的類型推斷。
從而:
class MyWindow : public QDialog {
QSerialPort m_port;
void onData() {
while (m_port->canReadLine())
auto input = QString::fromLatin1(m_port->readLine());
ui->label->setText(input);
qDebug() << input;
}
}
...
public:
MyWindow(QWidget * parent = 0) : QDialog(parent) {
...
connect(&m_port, &QIODevice::readyRead, this, &MyWindow::onData);
}
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.