我正在尝试制作一个连接到 RS232 设备并发送一些命令的 C++ 程序。我目前试图一次只发送一个命令,但我遇到了问题。看起来当我在不调用 serial.close() 的情况下发送命令时,我收到了设备的响应命令,告诉我没问题,但在那之后,串口关闭。如果我调用 serial.close(),我可以根据需要多次发送命令,但设备不会响应。下面是我的部分代码,包含我使用的设置和连接顺序:
/*Create the serial port and configure it*/
QSerialPort serial;
serial.setPortName("COM39");
serial.setBaudRate(QSerialPort::Baud9600);
serial.setDataBits(QSerialPort::Data8);
serial.setParity(QSerialPort::NoParity);
serial.setStopBits(QSerialPort::OneStop);
serial.setFlowControl(QSerialPort::NoFlowControl);
/*Connect to serial port and send the command*/
if(serial.open(QIODevice::ReadWrite)){
ui->label->setText("Connected");
serial.write("NOW11000000.....mENDBAAF");
//serial.close();
qDebug()<<"Command sent";
}
else{
ui->label->setText("Not Connected");
}
我正在使用端口监控软件查看设备是否通过 COM39 端口与我的程序通信,这就是我找出问题所在的方法。 我尝试编写一个打开端口的函数,但它进入无限循环或无法正常工作。
最佳答案
问题是我在 if 指令中调用了 serial.open(),这导致它每次执行只打开一次。为了工作,我将 serial.open() 方法放在端口配置之后。正确且完整的代码(对我有用)是这样的:
/*Create the serial port and configure it*/
QSerialPort serial;
serial.setPortName("COM39");
serial.setBaudRate(QSerialPort::Baud9600);
serial.setDataBits(QSerialPort::Data8);
serial.setParity(QSerialPort::NoParity);
serial.setStopBits(QSerialPort::OneStop);
serial.setFlowControl(QSerialPort::NoFlowControl);
/*Connect to serial port and send the command*/
if(serial.open(QIODevice::ReadWrite)){
ui->label->setText("Connected");
serial.write("NOW11000000.....mENDBAAF");
//serial.close();
qDebug()<<"Command sent";
}
else{
ui->label->setText("Not Connected");
}
关于c++ - 发送命令后串口关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32452304/