Loading...
Logo
Processing Forum

byte conversion error

in Programming Questions  •  2 years ago  
Hi guys,

Im new here and just started implementing a graphing interface for AVR mcu. I have this piece of code which sends a data packet frame via serial to avr and it has a start and an end packet. I originally coded in C#. And could some one please help me implement this in processing ?

Basically all I want to do is send the following. But a byte I believe is from -128 to 128 and not 0 - 255. How can I easily do this conversion ?

DLE
packet id -> 0 - 255 bytes
error id -> 0 - 255 bytes
packet size -> 0 - 255 bytes
payload -> array of bytes (0-255)
checksum -> 0 - 255 bytes
DLE
ETX


Heres the code,

Copy code
  1. byte _packetID;
  2. byte _errorCode;
  3. byte _defaultPacketByteCount;
  4. byte _packetByteCount = 4;
  5. byte[] _dataPayload = new Byte[251];
  6. int _dataPtr = 0;
  7. byte _checkSum = 0;

  8. byte DLE = (byte)10;
  9. byte ETX = (byte)3;
  10. _packetID = (byte)2;
  11. _errorCode = (byte)1;
  12. _packetByteCount++;
  13. _dataPtr++;
  14. _dataPayload[0] = (byte)1;
  15. _checkSum = calcCheckSum();
  16.   
  17. byte[] packet = new byte[ 7 ];
  18. packet[0] = DLE;
  19. packet[1] = _packetID;
  20. packet[2] = _errorCode;
  21. packet[3] = _packetByteCount;
  22. packet[4] = _checkSum;
  23. packet[5] = DLE;
  24. packet[6] = ETX;

  25. myPort.write (packet);

  26. // checksum function

  27. byte calcCheckSum()
  28. {
  29.   //checksum calculated as sum of all bytes XORed with 0xFF.
  30.   char calculatedCheckSum = 0;
  31.   calculatedCheckSum += _packetID;
  32.   calculatedCheckSum += _errorCode;
  33.   calculatedCheckSum += _packetByteCount;
  34.   for (int i = 0; i < _dataPtr; i++)
  35.   {
  36.     calculatedCheckSum += _dataPayload[i];
  37.   }

  38.   calculatedCheckSum = (byte)calculatedCheckSum ^ (byte)0xFF;
  39.   return calculatedCheckSum;
  40. }

Replies(2)

More exactly, a byte is in the range -128 +127.
Your code seems OK on first sight, I would just use an int for calculatedCheckSum, perhaps.
But you don't tell us what is your problem exactly, and we cannot run you code, so I can't help much more currently.
Yeah I was getting invalid checksums due to the byte exceeding 127. And you are right it is 127 rather than 128  .

I think it seems fine now after I type cast it to a byte. But I will need to run some tests to make sure that that is the case.

Copy code
  1.    calculatedCheckSum = (byte)(calculatedCheckSum ^ (byte)0xFF);