Search code examples
qthexportqbytearray

Is this code send hex data in correct way in Qt C++?


I am new to Qt.I am working on finger print madoule with this document. I want to send my data to serial port in this format:
enter image description here I wrote my code in this format, but I think my data has mistake, because this code turn on the LED in some device:

QByteArray ba;
ba.resize(24);
ba[0]=0x55;
ba[1]=0xAA;
ba[2]=0x24;
ba[3]=0x01;
ba[4]=0x01;
ba[5]=0x00;
ba[6]=0x00;
ba[7]=0x00;
ba[8]=0x00;
ba[9]=0x00;
ba[10]=0x00;
ba[11]=0x00;
ba[12]=0x00;
ba[13]=0x00;
ba[14]=0x00;
ba[15]=0x00;
ba[16]=0x00;
ba[17]=0x00;
ba[18]=0x00;
ba[19]=0x00;
ba[20]=0x00;
ba[21]=0x00;
ba[22]=0x27;
ba[23]=0x01;

p->writedata(ba);  

Is this data correct?


Solution

  • You're just copying a drawing into code. It won't work without understanding what the drawing means. You seem to miss that:

    1. The LEN field seems to be a little-endian integer that gives the number of bytes in the DATA field - perhaps it's the number of bytes that carry useful information if the packet has a fixed size.

    2. The CKS field seems to be a checksum of some sort. You need to calculate it based on the contents of the packet. The protocol documentation should indicate whether it's across the entire packet or not, and how to compute the value.

    It seems like you are talking to a fingerprint identification module like FPM-1502, SM-12, ADST11SD300/310 or similar. If so, then you could obtain a valid command packet as follows:

    QByteArray cmdPacket(quint16 cmd, const char *data, int size) {
      Q_ASSERT(size <= 16);
      QByteArray result(24, '\0');
      QDataStream s(&result, QIODevice::WriteOnly);
      s.setByteOrder(QDataStream::LittleEndian);
      s << quint16(0xAA55) << cmd << quint16(size);
      s.writeRawData(data, size);
      s.skipRawData(22 - s.device()->pos());
      quint16 sum = 0;
      for (int i = 0; i < 22; ++i)
         sum += result[i];
      s << sum;
      qDebug() << result.toHex();
      return result;
    }
    
    QByteArray cmdPacket(quint16 cmd, const QByteArray& data) {
       return cmdPacket(cmd, data.data(), data.size());
    }
    

    The command packet to turn the sensor led on/off can be obtained as follows:

    QByteArray cmdSensorLed(bool on) {
       char data[2] = {'\0', '\0'};
       if (on) data[0] = 1;
       return cmdPacket(0x124, data, sizeof(data));
    }