K.Robert
K.Robert

Reputation: 235

How to write data to a given serial port with qt?

#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();
}

The example above shows how to open all available serial ports and then close them. But I want to open a given serial port, such as COM6, set its BaudRate,DataBits,Parity,StopBits ,FlowControl and then send a string of hexadecimal numbers.

Upvotes: 4

Views: 21067

Answers (1)

ni1ight
ni1ight

Reputation: 347

This video will definitely help you: https://www.youtube.com/watch?v=UD78xyKbrfk

You can also find similar code here: https://cboard.cprogramming.com/cplusplus-programming/169624-read-write-serial-port.html

Example code:

#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);
}

Upvotes: 5

Related Questions