Jack's code works for me.
Please copy the code that you are using and post it here.
I used the select function in his original thread and I haven't changed anything.
void setup() {
Serial.begin(9600);
}
void loop() {
char input[3];
int charsRead;
int val;
if (Serial.available() > 0) {
charsRead = Serial.readBytesUntil('\n', input, 2); // fetch the two characters
input[charsRead] = '\0'; // Make it a string
val = StrToHex(input); // Convert it
Serial.print("Hex input was: "); // Show it...
Serial.print(input);
Serial.print(" decimal = ");
Serial.println(val);
}
}
int StrToHex(char str[])
{
return (int) strtol(str, 0, 16);
}
Works for me.
Can I please clarify what you are entering ? Every keystroke or mouse click in the order you enter them.
I've got the serial monitor set to autoscroll, no line ending, 9600Baud - tried newline as well. I've tried entering a few different codes in both uppercase and lowercase.
Typing the each of the below and either hitting the enter key or pushing the send button.
AF
FF
ff
2b
This is running on a Teensy 3.1 using Arduino 1.6.1 and teensyduino as the loader.
ended up using sscanf for the conversion.
sscanf(dataFromPC, "%x", &integerFromPC); //converts HEX string to a DEC int
econjack:
If it is truly a 2 char array that holds the hex string, then try this:void setup() {
Serial.begin(9600);
}
void loop() {
char input[3];
int charsRead;
int val;
if (Serial.available() > 0) {
charsRead = Serial.readBytesUntil('\n', input, 2); // fetch the two characters
input[charsRead] = '\0'; // Make it a string
val = StrToHex(input); // Convert it
Serial.print("Hex input was: "); // Show it...
Serial.print(input);
Serial.print(" decimal = ");
Serial.println(val);
}
}
int StrToHex(char str[])
{
return (int) strtol(str, 0, 16);
}
I'm not a big fan of *sscanf()* because it eats more memory than is usually necessary.
Can you help me for substring function Ex eFA covert FA to Hex
Hi,
Sorry for waking up a dead thread, but UKHeliBob's nice and simple solution (which I just used) contains a typo which could go unnoticed and bite you later on.
Namely the digit conversions should read <='9', not <'9'.
Here's a fixed version:
char hexValue[] = {'F', '9'};
void setup()
{
Serial.begin(115200);
byte tens = (hexValue[0] <= '9') ? hexValue[0] - '0' : hexValue[0] - '7';
byte ones = (hexValue[1] <= '9') ? hexValue[1] - '0' : hexValue[1] - '7';
byte number = (16 * tens) + ones;
Serial.println(number);
Serial.println(number, HEX);
}
void loop()
{
}
KR,
Vicne