Connecting to Serial port in QT

8.8k views Asked by At

I'd like to connect to a microcontroller using QSerialPort. I've added the line serial port to my .pro file, included QSerialPort in my source file and ran qmake. My code is below:

    serial.setPortName("COM3");
    serial.setBaudRate(QSerialPort::Baud9600);
    serial.setDataBits(QSerialPort::Data8);
    serial.setParity(QSerialPort::NoParity);
    serial.setStopBits(QSerialPort::OneStop);
    serial.setFlowControl(QSerialPort::NoFlowControl);
    serial.open(QIODevice::ReadWrite);
    serial.write("ok*");

When I run the code I get a message saying the device is not open though I've confirmed it's open with TeraTerm. What am I missing? The error message is below:

QIODevice::write: device not open
1

There are 1 answers

0
Jablonski On BEST ANSWER

First of all, you should check is open returns true. If no, then tell to user about error and call errorString()

if(serial.open(QIODevice::ReadWrite))
    serial.write("ok*");
else
{
    //error
    qDebug() << serial.errorString();
}

You try to open one port in different programs. It is forbidden in Windows. So you can't use this. In your video author open com3 in Qt but com4 in teraterm, it is different ports, so you should use same thing, not one port for few programs.

Pay attention on this program: com0com