我正在向串行端口写入一个字符并从中读取相同的字符。但我无法读取我发送的相同字符,我收到了不同的字符。
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include "radialbar.h"
#include <QtSerialPort/QSerialPortInfo>
#include <QDebug>
int main(int argc, char *argv[])
{
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
#endif
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;
qmlRegisterType<RadialBar>("CustomControls", 1, 0, "RadialBar");
const QUrl url(QStringLiteral("qrc:/main.qml"));
QObject::connect(&engine, &QQmlApplicationEngine::objectCreated,
&app, [url](QObject *obj, const QUrl &objUrl) {
if (!obj && url == objUrl)
QCoreApplication::exit(-1);
}, Qt::QueuedConnection);
engine.load(url);
// Open the serial port after the QML engine loads
QSerialPort serialPort;
serialPort.setPortName("/dev/ttyUSB0"); // Change this to your serial port name
serialPort.setBaudRate(QSerialPort::Baud9600);
serialPort.setDataBits(QSerialPort::Data8);
serialPort.setParity(QSerialPort::NoParity);
serialPort.setStopBits(QSerialPort::OneStop);
serialPort.setFlowControl(QSerialPort::NoFlowControl);
if (!serialPort.open(QIODevice::ReadWrite)) {
qDebug() << "Failed to open serial port:" << serialPort.errorString();
return 1;
}
if(serialPort.isOpen())
{
qDebug() << "Serial port is opened";
char ch_tx = 'a';
qDebug() << "Sending data is" << ch_tx;
serialPort.write(&ch_tx);
char ch_rx;
if (serialPort.waitForReadyRead(5000)) {
if (serialPort.getChar(&ch_rx)) {
qDebug() << "Received data is" << ch_rx;
} else {
qDebug() << "Error reading from serial port:" << serialPort.errorString();
}
} else {
qDebug() << "Timeout occurred while waiting for data to be read.";
}
}
// Close the serial port
serialPort.close();
return app.exec();
}
我尝试使用UTF-8进行编码和解码,但这不起作用。
也许你的imx8板面有错误。
您可以在Windows操作系统上检查您的qt应用程序。
我建议你在windows上安装虚拟串口模拟器并以桥接模式打开两个虚拟串口。之后你就可以使用任何串口程序了。
在这种情况下,您可以在没有硬件和IMX8软件的情况下检查QT端。
您可以通过此链接下载虚拟串口程序 https://freevirtualserialports.com/