Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

have problem with filling array from Serial. So basically, first asking for lenght of array, then should input from keyborad all elements. Problem is that it's not waiting to enter values into Serial and just fill with 0. If will type values right away, it will put them into array.

My question is how to force wait from Arduino till i will input values. Thank You!

boolean fill = false;
int sum = 0;
int lengthOfArray;

void setup() 
{
  Serial.begin(9600);
  Serial.print("Set lenght of array : ");
}

void loop() 
{
  if(fill == false)
  {
    if(Serial.available() > 0)
    {
      lengthOfArray = Serial.parseInt();
      Serial.println(lengthOfArray);
      int tab[lengthOfArray];

      for(int i = 0; i < lengthOfArray; i++)
      {
        delay(10);
        Serial.print("Tab[" + String(i) + "] : ");    
        tab[i] = Serial.parseInt();
        Serial.println(tab[i]);
        sum += tab[i];         
      }
      fill = true; 

      Serial.println("Sum = " + String(sum));
    }
  }
}


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
218 views
Welcome To Ask or Share your Answers For Others

1 Answer

If I understood your problem correctly, you're willing to print all the values at once, not for every value that you type.

You may maintain separate for-loops for reading and then printing

      for(int i = 0; i < lengthOfArray; i++)
      {
        delay(10);
        Serial.print("Tab[" + String(i) + "] : ");    
        tab[i] = Serial.parseInt();
        sum += tab[i];         
      }
      fill = true;
      for(int i = 0; i < lengthOfArray; i++) 
        Serial.println(tab[i]);

      Serial.println("Sum = " + String(sum));


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...