I am trying to send some binary data to my Arduino remotely, but I need the data to be retrieved from a web page. So the web page contains values like 0x61,0x00,0x0c,0x94,0x7e,...
I can receive the data from the page as a sequence of char variables or String objects but I am not sure how to convert them back to bytes.
It is like having the following:
char a = '0x61';
int bytevalue = ... //missing this step
Serial.print(bytevalue, BYTE);
I have tried casting but does not give the right output:
Serial.print((int)a, BYTE);
//I need Serial.print(0x61, BYTE);
I know char a = 0x61; works fine, but maybe I was not very clear: the sketch reads the byte values from a web page using the Ethernet library using the read() function like:
char c = client.read(); which I think will return something like char a = '0x61'; and not char a = 0x61;
No that statement is meaningless. The single quote defines a single ASCII character, I have no idea what that statement returns but it is not what you are expecting.
You need to find out what form the Ethernet library read() function returns.
No that statement is meaningless. The single quote defines a single ASCII character, I have no idea what that statement returns but it is not what you are expecting.
You need to find out what form the Ethernet library read() function returns.
Thanks! You are so right about the single quotes, really missed it! The read() returns int values, so reads it single character from the page and returns it into an int.
So now the question is how to convert '0', 'x', '6', '1' to 0x61 byte value!
int string_to_byte(char *data) {
if (data[0] != '0' || data[1] != 'x') return -1;
int a = hexdig(data[2]);
if (a < 0) return -1;
int b = hexdig(data[3]);
if (b < 0) return -1;
return (a << 4) + b;
}
Usage:
char *str = "0xfe";
int val = string_to_byte(str);
There are also functions in the standard library to do this, if you can afford to link that in. Look at strtol() and sscanf().
Thanks a lot! That worked pretty well! It also worked with:
str = "0x1d";
int n;
sscanf (str,"%x",&n);
Serial.prinln(n, BYTE);