Created
October 28, 2023 09:02
-
-
Save kachurovskiy/1304c2afade002920c648232dc553201 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
const int potPin = A0; | |
const int enaPin = 4; | |
const int dirPin = 5; | |
const int stepPin = 6; | |
const int fwdPin = 12; | |
const int revPin = 11; | |
const int maxSpeed = 700; // RPM | |
const int stepsPerRevolution = 200; | |
const int minPotValue = 20; // Minimum pot value to start the motor | |
int prevPotValue = 0; | |
int motorSpeed = 0; | |
int motorDirection = 0; | |
bool wairingForZero = true; | |
bool decelerate = false; | |
void setup() { | |
pinMode(fwdPin, INPUT_PULLUP); | |
pinMode(revPin, INPUT_PULLUP); | |
pinMode(dirPin, OUTPUT); | |
pinMode(stepPin, OUTPUT); | |
pinMode(enaPin, OUTPUT); | |
digitalWrite(dirPin, HIGH); | |
digitalWrite(enaPin, LOW); | |
Serial.begin(9600); | |
} | |
void loop() { | |
// Direction and enable logic. | |
if (digitalRead(fwdPin) == LOW && digitalRead(revPin) == HIGH) { | |
if (motorDirection != 1) { | |
motorDirection = 1; | |
wairingForZero = true; | |
decelerate = false; | |
digitalWrite(dirPin, LOW); | |
digitalWrite(enaPin, HIGH); | |
Serial.println("FWD"); | |
} | |
} else if (digitalRead(revPin) == LOW && digitalRead(fwdPin) == HIGH) { | |
if (motorDirection != -1) { | |
motorDirection = -1; | |
wairingForZero = true; | |
decelerate = false; | |
digitalWrite(dirPin, HIGH); | |
digitalWrite(enaPin, HIGH); | |
Serial.println("REV"); | |
} | |
} else if (motorDirection != 0) { | |
Serial.println("OFF"); | |
digitalWrite(enaPin, LOW); | |
motorDirection = 0; | |
decelerate = true; | |
} | |
// Speed. | |
int rawPotValue = analogRead(potPin); | |
int potValue = (rawPotValue + prevPotValue) / 2; | |
prevPotValue = rawPotValue; | |
if (potValue < minPotValue && wairingForZero) { | |
wairingForZero = false; | |
Serial.println("Found 0"); | |
} | |
if (!decelerate && !wairingForZero && motorDirection != 0) { | |
int newSpeed = 0; | |
if (potValue >= minPotValue) { | |
newSpeed = map(potValue, minPotValue, 1023, 10, maxSpeed); | |
} | |
if (newSpeed > motorSpeed) motorSpeed++; | |
else if (newSpeed < motorSpeed) motorSpeed--; | |
} | |
// Decelerate to avoid abrupt stops. | |
if (decelerate) { | |
if (motorSpeed > 0) motorSpeed--; | |
else decelerate = false; | |
} | |
// Issue a step. | |
if (motorDirection != 0 && motorSpeed != 0) { | |
long stepDelay = 75000 / motorSpeed; | |
digitalWrite(stepPin, LOW); | |
digitalWrite(stepPin, HIGH); | |
delayMicroseconds(stepDelay); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment