K.R*_*ert 4 qt serial-port qt5
#include <QSerialPort>
#include <QSerialPortInfo>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
// Example use QSerialPortInfo
foreach(const QSerialPortInfo &info, QSerialPortInfo::availablePorts()) {
// Example use QSerialPort
QSerialPort serial;
serial.setPort(info);
if (serial.open(QIODevice::ReadWrite))
//I try to send a string of hexadecimal numbers?seems not right
//serial.write(QByteArray("0xFF010100FFFFFF"));
serial.close();
}
return a.exec();
}
Run Code Online (Sandbox Code Playgroud)
上面的例子展示了如何打开所有可用的串口,然后关闭它们。但是我想打开一个给定的串口,比如 COM6,设置它的 BaudRate,DataBits,Parity,StopBits,FlowControl 然后发送一串十六进制数字。
这个视频一定能帮到你:https : //www.youtube.com/watch?v=UD78xyKbrfk
你也可以在这里找到类似的代码:https : //cboard.cprogramming.com/cplusplus-programming/169624-read-write-serial-port.html
示例代码:
#include <QSerialPort>
MySerialPort::MySerialPort()
{
serial = new QSerialPort(this);
openSerialPort();
}
void MySerialPort::openSerialPort()
{
serial->setPortName("COM3");
serial->setBaudRate(QSerialPort::Baud9600);
serial->setDataBits(QSerialPort::Data8);
serial->setParity(QSerialPort::NoParity);
serial->setStopBits(QSerialPort::OneStop);
serial->setFlowControl(QSerialPort::NoFlowControl);
if (serial->open(QIODevice::ReadWrite))
{
//Connected
}
else
{
//Open error
}
}
void MySerialPort::writeData(const QByteArray &data)
{
serial->write(data);
}
Run Code Online (Sandbox Code Playgroud)