Serial communication stuck after first attempt

I am using arduino Mega 2560 to control some vibration motors with touchdesigner through Serial Communication. I maped the pixels to control each motors, It works for a few seconds and gets stuck very soon. Is there anything wrong with my code?

Here is my arduino sketch:

#define MOTOR_COUNT 12
int motors[MOTOR_COUNT];

 

void setup()
{
  // Start up the serial port, for communication with the PC.
  Serial.begin(115200);
  Serial.println("Ready to receive frames.");
  // Serial.setTimeout(10);

 

  for (int i = 0; i < 11; i++) {
    pinMode(i, OUTPUT);
  }

 

//  for (int i = 44; i < 46; i++) {
//    pinMode(i, OUTPUT);
//  }
}

 

void loop()
{
  // If any digit is received, we will go into integer parsing mode
  // until all three calls to parseInt return an interger or time out.
  if (Serial.available())
  {
    char c = Serial.peek();
    if (!(c >= '0' && c <= '9'))
    {
      Serial.read(); // Discard non-digit character
    }
    else if (Serial.read() == '\n')
    {
      for (uint16_t i = 0; i < MOTOR_COUNT; i++)
      {
        //Serial.println( "inside");
        motors[i] = Serial.parseInt();
        Serial.print("motor ");
        Serial.print(i);
        Serial.print(":");
        Serial.println(motors[i]);

 

        if (i < 11) {
          analogWrite(i + 2, motors[i]);
        }
        else if (i > 11) {
          analogWrite(i + 44, motors[i]);
        }
        Serial.flush();
      }
    }
  }
}

your parsing of the Serial input is not robust. I would suggest to study Serial Input Basics to handle this

why do you define this

and then you have 11 in the code ?
also < is not the same as <=

this is not good for pin Tx

for (int i = 0; i < 11; i++) {
    pinMode(i, OUTPUT);
  }

(Serial.flush();will just empty the output buffer. not sure why you want to do that)

Thank you! ahh yeah, thanks I missed this = in the code. Serial.flush is just me trying to see if it helps. the serial lights flush for a while and just stoped working.

why not separate reading a complete string (up to \n), extracting the sub-string you're interested in and processing that sub-string?

Check out my Arduino Software Solutions which various ways to read from Serial with their pros and cons and also covers parsing numbers and how to completely flush the Serial input

The string is seperated with \n, and suppose to put the value before line break into the array motors[12]

do you mean the string is "terminated" (ends with) a \n?