Sending Hex data to a serial device



  • Hello everyone,

    I am researching on ways to send hex data to a serial device. Currently using QSerialPort to connect to the device.

    As an example I need to send the following data through serial:

     0000 0000 0000 0000 0000 0000 0000 00aa
     0000 0202 cc00 0000 0000 0000 0000 0000
     0a                                       
    

    Would QByteArray be a good option ? Can anyone give me a pratical example ?



  • Hexadecimal is a human readable text representation of binary data,
    Do you want to send the hex string or the actual binary values it represents?

    If you have this string in a QByteArray:

    QByteArray b("0000 0000 0000 0000 0000 0000 0000 00aa")
    

    and your want to send the hex string then you simply use this with QIODevice::write(). If you want to send the binary values that string represents then you have to pre-process it to convert from the human-readable string to the equivalent bytes. That might be as trivial as:

    QByteArray t = b.replace(" ", ""); // remove the spaces
    QByteArray bytes = b.fromHex(); // convert from hex to binary
    device.write(bytes);
    

    but it may be more complicated if the pairs of bytes represent 16-bit integers because you may have to consider byte order.



  • @ChrisW67 says:

    QByteArray t = b.replace(" ", ""); // remove the spaces
    QByteArray bytes = b.fromHex(); // convert from hex to binary
    device.write(bytes);
    

    I've tried this but fromHex is a static method. Gonna give some feedback on data later on.



  • @Alfredo-Palhares
    Hi, QByteArray should work properly on binary datas, even if there are many bytes which are not ASCII charactors. For QByteArray represent and save it's content length with it's own member variable, instead of working as a null-terminated string.
    For initializing a QByteArray instance with a binary sequence like your example, you can write code like this:

    QByteArray foo("\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xaa\
    \x00\x00\x02\x02\xcc\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\
    \x0a");
    

    For sending these datas through a QSerialPort object, you can simply do it like this:

    serialport.write(foo);
    


  • @Alfredo-Palhares
    Indeed, QByteArray::fromHex() is static, my bad.

    QByteArray t = b.replace(" ", ""); // remove the spaces
    QByteArray bytes = QByteArray::fromHex(t); // convert from hex to binary
    device.write(bytes);
    


  • @Alfredo-Palhares

    you can also use a uin16_t array.

    uint16_t data[] = {0x0000, 0x0000, 0x0000, ... 0x00AA, 0x0000, 0x0202 ...};

    serial->write(data, sizeof(data));


Log in to reply
 

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