TB6612FNG Motor Driver Demo Code

The following code is to demonstrate using the TB661FNG Motor Driver. Please refer to the documentation at https://learn.sparkfun.com/tutorials/tb6612fng-hookup-guide?_ga=2.39501219.1275598452.1574719960-253230089.1568042226 for full details.

NOTE: We did not use the code from the SparkFun site and instead implemented our own version to control the Motor Driver based on the documentation from the Hookup Guide.

const int offsetA = 1;
const int offsetB = 1;
// Pins for all inputs, keep in mind the PWM defines must be on PWM pins
#define AIN1 2
#define BIN1 7
#define AIN2 4
#define BIN2 8
#define PWMA 5
#define PWMB 6
#define STBY 9


void setup()
{
 
    Serial.begin(9600);
    pinMode(AIN1,OUTPUT);
    pinMode(AIN2,OUTPUT);
    pinMode(BIN1,OUTPUT);
    pinMode(BIN2,OUTPUT);
    pinMode(STBY,OUTPUT);

}

void forward(int HowFast){

    analogWrite(PWMA,HowFast);
    analogWrite(PWMB,HowFast);
    digitalWrite(AIN1,LOW);
    digitalWrite(AIN2,HIGH);

    digitalWrite(BIN1,LOW);
    digitalWrite(BIN2,HIGH);
    
    
    digitalWrite(STBY,HIGH);


  
}

void backward(int HowFast){
    analogWrite(PWMA,HowFast);
    analogWrite(PWMB,HowFast);
    digitalWrite(AIN1,HIGH);
    digitalWrite(AIN2,LOW);

    digitalWrite(BIN1,HIGH);
    digitalWrite(BIN2,LOW);

    
    digitalWrite(STBY,HIGH);
}


void rightTurn(int HowFast){
    analogWrite(PWMA,HowFast);
    analogWrite(PWMB,HowFast);
  
    digitalWrite(AIN1,LOW);
    digitalWrite(AIN2,HIGH);

    digitalWrite(BIN1,HIGH);
    digitalWrite(BIN2,LOW);

    
    digitalWrite(STBY,HIGH);
}


void leftTurn(int HowFast){
  
    analogWrite(PWMA,HowFast);
    analogWrite(PWMB,HowFast);
   
    digitalWrite(AIN1,HIGH);
    digitalWrite(AIN2,LOW);

    digitalWrite(BIN1,LOW);
    digitalWrite(BIN2,HIGH);

    
    digitalWrite(STBY,HIGH);
}




void loop()
{

    // drive 2 dc motors at speed=255, clockwise
    Serial.println("run at speed=255");
    forward(255);
    delay(2000);
    leftTurn(255);
    delay(500);
    backward(255);
    delay(2000);
    rightTurn(255);
    delay(500);
    digitalWrite(STBY,LOW);
    delay(2000);


}