Pages: [1]   Go Down
Author Topic: trouble incrementing index  (Read 327 times)
0 Members and 1 Guest are viewing this topic.
Offline Offline
Newbie
*
Karma: 0
Posts: 15
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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:

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]);
     
    }
  }
}

Logged

Global Moderator
Online Online
Brattain Member
*****
Karma: 480
Posts: 18720
Lua rocks!
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset

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

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


Code:
int index = 0;

void loop() {
Logged


Offline Offline
Newbie
*
Karma: 0
Posts: 15
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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


Code:
int index = 0;

void loop() {


Thanks!
Logged

France
Online Online
Edison Member
*
Karma: 37
Posts: 1004
Scientia potentia est.
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

loop() is already a loop, you don't need another loop "while (Serial.available() > 0)", just use something like this:
Code:
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 );
  }
}
« Last Edit: November 26, 2012, 10:17:57 pm by guix » Logged

Pages: [1]   Go Up
Jump to: