Reverse DC Motor with Code [Solved]

Hi there,

I recently programmed and built a small radio-controlled car using an Arduino Uno, a small servo and a small 3V DC brushed motor.

It functions perfectly, except that I would like the motor to turn in the opposite direction (which I want to change in my programming; not mechanically).

This is an extract of the code showing my programming relating specifically to the control of the motor:

#define pwmThro 10
const int motor = 5;
int thro;

void setup() 
  pinMode(pwmThro, INPUT);
void loop() 
  thro = pulseIn(pwmThro, HIGH, 25000);
  thro = constrain(thro, 1099, 1890);
  thro = map(thro, 1099, 1890, 0, 254);
  analogWrite(motor, thro);

I tried to put a negative sign before the "255" in the map function, as seen below:

thro = map(thro, 1099, 1890, 0, -254);

This did not produce the desired results.

Can anyone help me modify the above code segment to make the motors turn in the opposite direction?


If you are not using an H-bridge of some sort to drive the motor, you can't reverse the motor just with code. Show a schematic of your wiring, please.

This is the circuit I am using. I am using a MOSFET, not an H-bridge. Can the direction of the motor still be changed using code?

I do apologise for the amateur layout, I drew it a while ago! (Please ignore the potentiometer portion at the bottom left of the circuit).

There is NO way to reverse the current through the motor with that circuit. You need an H-bridge.

Okay, thanks, I appreciate the help.