Code: Select all
#include <AFMotor.h>
AF_DCMotor motor(2);
const int PotPin = A0; // Change this if pot is connected to another pin
int direction = FORWARD; // Where we are going
int speed = 0; // How fast
int potVal = 506; // Current potvalue
void setup() {
// initialize serial communication at 9600 bits per second:
Serial.begin(9600);
motor.setSpeed(255);
motor.run(RELEASE);
}
void loop() {
// read the input on the pot:
potVal = analogRead(PotPin);
if (potVal < 506)
{ // Smaller than 506 so we're going forward
direction = FORWARD;
// Map value from pot-range to motorspeed-range
speed = map(potVal, 0, 506, 255, 0);
}
else
{ // Otherwise, we're going backward
direction = BACKWARD;
// Map value from pot-range to motorspeed-range
speed = map(potVal, 507, 1024, 0, 255);
}
// print out the variables:
Serial.print("Read: ");
Serial.print(potVal);
Serial.print(" direction: ");
if (direction==FORWARD)
Serial.print("Forward");
else
Serial.print("Backward");
Serial.print(" Speed: ");
Serial.println(speed); // End of line, so also make it go a line
delay(1); // delay in between reads for stability
}