Go Down

Topic: trouble incrementing index (Read 404 times) previous topic - next topic

motomoto

I'm trying to read a pair of comma separated values, store the values into arrays, read the next pair of values, and append them to the arrays.

Right now I can store the first pair of values into the array. But when I try to increment the array index and use it for the next set, it does not increment and instead overwrites the first set.

My code right now looks like this:
Code: [Select]


void setup() {
  // initialize serial:
  Serial.begin(9600);

  Serial.println("Ready");

}

void loop() {
  int index = 0;
  int t[50];
  int n[50];
  // if there's any serial available, read it:
  while (Serial.available() > 0) {
 


    // look for the next valid integer in the incoming serial stream:
    int c1 = Serial.parseInt();
    // do it again:
    int c2 = Serial.parseInt();

    // look for newline
    if (Serial.read() == '\n') {
     
      Serial.println(c1, DEC);
      Serial.println(c2, DEC);

      t[index] = c1;
      n[index] = c2;
      ++index;
    }
   
    //print what's currently in the arrays
    Serial.println("Sequence");
    int i;
    for (i = 0; i < 10; i = i + 1) {
    Serial.println(t[i]);
    Serial.println(n[i]);
     
    }
  }
}



Nick Gammon

Code: [Select]
void loop() {
  int index = 0;


You are resetting it to zero each time through loop. Try moving it outside loop, eg.


Code: [Select]
int index = 0;

void loop() {

Please post technical questions on the forum, not by personal message. Thanks!

More info:
http://www.gammon.com.au/electronics

motomoto


You are resetting it to zero each time through loop. Try moving it outside loop, eg.


Code: [Select]
int index = 0;

void loop() {




Thanks!

guix

#3
Nov 27, 2012, 04:10 am Last Edit: Nov 27, 2012, 04:17 am by guix Reason: 1
loop() is already a loop, you don't need another loop "while (Serial.available() > 0)", just use something like this:
Code: [Select]

if ( Serial.available () > 0 )
{
 static char input[16];
 static uint8_t i;
 char c = Serial.read();

 if ( c != '\r' && i < 15 ) // assuming "Carriage Return" is chosen in the Serial monitor as the line ending character
   input[i++] = c;
   
 else
 {
   input[i] = '\0';
   i = 0;
   
   //do whatever with input string...
   Serial.println( input );
 }
}

Go Up