Alex
Alex

Reputation: 107

Serial port closing after sending a command

I am trying to make a c++ program that connects to a RS232 device and sends some commands. I am currently trying to send only one command at a time, but I have a problem with it. It looks like when I send the command without calling serial.close(), I get the response command from the device telling me it's okay, but after that, the serial port closes. If i call the serial.close(), I can send the command as many times as I want, but the device doesn't respond back. Below is part of my code, containing the settings and the connect sequence I use:

/*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");
}

I am using a port monitoring software to see if the device is communicating with my program through the COM39 port and that's how I figured out what is the problem. I tried writing a function that opens the port but it goes into a infinite loop or isn't working.

Upvotes: 1

Views: 886

Answers (1)

Alex
Alex

Reputation: 107

The problem was that I called the serial.open() in the if instruction, and that caused it to be opened only once per execution. To work, I placed the serial.open() method just right after the configuration of the port. The correct and complete code (that is working for me) is this:

/*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");
}

Upvotes: 1

Related Questions