[SOLVED] Arduino reads serial input only once.

So recently i got my hands on an arduino mega, because i need to send data from a Raspberry pi 0 w to an arduino via Serial and want to debug it. (B.c. the mega has multiple serial ports).
So the raspberry is sending an array of bytes (size: 29) every second. I know that everything on the sending side (Raspberry) works perfectly fine.

But when i run this code here on the arduino:

int dataArray[29];

void setup() {
  Serial.begin(9600);
  Serial1.begin(9600);

}

void loop() {
  int x = 0;
  while(Serial1.available() > 0) {
      dataArray[x] = Serial1.read();
      ++x;
  }

  for(int i; i <= 28; ++i) {
    Serial.println(dataArray[i]);
  }
}

... i only get:

0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0

from the serial monitor ONCE after i press the reset button or reupload.

Does anybody know why it gets stuck? (B.c. even if it doesnt read anything on the serial port it should print "0" over and over)

Sure. x starts at 0.

You get a byte, it is stored at 0. The while() exits.
The empty array is printed.

Loop starts again, x is set to 0 again.
No data came in - (9600 is pretty slow). The while() waits for a byte; nothing prints.

You might want to wait for serial.available to be >28 before doing the read, and then printing in the while after 29 are read.

You need to initialize the variable controlling the for loop.

//for(int i; i <= 28; ++i) {
for(int i=0; i <= 28; ++i) {

This Simple Python - Arduino demo may help.

...R

Alright i modified my code to look like this:

int dataArray[29];

void setup() {
  Serial.begin(9600);
  Serial1.begin(9600);

}

void loop() {
  if(Serial1.available() >= 29) {
    for(int i = 0; i <= 28; ++i) {
      dataArray[i] = Serial1.read();
    }
  }

  for(int i = 0; i <= 28; ++i) {
    Serial.println(dataArray[i]);
  }
}

And it worked thanks guys. (especially to CrossingRoads)

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