PDA

View Full Version : calculating checksum in serialcommunication



jjbabu
12th October 2007, 08:14
hi to all,
i am sending some data through the serial port using the "qextserial port".while sending the data,am converting evrything to ascii values.like this
port->write(QString::QString(":").toAscii());//converted char":" to string and sending
port->write(QString::number(3).toAscii());//converted number to string and sending.

here the data is transmitting like a packet,so i need to calculate check sum for that packet.
the rule we follow to calculate check sum is addition of all ascii values of data which we r sending.
for this i did like bellow,
QString sum;
sum= QString(":").toAscii();
sum=sum+(QString::number(3).toAscii()); ......//like this untill end
my problem is not getting check sum as a single data(like char+char=char)
the output i am getting for above is like in the format of strings concordination(: 3)

how to calculate the checksum plz kindly help me.

thanx in advance

ChristianEhrlicher
12th October 2007, 09:30
Put all data to send into a QByteArray and iterate of them to calculate your checksum.

And please don't do things like


port->write(QString::QString(":").toAscii());

Conversion from Ascii to QString and back is useless. Also QString(":") would be enough.

jjbabu
12th October 2007, 10:50
thanx for ur reply ChristianEhrlicher,
but sorry to say that am not understood ur explanation,
once again i will explain what i did for my explanation,

my packet structure is like this,
startbit- ":" , packet id-"3" , total no.of bytes - "no." , variable1 ,variable 2,variable3......,checksum.

*ALL VARIABLES ARE USER CHOICE*

for this structure,according to "qextseriaport example" i wrote the code as bellow:

port->write(QString::QString(":").toAscii());
port->write(QString::number(3).toAscii());
port->write(QString::number(0).toAscii()); //this is variable 1,either 1 or 0

int X=ui.spinBox->value();
port->write(QString::number(X).toAscii());
:
:
like continuously i wrote the values to the serialport.

now tell me how can i add all the characters to calculate checksum.
if u have any sample code please provide to me.
thanx alot,

ChristianEhrlicher
12th October 2007, 11:16
I won't provide sample code because *you* should learn.

Don't write the data to port but instead to a QByteArray. After this, you can calculate the checksum of this bytearray and then write the whole bytearray to port.

jjbabu
12th October 2007, 12:38
ok,i got the idea ChristianEhrlicher,
instead of writing into the port,i will take the data to the QByteArray.
onething i dont understand from ur explanation is,addition of all data elements in the QByteArray,how can i do this?
>can i add the data elements directly?
can u provide some sample prototype for this?
thanx in advance.

ChristianEhrlicher
12th October 2007, 12:43
Just use QByteArray::append() (http://doc.trolltech.com/4.3/qbytearray.html#append-3) instead port->write() and all should work fine