Using "if" statement on character within a string

I'm just getting back into programming so have forgotten a load of stuff (10yrs+) I'm trying to receive a series of characters through serial, which seems to work OK. The issue I'm having is processing the characters.

In the code below, it is a 5 character code + null, I'm trying to use an if statement on the 2nd character of the code i.e. message[1] I'm assuming as it's a character I can do an

'if (message[1]=="a") {.....} else {....}'

but it's not working. It always goes to the else statement, I've tried variations using numerals, single =, /= with and without " " etc...

I'm sure I'm missing something very simple, just can't seem to see it. :confused:

void serialEvent() {

 //Check to see if anything is available in the serial receive buffer
 while (Serial.available() > 0)
 {
   //Create a place to hold the incoming message
   static char message[MAX_MESSAGE_LENGTH];
   static unsigned int message_pos = 0;

   //Read the next available byte in the serial receive buffer
   char inByte = Serial.read();
   int quantBytes;
   int directionTravel;

   //Message coming in (check not terminating character) and guard for over message size
   if ( inByte != '\n' && (message_pos < MAX_MESSAGE_LENGTH - 1) )
   {
     //Add the incoming byte to our message
     message[message_pos] = inByte;
     message_pos++;
   }
   //Full message received...
   else
   {
     //Add null character to string
     /* Serial Protocol to use is 5 characters plus null character - in this case using numerals throughout
     bit no.
     0 =>  case 0-4 using "Switch"
     1 =>  a= -ve value           anything else = negative value
     2:4 => 3 digit value for movement if nessecary

     EXAMPLE: Code received 0a152 means Case 0; Move Negative 152 steps


     */
     
     message[message_pos] = '\0';

      Serial.print("Message [1] = ");
      Serial.println(message[1]);

      if (message[1] == "a") {
        directionTravel = -1;
        Serial.println("direction Negative");
      }
        else {
        directionTravel = 1;
        Serial.println("Direction Positive");
        }

single quotes for single char double quotes for strings..

good luck.. ~q

Welcome to the forum

if (message[1]=="a") {.....} else {....}

Assuming that message is an array of chars that test is wrong. It should be

if (message[1]=='a') {.....} else {....}

Single quotation marks denote a single char where as normal quotation marks denote a string, even if it is only a single character

In addition, you cannot use == to compare strings, you must use strcmp()

so to be clear

if (message[1] == 'a') {
  •••

You might also need to remember that index starts at 0, so message[1] is the second character (just in case....)

Marvelous, I knew it would be something silly I'm overlooking!

Thanks, yes I know, I curtailed the code for posting

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.