I am finding myself again confused by C strings, chars, etc.
Here is some code I am using to test the syntax on the Arduino. I know that (*message)buff will give me a pointer (I still don’t really know why I need to use pointers, but I can do some research on that!), I convert the *message_buff to a String (just for something to do, but note that later on when I try and print this string to serial I only get a single 'c' character).
I set an array pointer three elements long (three bytes long?? I don't really know):
char *mqtt_command[3] = {};
And later on when I try and add a value to the array using:
*mqtt_command[i] = str;
I get the error:
error: invalid conversion from 'char*' to 'char'
If I change that to:
mqtt_command[i] = str;
(without the *) it compiles fine. I don't know why...
Here is my code:
char *message_buff = "command:range:1";
char *str;
String msgString = String(*message_buff);
char *mqtt_command[3] = {};
int i = 0;
void setup()
{
Serial.begin(9600);
delay(500);
while ((str = strtok_r(message_buff, ":", &message_buff)) != NULL)
{
Serial.println(str);
mqtt_command[i] = str;
i++;
}
delay(1000);
Serial.print("Command: ");
Serial.println(mqtt_command[1]);
Serial.print("MQTT string: ");
Serial.println(msgString);
}
void loop()
{
// Do something here later
}
And here is the output:
command
range
1
Command: range
MQTT string: c
How can I understand chars, strings, pointers, and char arrays? Where can I go for a good all round tutorial on the topic?
I am passing in a command string (I think it is a string, maybe it is a char array????) via MQTT, and the message is:
command:range:1
I am trying to build a little protocol to do things on the Arduino when an MQTT message is received. I can handle the MQTT callbacks fine, that not the problem. The issue is that I don't really understand C strings and chars. I would like to be able to handle commands like:
command:range:0
command:digital:8
read:sensor:2
etc.