0

I am finding way to send hex data via serial communication i searched it several times and followed some ways but it didn't work. i checked that protocol is working with using other software that sending hex data to device below is my code

const char data[]={0xAA,0xAA,0x01,0x00,0x00,0x0E,0x00,0x01,0x00,0x00,0x00,0x2D,0x37,0x1D,0xAA,0xAA,0x01,0x00,0x00,0x0E,0x00,0x0C,0x10,0x00,0x00,0x01,0x76,0x13}; 
serial->setPortName(("COM8"));
initSerialPort(); // baud rate and etc

if(serial->open(QIODevice::ReadWrite))
{
    qDebug()<<"Port is open!";
    if(serial->isWritable())
    {
        qDebug()<<"Yes, i can write to port!";
       int size = sizeof(data);
       serial->write(data,size);
    }
}

and when i use other declare like uint16_t, uchar, write function cannot convert argument 1 from uint16_t (or uchar) to const char *

i did try also this form

QByteArray hex("AAAA0100000E00010000002D371DAAAA0100000E000C100000017613");
QByteArray data = QByteArray::fromHex(hex);

and it also didnt work

  • *and when i use other declare [...] write function cannot convert argument* - well, don't use it then? What is it that you're trying to do would be the most important thing. The `QByteArray data` version works great, but of course it doesn't need the `size` argument since the whole point of array/vector classes is so they know their own size so you don't need to write C code anymore. – Kuba hasn't forgotten Monica Mar 13 '21 at 23:15
  • QByteArray has the ability to serialize values and this operation done by the "<<" operator. predefined variables have "<<" operator and for the user-defined variable, you must reimplement the "<<" operator. see this topic --> https://stackoverflow.com/questions/33217592/how-to-simply-serialize-complex-structures-and-send-them-over-a-network-in-qt – SajadBlog Mar 14 '21 at 05:19

1 Answers1

0

You can do this using only QByteArray like:

connect(serial, &QSerialPort::readyRead, this, &YourClass::doSomeStuff);

QByteArray arr;

arr += static_cast<char>(0xAA);
arr += static_cast<char>(0x01);

<...>

serial->setPortName("COM8");
initSerialPort(); // baud rate and etc

if(serial->open(QIODevice::ReadWrite) && serial->isWritable())
    serial->write(arr);
Shtol Krakov
  • 1,260
  • 9
  • 20