[SOLVED] Arduino line-following code not turning correctly on the figure 8 mat


#1

I am trying to recreate the factory line following mode for the mBot with Arduino. However, with my current code, it often stops and spin on the spot when it hits the opposite side of the black line. I believe the problem may have something to do with my code for handling when it goes completely off the line onto the white part of the mat. Is there a better approach to line following with this kit?

#include "MeOrion.h"

// Components
MeLineFollower lineFinder(PORT_2);
MeDCMotor motorL(M1);
MeDCMotor motorR(M2);

// Constants
const uint8_t MOTOR_SPEED = 125;
const float TURN_RATE = 0.9;

// Variables
uint8_t sensorState = S1_OUT_S2_IN;
uint8_t lastState = S1_OUT_S2_IN;

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

void loop()
{
  lastState = sensorState;
  sensorState = lineFinder.readSensors();
  switch (sensorState)
  {
    case S1_IN_S2_IN:
      motorL.run(-MOTOR_SPEED);
      motorR.run(MOTOR_SPEED);
      Serial.println("Moving straight on the black line.");
      break;
    case S1_IN_S2_OUT:
      motorL.run(MOTOR_SPEED);
      motorR.run(MOTOR_SPEED * TURN_RATE);
      Serial.println("Turning left.");
      break;
    case S1_OUT_S2_IN:
      motorL.run(MOTOR_SPEED * TURN_RATE);
      motorR.run(MOTOR_SPEED);
      Serial.println("Turning right.");
      break;
    case S1_OUT_S2_OUT:
      if (lastState == S1_OUT_S2_IN)
      {
        motorL.run(MOTOR_SPEED * TURN_RATE);
        motorR.run(MOTOR_SPEED);
      }
      else if (lastState == S1_IN_S2_OUT)
      {
        motorL.run(MOTOR_SPEED);
        motorR.run(MOTOR_SPEED * TURN_RATE);
      }
      Serial.println("Off the line; correcting position.");
      break;
    default:
      Serial.println("Unknown sensor state.");
      break;
  }

  delay(100);
}

#2

As it turns out, I was supposed to use #include <MeMCore.h>, not #include “MeOrion.h” for the mBot kit. That was messing up my line follower sensor input.


#3

If you still need help, be sure to let me know!
I’m on a trip and I don’t have much time, so it might be a week before I can assist you best.
Otherwise, I can mark this topic as solved.

Thanks!
@jmancoder


#4

Yes, you can mark it as solved. I was just confused for a bit because some of the sample programs used different libraries.


#5

Awesome! Be sure to let me know if you need anything else.