[英]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.