I'm working on a project where I'm sending various size packets to some equipment.
I'm trying to create a class or template or something that will send the packets, make a note for debugging, and calculate a checksum.
This is all point to point, so there is no header, strangely.
How can I do this? Why is this reporting wrong packet information? See log below..
#include <Arduino.h>
#include <Vector.h>
const unsigned int interPacketDelay = 500;
#define debugMode 1
//debugging
#if debugMode == 1
#define debug(x) Serial.print(x)
#define debugln(x) Serial.println(x)
#define debuglnHEX(x) Serial.println(x, HEX)
#else
#define debug(x)
#define debugln(x)
#define debuglnHEX(x)
#endif
class writeSerial {
public:
writeSerial(Stream &p) : port(p) {
}
void writePacket(byte data[], String identifier) {
unsigned int length = sizeof(data);
debug("Sending "); debug(length); debug(" byte packet for: "); debugln(identifier);
appendChecksum(data, identifier, length);
delay(interPacketDelay );
//port.write(data, length);
debug("--Sent "); debugln(identifier);
}
void appendChecksum(byte data[], String identifier, unsigned int length) {
data[length - 1] = calculateChecksum(data, length - 2);
debug("..Calculated Checksum for "); debug(identifier); debug(": "); debuglnHEX(data[length - 1]);
}
byte calculateChecksum(byte data[], unsigned int length){
byte chk = 0;
for (int i=0; i<length; i++) {
chk += data[i];
}
chk = chk % 256;
return chk;
}
private:
Stream &port;
};
writeSerial xs(Serial);
void setup() {
Serial.begin(115200);
byte test10[10] = {0x00,0xFF,0x00,0xFF,0x00,0xFF,0x00,0xFF,0x00,0x00};
xs.writePacket(test10, "Should be 10 bytes long");
byte test3[3] = {0x00,0xFF,0x00};
xs.writePacket(test3, "Should be 3 bytes long");
byte test1[1] = {0x00};
xs.writePacket(test1, "Should be 1 byte long");
}
void loop() {
}
Results:
Sending 2 byte packet for: Should be 10 bytes long
..Calculated Checksum for Should be 10 bytes long: 0
--Sent Should be 10 bytes long
Sending 2 byte packet for: Should be 3 bytes long
..Calculated Checksum for Should be 3 bytes long: 0
--Sent Should be 3 bytes long
Sending 2 byte packet for: Should be 1 byte long
..Calculated Checksum for Should be 1 byte long: 0
--Sent Should be 1 byte long