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