firmwareMIT

Arduino Uno: robot motor

breadboardhub/arduino-robot-motor
arduinounopotmotor
ShareXLinkedInFacebookRedditWhatsApp
B
Mike M
v1.0.0 · UpdatedNov 24, 2026 ·0 downloads ·0 forks
// Robot motor: the knob on A0 sets the motor's speed and direction.
// Middle: stop. Turn right: forward. Turn left: backward.
// The driver (L298N style): EN sets the speed with PWM, IN1 and IN2 the direction.

const int EN = 9;
const int IN1 = 8;
const int IN2 = 7;

void setup() {
  pinMode(EN, OUTPUT);
  pinMode(IN1, OUTPUT);
  pinMode(IN2, OUTPUT);
}

void loop() {
  int knob = analogRead(A0); // 0 to 1023
  int speed = map(knob, 0, 1023, -255, 255);

  if (speed > 20) {
    digitalWrite(IN1, HIGH); // forward
    digitalWrite(IN2, LOW);
  } else if (speed < -20) {
    digitalWrite(IN1, LOW); // backward
    digitalWrite(IN2, HIGH);
  } else {
    digitalWrite(IN1, LOW); // both the same: stop
    digitalWrite(IN2, LOW);
    speed = 0;
  }
  analogWrite(EN, abs(speed));
  delay(50);
}
Description

Set a DC motor's speed and direction with a potentiometer. It compiles and runs on a virtual Uno in the browser. Turn the knob from one end to the other. Then make the motor stop in a wider middle band.

Cite this design
@design{breadboardhub/arduino-robot-motor,
  title = {Arduino Uno: robot motor},
  author = {breadboardhub},
  url = {https://www.breadboardhub.com/breadboardhub/arduino-robot-motor},
  version = {1.0.0}
}