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,
- byte _packetID;
- byte _errorCode;
- byte _defaultPacketByteCount;
- byte _packetByteCount = 4;
- byte[] _dataPayload = new Byte[251];
- int _dataPtr = 0;
- byte _checkSum = 0;
- byte DLE = (byte)10;
- byte ETX = (byte)3;
- _packetID = (byte)2;
- _errorCode = (byte)1;
- _packetByteCount++;
- _dataPtr++;
- _dataPayload[0] = (byte)1;
- _checkSum = calcCheckSum();
- byte[] packet = new byte[ 7 ];
- packet[0] = DLE;
- packet[1] = _packetID;
- packet[2] = _errorCode;
- packet[3] = _packetByteCount;
- packet[4] = _checkSum;
- packet[5] = DLE;
- packet[6] = ETX;
- myPort.write (packet);
- // checksum function
- byte calcCheckSum()
- {
- //checksum calculated as sum of all bytes XORed with 0xFF.
- char calculatedCheckSum = 0;
- calculatedCheckSum += _packetID;
- calculatedCheckSum += _errorCode;
- calculatedCheckSum += _packetByteCount;
- for (int i = 0; i < _dataPtr; i++)
- {
- calculatedCheckSum += _dataPayload[i];
- }
- calculatedCheckSum = (byte)calculatedCheckSum ^ (byte)0xFF;
- return calculatedCheckSum;
- }
1