i have a string that i pass to a variable of char[5] via the serial port
i now need to copy this string/char[] to a char variable
is there a way to convert a string hex ie "0x11" to a char ?
i have a string that i pass to a variable of char[5] via the serial port
i now need to copy this string/char[] to a char variable
is there a way to convert a string hex ie "0x11" to a char ?
You can use strtoul
thanks for the tip
is this the correct syntax ?
Char User1;
char cvar[5];
if (Serial.available() > 0) {
// read the incoming byte:
incomingStr = Serial.readString();
if (incomingStr.startsWith("U1D")) {
Serial.print("User1 Data");
incomingStr = (incomingStr.substring(3));
incomingStr.toCharArray(cvar, 5);
Serial.print(cvar);
Serial.println("#");
User1 = strtoul(cvar , NULL , 5);
{
is this the correct syntax ?
Char User1;
No.
'char' is spelled 'char'.
Please remember to use code tags when posting code
It looks like strtoul will not handle the "0x" prefix, so you need to pass a pointer to the string after the 'x'. The third parameter is the base, not the size. Here's my test.
void setup()
{
const char c_number[] = "0x11";
Serial.begin(9600);
Serial.print("Char: "); Serial.println(c_number); // 0x11
unsigned long ul_number;
ul_number = strtoul(c_number, NULL, 2);
Serial.print("Ulong: "); Serial.println(ul_number); // 0
ul_number = strtoul(strchr(c_number, 'x') + 1, NULL, 2);
Serial.print("Ulong: "); Serial.println(ul_number); // 3
}
void loop()
{
}
If you tell strtoul that the text is a base-2 representation, 0x is obviously invalid.
void setup()
{
Serial.begin(57600);
while(!Serial);
char text[] = "0x11";
byte number = strtoul(text, NULL, 16);
Serial.println(number);
}
void loop()
{
}
thanks guys - that worked a treat
User2 = strtoul(cvar, NULL, 16);