I have the V1 motor shield and I've been using it to run 4 DC motor wheels. I have no issue getting the motors to run by themselves (as in, run nonstop without the ability to control them), but I've run into issues when trying to make it so that I can use two pushbuttons (one for forwards and one for backwards) to make the motors run in the respective direction while the button is being held then stop when the button is released. All the code I've found online has been for wireless projects and I don't know whether I'm altering it correctly for my project.
Here is the main code I've been using to try to achieve this:
Code: Select all
#include <AFMotor.h>
//initial motors pin
AF_DCMotor motor1(1, MOTOR12_64KHZ);
AF_DCMotor motor2(2, MOTOR12_64KHZ);
AF_DCMotor motor3(3, MOTOR34_64KHZ);
AF_DCMotor motor4(4, MOTOR34_64KHZ);
// constants won't change. They're used here to set pin numbers:
const int forwardButtonPin = A2; // the number of the pushbutton pin
const int backButtonPin = A3;
// variables will change:
int forwardButtonState = LOW; // variable for reading the pushbutton status
int forwardCheck = 1;
int backButtonState = LOW;
int backCheck = 1;
void setup() {
// initialize the driving pins as an output:
// initialize the pushbutton pin as an input:
pinMode(forwardButtonPin, INPUT);
pinMode(backButtonPin, INPUT);
motor1.setSpeed(200);
motor2.setSpeed(200);
motor3.setSpeed(200);
motor4.setSpeed(200);
}
void loop() {
// read the state of the pushbutton value:
forwardButtonState = digitalRead(forwardButtonPin);
forwardCheck = digitalRead(forwardButtonPin);
backButtonState = digitalRead(backButtonPin);
backCheck = digitalRead(backButtonPin);
if (forwardButtonState == HIGH) {
if (forwardCheck == 1) {
forward();
}
forwardCheck = 0;
} else if (backButtonState == HIGH) {
if (backCheck == 1) {
back();
}
backCheck = 0;
} else {
forwardCheck = 1;
backCheck = 1;
Stop();
}
}
void forward() {
motor1.run(FORWARD); //rotate the motor clockwise
motor2.run(FORWARD); //rotate the motor clockwise
motor3.run(FORWARD); //rotate the motor clockwise
motor4.run(FORWARD); //rotate the motor clockwise
}
void back() {
motor1.run(BACKWARD); //rotate the motor anti-clockwise
motor2.run(BACKWARD); //rotate the motor anti-clockwise
motor3.run(BACKWARD); //rotate the motor anti-clockwise
motor4.run(BACKWARD); //rotate the motor anti-clockwise
}
void Stop() {
motor1.run(RELEASE); //stop the motor when release the button
motor2.run(RELEASE); //rotate the motor clockwise
motor3.run(RELEASE); //stop the motor when release the button
motor4.run(RELEASE); //stop the motor when release the button
}