Arduino Control DC Motor Direction

This sketch will control the direction of rotation of a DC motor based on IR sensor output.  Flashing lights indicate the direction of rotation.

The code for this sketch is below.

A video and wiring diagram are in the editing queue.  If you need them, contact us and we will bump them up.

[code]
//Motor Control Sensor with flashing direction lights
/*When the motor is running, one of two LEDs on the control panel will flash indicating
the dirrection or rotation.*/

#define Sensor A0 //connects to output pin of sensor
#define runPin 5 // must a pwm pin
#define black 6 // connects to black wire on motor
#define red 7 // connects to red wire on motor
int rpm = 200; // sets speed of motor.

#define ledcw 8 // connect led indicating clockwise direction to this pin
#define ledccw 9 // connect led indicating counter-clockwise direction to this pin
int LEDflash;

//millis()
long t1 = 0;
long t2;
long flashTime = 1000;

void setup() {
Serial.begin(9600);
//Motot ————————————–
pinMode(Sensor, INPUT);
pinMode(runPin, OUTPUT);
pinMode(black, OUTPUT);
pinMode(red, OUTPUT);

//LEDs ————————————-
pinMode(Sensor, INPUT);
pinMode(ledcw, OUTPUT);
pinMode(ledccw, OUTPUT);
LEDflash = 1;
t2 = millis();
}

void loop() {

int valSensor = analogRead(Sensor);

if (valSensor > 500) {

digitalWrite(red, LOW);
digitalWrite(black, HIGH);
analogWrite(runPin, rpm);
}

if (valSensor < 500) {

digitalWrite(red, LOW);
digitalWrite(black, HIGH);
analogWrite(runPin, 0);
}

//LED Control
// —————————-
t1 = (millis() – t2);
if (valSensor > 500) {
digitalWrite(ledccw, LOW); //LED ccw should be ‘off’

if (t1 >= flashTime) { // flash timer has timed-out – swap ‘on’ and ‘off’
LEDflash = 1 – LEDflash;
t2 = millis();
Serial.println(t1);
Serial.print(“CW direction “);
Serial.println(LEDflash);
}
digitalWrite(ledcw, LEDflash);
}

//——————————–changing from CW to CCW

if (valSensor <= 500) {
digitalWrite(ledcw, LOW); //LED cw should be ‘off’

if (t1 >= flashTime) { //flash timer has timed out
LEDflash = 1 – LEDflash;
t2 = millis();
Serial.println(t1);
Serial.print(“CCW direction”);
Serial.println(LEDflash);
}
digitalWrite(ledccw, LEDflash);
}
}
[/code]


We hope that you found the information in this page useful. The internet is all about getting and giving. And giving back is the best. Please donate $1 or more to aid us in our continuing quest to add to and polish the information in our site.


Scroll to top