Lab: DC Motor Control Using an H-Bridge
In this lab I learned to control the functions of a DC motor through a motor driver board that handles power functions for the motor and communicates with an Arduino.
The motor controller on hand was a A4988 Stepper Motor Driver Carrier from Pololu. The A4988 board pinout and basic wiring diagram here:
My setup with the Arduino Mega and a 12-volt DC computer fan looked like this:
While the motor controller was designed for a stepper motor, which has two separate coils, the DC motor I was using only had one so I only need to wire up the “A” motor pins.
Next I added a switch to the circuit that would be read by the Arduino Mega to then set the DC motor to ON or OFF.
Using a tutorial from MarkerGuides.com as a starting point I revised their Arduino sketch into the code below and was able to turn the DC fan motor ON and OFF. I a not entirely sure why but it was necessary toggle the digitalWrite() for the motor driver pin multiple times in the code to set the state to ON or OFF.
/*Example sketch to control a stepper motor with A4988 stepper motor driver and Arduino without a library. More info: https://www.makerguides.com */ // Define stepper motor connections and steps per revolution: #define dirPin 2 #define stepPin 3 #define switchPin 4 #define stepsPerRevolution 200 int switchState = LOW; void setup() { // configure the serial connection: Serial.begin(9600); // Declare pins as output: pinMode(stepPin, OUTPUT); pinMode(dirPin, OUTPUT); pinMode(switchPin, INPUT); } void loop() { // if the switch is high, motor will turn on one direction: if (digitalRead(switchPin) == HIGH && switchState == LOW) { digitalWrite(stepPin, LOW); // set motor driver high digitalWrite(stepPin, HIGH); // set motor driver high digitalWrite(stepPin, LOW); // set motor driver low digitalWrite(stepPin, HIGH); // set motor driver high Serial.println("HIGH"); switchState = HIGH; } // if the switch is low, motor will turn in the other direction: else if(digitalRead(switchPin) == LOW && switchState == HIGH) { digitalWrite(stepPin, LOW); // set motor driver low digitalWrite(stepPin, HIGH); // set motor driver high digitalWrite(stepPin, LOW); // set motor driver high digitalWrite(stepPin, HIGH); // set motor driver high Serial.println("LOW"); switchState = LOW; } delay(10); }