Advertisement
microrobotics

DRV8871 DC Motor Driver - 3.6A

Oct 19th, 2023
1,387
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.13 KB | None | 0 0
  1. /*
  2. The DRV8871 is a motor driver IC designed to control DC motors. Below is a simple example Arduino code to use with the DRV8871 DC Motor Driver. Note that you'll need to connect the appropriate pins from your Arduino to the motor driver according to the datasheet.
  3.  
  4. This code demonstrates how to control a DC motor using PWM for speed control and two digital pins for direction control. Adjust the pin assignments based on your actual wiring. The example includes forward and reverse motions with a brief stop in between. The motorControl function sets the motor speed and direction.
  5.  
  6. Please refer to the DRV8871 datasheet for the correct pin connections and specifications based on your motor and power supply.
  7. */
  8.  
  9. // Define the pins for motor control
  10. const int motorPWM = 9;    // PWM input for motor speed control
  11. const int motorINA = 8;    // Input A for motor direction control
  12. const int motorINB = 7;    // Input B for motor direction control
  13.  
  14. void setup() {
  15.   // Set the motor control pins as outputs
  16.   pinMode(motorPWM, OUTPUT);
  17.   pinMode(motorINA, OUTPUT);
  18.   pinMode(motorINB, OUTPUT);
  19.  
  20.   // Initialize the motor in the stopped state
  21.   digitalWrite(motorINA, LOW);
  22.   digitalWrite(motorINB, LOW);
  23.  
  24.   // Start the serial communication for debugging (optional)
  25.   Serial.begin(9600);
  26. }
  27.  
  28. void loop() {
  29.   // Run the motor forward for 2 seconds
  30.   motorControl(255, HIGH, LOW);
  31.   delay(2000);
  32.  
  33.   // Stop the motor for 1 second
  34.   motorControl(0, LOW, LOW);
  35.   delay(1000);
  36.  
  37.   // Run the motor in reverse for 2 seconds
  38.   motorControl(255, LOW, HIGH);
  39.   delay(2000);
  40.  
  41.   // Stop the motor for 1 second
  42.   motorControl(0, LOW, LOW);
  43.   delay(1000);
  44. }
  45.  
  46. // Function to control the motor
  47. void motorControl(int speed, int inA, int inB) {
  48.   analogWrite(motorPWM, speed);   // Set motor speed
  49.   digitalWrite(motorINA, inA);   // Set direction A
  50.   digitalWrite(motorINB, inB);   // Set direction B
  51.  
  52.   // Optional: print motor speed and direction for debugging
  53.   Serial.print("Speed: ");
  54.   Serial.println(speed);
  55.   Serial.print("Direction: ");
  56.   Serial.println((inA == HIGH) ? "Forward" : (inB == HIGH) ? "Reverse" : "Stop");
  57. }
  58.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement