There are several issues with your sketch. The most important is the lack of understanding for the difference between internal and external representation.
The sketch reads a single character from Serial and prints the value as a hexadecimal number. The character is ASCII; a number that represents symbols in our alphabet.
Your goal is to read characters into a string and then convert the string to a number assuming that the string represents a hexadecimal number ('0'..'9' and 'a'..'f' or 'A'..'F').
The sketch should be 1) scan string, 2) parse and convert string to number, 3) print the number.
Scanning the string requires skipping whitespace and then collecting characters until a whitespace.
The sketch could look something like this:
void setup() {
Serial.begin(57600);
while (!Serial);
Serial.println(F("Serial started..."));
}
void loop() {
const size_t BUF_MAX = 16;
char buf[BUF_MAX];
char* bp = buf;
char c;
// Skip whitespace
do {
while (!Serial.available());
c = Serial.read();
} while (c <= ' ');
// Scan token until whitespace
*bp = c;
do {
while (!Serial.available());
c = Serial.read();
*++bp = c;
} while (c > ' ');
*bp = 0;
// Print scanned token
Serial.println(buf);
// Convert to number and print
const int BASE = 16;
long val = strtol(buf, &bp, BASE);
if (*bp == 0)
Serial.println(val);
else
Serial.println(F("not a number"));
}
This allows scan of hexadecimal numbers with possible sign (as defined by strtol
). By changing the BASE to zero strtol
will use the notations for base definitions (prefix '0' for octal, '0x' for hexadecimal). Last, please observe the parse error handling provided by strtol
(*bp != 0).
Cheers!