0

I have a string which I send to the arduino using serial monitor. Something like that:

my specific string 0x0F 0x2C 0x98 0xBC

How can I parse this string in the arduino to get an array of hex values:

0x0F 0x2C 0x98 0xBD

? There are two prerequisites:

  1. All hexadecimal starts with #
  2. The size of hexadecimal is 2. No 0x111 or '0xbbb'
  • Do hexadecimals start with a #, as you wrote in the text, or with a 0x, like in the example? – frarugi87 Oct 13 '15 at 9:21
  • It would be easier to send decimal numbers over the serial and read them as so. After that you can read them from the array as HEX values? If you have the possibility to change whatever is sending through your serial. – Paul Oct 13 '15 at 13:55
1

How can I parse this string in the arduino to get an array of hex values:

There are a few standard library (stdlib) functions that can help you with that. Below is a snippet:

char buf[] = "0x0F 0x2C 0x98 0xBD";
uint8_t val[4];

void setup()
{
  Serial.begin(9600);

  char* bp = buf;
  int i = 0;
  do {
    char* ep;
    val[i] = strtol(bp, &ep, 16);
    Serial.println(val[i], HEX);
    bp = ep;
    i += 1;
  } while (*bp != 0);
}

void loop()
{
}

Cheers!

| improve this answer | |
0

You can try reading each character and convert it to hexadecimal representation. I suppose you wanna 1 byte each value in hexadecimal representation, so, let's start.

For example the string "0x25", ignore the 0x and read the '2' and save it into a char variable. Same for '5';

char highBits = '2' - '0'; // convert to decimal representation
char lowBits  = '5' - '0'; 

byte = (highBits << 4 | lowBits);

Now, save it inside you array. Make sure you check if the value is one of the possible letters in hexadecimal and convert it properly (A=10 and so on). Just include an if statement if it is a letter and convert it.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.