Created
December 2, 2024 15:54
-
-
Save fxprime/c8295c53469c62fb352f4f39de084850 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* DRV8871 Motor Control with Arduino UNO | |
* | |
* Wiring: | |
* Arduino UNO DRV8871 | |
* ----------------------------------- | |
* D5 IN1 | |
* D6 IN2 | |
* GND GND | |
* VIN VM (Motor Power Supply) | |
* | |
* Control Logic: | |
* 1. PWM duty cycle (0–255) determines motor speed. | |
* 2. Direction (0 = CW, 1 = CCW). | |
* 3. Both inputs LOW stops the motor. | |
* | |
* Usage: | |
* - Enter commands in Serial Monitor as: <PWM> <Direction> | |
* - Examples: | |
* 128 0 -> 50% speed, CW | |
* 199 1 -> ~78% speed, CCW | |
* 0 0 -> Stop | |
* 0 1 -> Stop (same as above) | |
* | |
* Created by: Modulemore Co., Ltd | |
*/ | |
void setup() { | |
Serial.begin(9600); // Start serial communication | |
pinMode(5, OUTPUT); | |
pinMode(6, OUTPUT); | |
analogWrite(5, 0); // Initialize both outputs to 0 | |
analogWrite(6, 0); | |
} | |
void loop() { | |
if (Serial.available() > 0) { | |
String input = Serial.readStringUntil('\n'); // Read input as a line | |
input.trim(); // Remove any trailing newline or spaces | |
int pwmValue = 0; | |
int direction = 0; | |
// Parse the input | |
int spaceIndex = input.indexOf(' '); | |
if (spaceIndex != -1) { | |
pwmValue = input.substring(0, spaceIndex).toInt(); | |
direction = input.substring(spaceIndex + 1).toInt(); | |
} | |
// Constrain values to avoid invalid inputs | |
pwmValue = constrain(pwmValue, 0, 255); | |
direction = constrain(direction, 0, 1); | |
// Motor control logic | |
if (pwmValue == 0) { | |
// Stop the motor | |
analogWrite(5, 0); | |
analogWrite(6, 0); | |
} else if (direction == 0) { | |
// CW: Set PWM on pin 5, pin 6 LOW | |
analogWrite(5, pwmValue); | |
analogWrite(6, 0); | |
} else { | |
// CCW: Set PWM on pin 6, pin 5 LOW | |
analogWrite(5, 0); | |
analogWrite(6, pwmValue); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment