Changing Directions Motor Controller

Hey Guys, I currently have an Arduino duemilanove connected to a Polulu dual-serial low voltage motor controller.

I’m trying to make a robot that goes forward and turns left if it gets too close to a wall, below is the code involved.

void loop() 
{       
      val_dist = analogRead(dist_sensor); // read the value from the sensor
      val_dist = convDistance(val_dist);
      Serial.print("Distance from wall is :");
      Serial.print(val_dist);
      Serial.println(" cm");
      
      
      if (val_dist > 10)
      {
        moveForward();
      }
      else
      {
        turnLeft();
      }
      
      
   
}

void moveForward()
{
  
  Serial.println("MOVING FORWARD");
   // Create the packet buffer
   unsigned char buffer[4];     
   
   buffer[0] = 0x80;
   buffer[1] = 0x00;
   buffer[2] = 0x04;
   buffer[3] = 0x7F;
   SendPacket(buffer, 4); 
        
   buffer[0] = 0x80;
   buffer[1] = 0x00;
   buffer[2] = 0x06;
   buffer[3] = 0x7F;
   SendPacket(buffer, 4); 
   
        
   delay(1000);
}

void turnLeft()
{
  
    Serial.println("TURNING LEFT");
    unsigned char buffer[4];
    buffer[0] = 0x80;
    buffer[1] = 0x00;
    buffer[2] = 0x04;
    buffer[3] = 0x7F;
    SendPacket(buffer, 4); 
    
    buffer[0] = 0x80;
    buffer[1] = 0x00;
    buffer[2] = 0x07;
    buffer[3] = 0x7F;
    SendPacket(buffer, 4); 
        
    delay(1000);
}

The code works initially and the robot keeps going straight. However, once it nears the wall and the distance is less than 10cm, it just brakes and stop there. But in the serial monitor is is printing “TURNING LEFT” which means it is in the turnLeft() function and the data is being sent. I don’t understand why is it stopping. Can anybody enlighten me?? Thanks!

void SendPacket(unsigned char *buffer, int bufferCount)
{
	for(int i = 0; i < bufferCount; i++)
		motorSerial.write((byte)buffer[i]);
}

Sorry, forgot to add in this

Hello.

What are you using for your motors and how are you powering everything? You are commanding a motor spinning full-speed forward to abruptly go full-speed reverse, which can briefly cause the motor to draw nearly twice its stall current and generate a significant amount of electrical noise. I suspect this is the cause of your problems. One way to check this would be to set motor 3 to speed zero rather than -127 and see if the behavior is different:

void turnLeft()
{
  
    Serial.println("TURNING LEFT");
    unsigned char buffer[4];
    buffer[0] = 0x80;
    buffer[1] = 0x00;
    buffer[2] = 0x04;
    buffer[3] = 0x7F;
    SendPacket(buffer, 4); 
    
    buffer[0] = 0x80;
    buffer[1] = 0x00;
    buffer[2] = 0x06;
    buffer[3] = 0x00;  // stop the left motor
    SendPacket(buffer, 4); 
        
    delay(1000);
}

Does this change affect the robot’s behavior?

- Ben