Really strange local variable problem

Hi,

I am using an Arduino Yun with an external RS232 card and SoftwareSerial library.

My problem is if I declare a local variable k as a counter in loop(), it never increments!!! However if I declare it as a global variable it works fine.

Here is the code:

#include <SoftwareSerial.h>

SoftwareSerial mySerial(10, 5); // RX, TX


int k = 0;

void setup()
{
  Serial.begin(9600);
  while(!Serial);
  Serial.println("OK");
  
  // start the external RS232 driver
  mySerial.begin(9600);
  
}

void loop()
{
  char command[100];
//  int k = 0;
    
  if (mySerial.available()) {
    char c;
        
    Serial.println("char available");
    
    c = mySerial.read();
    if ((c != '\n') && (c != '\r')) {
       command[k++] = c;
       Serial.println(k);
    } else if (c == '\r') {
       // ignore
    } else if (c == '\n') {
       command[k] = '\0';
       Serial.print("\n\rGot command: ");
       Serial.println(command);
       k = 0;
    }
  }
  delay(50);
 
}

Here is the output with k as a local variable when I enter “abc” on the serial line:

OK
char available
1
char available
1
char available
1
char available
char available

Got command:

and with k as a global variable (as in the code above):

OK
char available
1
char available
2
char available
3
char available
char available

Got command: abc

I’m really not sure why this is? Any ideas?

Thanks.

If you declare and set k to zero every time through loop() why would you be surprised that once incremented it would not go back to zero when declared and set to zero again next time round ?

Solutions

1 Use a global variable and do not declare it in loop()
2 Declare it as static in loop() so that it retains its value if it is changed within loop()

While you are making changes either way declare it as a byte rather than an int to save memory.

    if ((c != '\n') && (c != '\r')) {
       command[k++] = c;
       Serial.println(k);
    } else if (c == '\r') {
       // ignore
    } else if (c == '\n') {
       command[k] = '\0';
       Serial.print("\n\rGot command: ");
       Serial.println(command);
       k = 0;
    }

You are testing for \n and \r twice.

How about:

   if (c == '\r') {
       // ignore
    } else if (c == '\n') {
       command[k] = '\0';
       Serial.print("\n\rGot command: ");
       Serial.println(command);
       k = 0;
    }
  else  
    {
    command[k++] = c;
    Serial.println(k);
    }

I understand now, thank you for your help. I had mis-interpreted how the loop() function works, I thought it was only called once from setup() then looped internally...I am new to Arduino so still learning.

I will use your suggestion.

Thanks again.