Robot Quickstart!
Contributors:
Miskatonic
Complete Code
Here's the complete test code. We've created two custom functions to control the two motors: setMotorA() and setMotorB(). These functions take a single parameter from -255 to +255 that defines the speed of the motor. Positive values drive the motor clockwise, and negative values drive the motor counter-clockwise.
language:cpp
const byte AIN1 = 13;
const byte AIN2 = 12;
const byte PWMA = 11;
const byte BIN1 = 8;
const byte BIN2 = 9;
const byte PWMB = 10;
void setup()
{
pinMode(AIN1, OUTPUT);
pinMode(AIN2, OUTPUT);
pinMode(PWMA, OUTPUT);
pinMode(BIN1, OUTPUT);
pinMode(BIN2, OUTPUT);
pinMode(PWMB, OUTPUT);
}
void loop()
{
//set direction to clockwise
setMotorA(50);
setMotorB(-50);
delay(1000);
//set direction to counterclockwise
setMotorA(-255);
setMotorB(255);
delay(1000); //brake
setMotorA(0);
setMotorB(0);
delay(1000);
}
void setMotorA(int motorSpeed)
{
if (motorSpeed > 0)
{
digitalWrite(AIN1, HIGH);
digitalWrite(AIN2, LOW);
}
else if (motorSpeed < 0)
{
digitalWrite(AIN1, LOW);
digitalWrite(AIN2, HIGH);
}
else
{
digitalWrite(AIN1, HIGH);
digitalWrite(AIN2, HIGH);
}
analogWrite(PWMA, abs(motorSpeed));
}
void setMotorB(int motorSpeed)
{
if (motorSpeed > 0)
{
digitalWrite(BIN1, HIGH);
digitalWrite(BIN2, LOW);
}
else if (motorSpeed < 0)
{
digitalWrite(BIN1, LOW);
digitalWrite(BIN2, HIGH);
}
else
{
digitalWrite(BIN1, HIGH);
digitalWrite(BIN2, HIGH);
}
analogWrite(PWMB, abs(motorSpeed));
}