-3

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.

Jonas
  • 6,915
  • 8
  • 35
  • 53
techset
  • 7
  • 8

1 Answers1

0

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;
Community
  • 1
  • 1
Tomáš Zato
  • 50,171
  • 52
  • 268
  • 778
  • Char literals can be composed of multiple characters. – Kerrek SB Jan 20 '17 at 01:18
  • Interesting to know. But apparently there is no standard definition on what do they do or mean. – Tomáš Zato Jan 20 '17 at 01:22
  • 2
    @KerrekSB but I believe that usage is non-portable, you need to see how your compiler handles it. And you certainly wouldn't want to compare it to the result of a single `read`. – Mark Ransom Jan 20 '17 at 01:22
  • @TomášZato: Well, the Standard defines their meaning to be implementation-defined... – Kerrek SB Jan 20 '17 at 01:53
  • @KerrekSB And what is the practical difference between "implementation defined" and "not defined"? Implementation defines all aspects that are not defined. – Tomáš Zato Jan 20 '17 at 01:55
  • 1
    @TomášZato: The difference is that if something is implementation-defined, the implementation is required to document it. – Keith Thompson Jan 20 '17 at 02:06