I'm coding my BB-8 project and I'm using bluetooth with my Arduino so I'm using:
if (Serial.available() > 0) {
state = Serial.read();
Most people send numbers through like this which works:
if (state == '1') {
But I would like to send a string through instead, of a number to make it easier like this:
if (state == 'stop') { // or go etc.
But this doesn't seem like it would work so I tried using a string:
if (state == "stop") {
But I get this error
ISO C++ forbids comparison between pointer and integer [-fpermissive]
Which one would work and if neither what should I do instead?
Thank you.
First off, apostrophes are for char literals not strings , that is 'x'
is of type char
whereas "x"
is of type char*
. It is not clearly defined what 'xyz'
means, as discussed in this question: https://stackoverflow.com/a/3961219/607407
The value Serial.read
returns is of type int
. So in this case:
if (state == "stop")
You are comparing int
with const char*
. Instead, you probably want to read a string and compare that. Here is an example of reading string on arduino from serial:
const int max_len = 20;
char input_string[max_len+1]; // Allocate some space for the string
size_t index = 0;
while(Serial.available() > 0) // Don't read unless
{
if(max_len < 19) // One less than the size of the array
{
int input_num = Serial.read(); // Read a character
input_string[index] = (char)input_num; // Store it
index++; // Increment where to write next
input_string[index] = '\0'; // Null terminate the string
}
else {
// all data read, time to data processing
break;
}
}
// Don't forget that you have to compare
// strings using strcmp
if(strcmp(inData, "stop") == 0) {
// do something
}
// reset the buffer so that
// you can read another string
index = 0;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.