// Define the pins used for the motor control and speed
const int speedPin = 11;
const int dir1 = 9;
const int dir2 = 10;
int motorSpeed = 0; // Set the initial motor speed to 0
void setup() {
// Initialize the serial communication and set pin modes
Serial.begin(9600);
pinMode(speedPin, OUTPUT);
pinMode(dir1, OUTPUT);
pinMode(dir2, OUTPUT);
}
void loop() {
//4.5.2
// Read the value from the potentiometer and map it to a motor speed between 0 and 255
int potValue = analogRead(A0);
motorSpeed = map(potValue, 0, 1023, 0, 255);
// Set the motor direction
digitalWrite(dir1, LOW);
digitalWrite(dir2, HIGH);
// Apply a "kick" to the motor to start it
analogWrite(speedPin, 255);
delay(25);
/* 4.5.3
// Determine the motor direction based on the potentiometer value
if (potValue < 512) {
// Set the motor direction to forward
digitalWrite(dir1, LOW);
digitalWrite(dir2, HIGH);
Serial.println(" DC motor rotates in FORWARD direction");
} else {
// Set the motor direction to reverse
digitalWrite(dir1, HIGH);
digitalWrite(dir2, LOW);
Serial.println(" DC motor rotates in REVERSE direction");
}
*/
// Set the motor speed and run it for a period of time
analogWrite(speedPin, motorSpeed);
delay(50);
// Print the current motor speed to the serial monitor
Serial.print("Current speed: ");
Serial.println(motorSpeed);
}