Example Code for Arduino-Motor Control
This article offers a detailed guide on controlling a DC motor using Arduino, including hardware and software setup, wiring instructions, safety tips, and sample code to run the motor forwards and backwards.
Hardware Preparation
- 1 x DFRduino UNO (or similar)
- 1 x DC Motor Driver
- 1 x DC Motor
- 1 x Fuse@20A
- Jumper wires
Software Preparation
- Arduino IDE Click to Download Arduino IDE from Arduino®.
Wiring Diagram
Facility Safety and the Personal Safety:
Please add a fuse@20A between the Power source and the module (9-36V).
The 5VO port is for 5V output for other module, can NOT be used as Power_In.
Installation Tips
The module needs a cooling system once your motor runs over 15 amps, like Electronics Blower Fan, Heatsink, etc.
The backside of the driver, as right-hand picture shows, that its conducting layer can be very wide, so you should take some measurements to ensure it won't short-circuit, like applying 1mm layer conductive epoxy or any other similar materials.
Important: Pluggable Connector
You may find that the connector is designed as pluggable type to adapt with Male or Female wires.
Sample Code
/*
* @file Motor driver DRI0042_Test.ino
* @brief DRI0042_Test.ino Motor control program
*
* control motor positive inversion
*
* @author [email protected]
* @version V1.0
* @date 2016-8-10
*/
const int IN1=5;
const int IN2=4;
const int PWM=6;
void setup() {
pinMode(IN1, OUTPUT);
pinMode(IN2, OUTPUT);
pinMode(PWM, OUTPUT);
}
void loop() {
Motor_Brake();
delay(100);
Motor_Forward(200);//Forward, PWM setting 0-255
delay(3000);
Motor_Brake();
delay(100);
Motor_Backward(200);//Reverse, PWM setting 0-255
delay(3000);
}
void Motor_Forward(int Speed) {
digitalWrite(IN1,HIGH);
digitalWrite(IN2,LOW);
analogWrite(PWM,Speed);
}
void Motor_Backward(int Speed) {
digitalWrite(IN1,LOW);
digitalWrite(IN2,HIGH);
analogWrite(PWM,Speed);
}
void Motor_Brake(){
digitalWrite(IN1,LOW);
digitalWrite(IN2,LOW);
}
Result
You could see your motor run forward for 3 second and then run reversely for another 3 seconds and repeat this behavior then.
Was this article helpful?
