// Define the pins used for the motor control and speed
const int speedPin = 11;
const int dir1 = 9;
const int dir2 = 10;
// Define the pins used for the push buttons
const int speedButtonPin = 3;
const int directionButtonPin = 4;
// Define variables for the motor speed and direction
int motorSpeed = 0;
int motorDirection = 1; // 1 = forward, -1 = backward
// Define variables to store the state of the push buttons
int speedButtonState = 0;
int directionButtonState = 0;
int lastSpeedButtonState = 0;
int lastDirectionButtonState = 0;
void setup() {
// Initialize the serial communication and set pin modes
Serial.begin(9600);
pinMode(speedPin, OUTPUT);
pinMode(dir1, OUTPUT);
pinMode(dir2, OUTPUT);
pinMode(speedButtonPin, INPUT_PULLUP);
pinMode(directionButtonPin, INPUT_PULLUP);
}
void loop() {
// Read the state of the push buttons
speedButtonState = digitalRead(speedButtonPin);
directionButtonState = digitalRead(directionButtonPin);
// Check if the speed button has been pressed
if (speedButtonState != lastSpeedButtonState) {
if (speedButtonState == LOW) {
// Toggle the motor speed between 0 and 255
if (motorSpeed == 0) {
motorSpeed = 255;
} else {
motorSpeed = 0;
}
}
// Remember the current state of the speed button
lastSpeedButtonState = speedButtonState;
}
// Check if the direction button has been pressed
if (directionButtonState != lastDirectionButtonState) {
if (directionButtonState == LOW) {
// Toggle the motor direction between forward and backward
motorDirection = -motorDirection;
}
// Remember the current state of the direction button
lastDirectionButtonState = directionButtonState;
}
// Set the motor direction
if (motorDirection == 1) {
digitalWrite(dir1, LOW);
digitalWrite(dir2, HIGH);
} else {
digitalWrite(dir1, HIGH);
digitalWrite(dir2, LOW);
}
// Set the motor speed
analogWrite(speedPin, motorSpeed);
// Print the current motor speed and direction to the serial monitor
Serial.print("Motor speed: ");
Serial.print(motorSpeed);
Serial.print(", Motor direction: ");
if (motorDirection == 1) {
Serial.println("Forward");
} else {
Serial.println("Backward");
}
// Delay for a short period of time before repeating the loop
delay(100);
}