If the rfid reader sends the STX signal as "02" instead of 0x02, you'll have to change the code and add another state to the state machine.
It's still a mystery to me why it converts ASCII to ASCII. It makes much more sense to just send 0x02 33 44 03 for example (this is the binary representation of 'STX', '3', 'D', 'ETX') instead of 0x30 32 33 33 34 34 30 33 ('0', '2', '3', '3', '4', '4', '0', '3').
Pieter
This piece of code parses "0230313046313737454341414403" to "010F177ECAAD":
#define STX1 '0'
#define STX2 '2'
#define ETX1 '0'
#define ETX2 '3'
const size_t LEN = 24; // length of the expected message (e.g. 12 ASCII characters in hex = 12 * 2 = 24)
void setup() {
Serial.begin(115200);
}
char buffer[LEN + 1]; // 24 characters + terminating null character
uint8_t index = 0;
bool receiving = false;
char prevByte = 255;
void loop() {
if (Serial.available() > 0) {
char serialByte = Serial.read();
if (serialByte == STX2 && prevByte == STX1) { // start character STX received
receiving = true;
index = 0;
} else if (receiving) {
if (index > LEN) { // message is too long
receiving = false;
}
if (index % 2 && serialByte == ETX2 && prevByte == ETX1) { // end character ETX received at even position
buffer[index - 1] = '\0';
parse(buffer, index);
receiving = false;
} else {
buffer[index++] = serialByte;
}
}
prevByte = serialByte;
}
}
void parse(char* input, size_t length) {
Serial.print("Input:\t");
Serial.println(input);
Serial.print("Length:\t");
Serial.println(length);
size_t numberOfHexChars = (length-1) / 2;
char hexChars[numberOfHexChars + 1];
for (int i = numberOfHexChars - 1; i >= 0; i--) {
input[2 * i + 2] = '\0';
hexChars[i] = strtoul(&input[2 * i], NULL, 16);
}
hexChars[numberOfHexChars] = '\0';
Serial.print("Hex:\t");
Serial.println(hexChars); Serial.println();
}