Problem with my code

hi i wrote a code to drive 2 motors but the weird thing when i run this on the arduino the arduino keeps going to setup each time it goes to read the serial recived but when i ran it on the aruino leonardo it kept writing a very weird error the io exception thing or idk

here is the code 

 

int motors[2][3]={3,5 ,                  //PWM PINs

                  4,6,                   // wire1

                  7,8} ;                //wire2

 

int Recived=0;

 

 void setup(){

  Serial.begin(9600);

 Serial.println("Connected!"); 

 

 

 }

 void motor_assignment(int motorno,int motorstate){

  switch(motorstate){

  case 0: // stop the motor

    analogWrite( motors[0][motorno],0);

    digitalWrite(motors[2][motorno],LOW);

    digitalWrite(motors[1][motorno],HIGH);

    //    Serial.print("motor ");Serial.print(motorno);

    //     Serial.println(" is now stopped");

    break;

 

  case 1: // go forward

    analogWrite( motors[0][motorno],255);

    digitalWrite(motors[2][motorno],LOW);

    digitalWrite(motors[1][motorno],HIGH);

    //    Serial.print("motor ");Serial.print(motorno);

    //    Serial.println(" is now forward");

    break;

 

  case 2: // go backward

    analogWrite( motors[0][motorno],255);    

    digitalWrite(motors[1][motorno],LOW);

    digitalWrite(motors[2][motorno],HIGH);

    //    Serial.print("motor ");Serial.print(motorno);

    //    Serial.println(" is now backward");

    break;

  } 

 }

 void ams(int m1,int m2){ // assing motor state

  ams(0,m1);

 ams(1,m2); 

 }

 void behave(){ // does something about the recived character 

  switch (Recived){

   case '0':

   ams(0,0); // stop

   break;

   case '1':

   ams (1,1);// forward

   break;

   case '2' :

   ams (2,2); // backward

   break;

   case 3:

   ams(1,2); // left

   break;

   case 4:

   ams (2,1); // right

   break;

  } 

 }

 

 void loop(){

  if (Serial.available()){

 

   Recived=Serial.read();

 

   behave();

  } 

 }

My guess is that you have a
My guess is that you have a power problem. If you’re entering setup() more than once then the power to the Arduino is going to low and it’s rebooting.

Question: are you using the +5 out of the Arduino to power your motors?

Are you using rechargable batteries? You almost always should be.

What type of batteries are you using?

Can you attach a detailed image of your robot so we can see the wiring?

One quick thing about your code: the case statement did not have a “default” clause. I would put one into see what the incorrect character is. Also “case 3:” should be “case ‘3’:”, likewise for case 4.

I hope this helps.