Qt Serial Port - Unable to Read



  • I'm trying to read a serial port with the Qt SerialPort library. I can read the data using HyperTerminal.

    In Qt I used the following code to try and do the same thing. Qt says the the port has been opened correctly, but for some reason, the bytesAvailable from the serial port is always 0.

    Can anyone help? Thanks in advance!

    serial.setPortName("COM20");

    if (serial.open(QIODevice::ReadOnly))
    qDebug() << "Opened port " << endl;
    else
    qDebug() << "Unable to open port" << endl;

    serial.setDataBits(QSerialPort::Data8);

    serial.setParity(QSerialPort::EvenParity);

    serial.setBaudRate(QSerialPort::Baud115200);

    qDebug() << "Is open?? " << serial.isOpen();

    // Wait unit serial port data is ready
    while (!serial.bytesAvailable())
    {
    //qDebug() << serial.bytesAvailable()<<endl;
    continue;
    }

    QByteArray data = serial.read(100);

    qDebug() << "This is the data -" << data << endl;

    serial.close();
    In comparison, MATLAB code with the same structure as the above code, successfully manages to read the serial port data

    %Serial Port Grapher - Shurjo Banerjee

    s = serial('COM20');
    s.BaudRate = 460800;
    s.Parity = 'even';

    try
    input('Ready to begin?');
    catch
    end

    fopen(s);

    fh = figure();
    hold on;

    t = 1;

    while (s.BytesAvailable <= 0)
    continue
    end
    a = fread(s, 1)

    old_t = 1;
    old_a = a;

    while true

    if (s.BytesAvailable > 0)
    a = fread(s, 1)

        figure(fh)
        t = t + 1;
        plot([old_t t], [old_a a]);
        old_t = t;
        old_a = a;
    end
    

    end

    fclose(s);


  • Lifetime Qt Champion

    Hi and welcome to devnet,

    You can't translate the code from MatLab 's serial to QSerialPort like that. QSerialPort should be used asynchronously (there's currently a bug preventing the use of the synchronous API).

    Please have a look at the examples to see how it's handled.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.