Qt send full byte on serial port

3.5k Views Asked by At

I have this simple code that use QtSerialPort:

char foo[] = {130,50,'\0'};
serial->write(foo);

The result on my serial is {2, 50}. I think that che biggest number that I can send is 128 (char go from -128 to 128). Where is the manner for send number from 0 to 255? I try to use unsigned char but the method "write" don't work with it. The same problem also appear with QByteArray.

Thankyou all.

2

There are 2 best solutions below

2
On BEST ANSWER

The QIODevice interface has the default char for sending which may be compiler dependent. See the documentation for details.

qint64 QIODevice::write(const char * data, qint64 maxSize)

Writes at most maxSize bytes of data from data to the device. Returns the number of bytes that were actually written, or -1 if an error occurred.

However, you should not be concerned much if you take the data properly on the other hand. you can still send the greater than 128 values through as signed, but they will come across as negative values, for instance 0xFF will be -1.

If you take the same logic in the reverse order on the receiving end, there should be no problems about it.

However, this does not seem to relate to your issue because you do not get the corresponding negative value for 130, but you get it chopped at 7 bits. Make sure you connection is 8 data bit.

You can set that explicitly after opening the port with this code:

QSerialPort serialPort;
QString serialPortName = "foo";
serialPort.setPortName(serialPortName);

if (!serialPort.open(QIODevice::WriteOnly)) {
    standardOutput << QObject::tr("Failed to open port %1, error: %2").arg(serialPortName).arg(serialPort.errorString()) << endl;
    return 1;
}   

if (!serialPort.setDataBits(QSerialPort::Data8)) {
    standardOutput << QObject::tr("Failed to set 8 data bits for port %1, error: %2").arg(serialPortName).arg(serialPort.errorString()) << endl;
    return 1;
} 

// Other setup code here

char foo[] = {130,50,'\0'};
serialPort.write(foo);
0
On

Make sure you've set the serial port to send 8 bits, using QSerialPort::DataBits

The fact that '130' is coming as '2' implies that the most significant bit is being truncated.