Hi. I am looking to coordinate a rotary encoder with a dc motor so that the dc motor brakes after 57 encoder rotations, then goes at a slower speed, and finally stops at a new variable "TotalRotations" for when the rotary encoder records that many rotations.
So far, I have this code, and the rotary encoder records the number of rotations in the serial monitor, but besides that, nothing else I want to happen, happens. Would you know how to fix this? Thank you.
int motorPinA = 5;
int motorPinB = 10;
int ena = 1;
int enb = 2;
int totalRotations;
boolean BRAKE = true;
int val;
int encoder0PinA = 3;
int encoder0PinB = 4;
int encoder0Pos = 0;
int encoder0PinALast = LOW;
int n = LOW;
void setup() {
pinMode (motorPinA, OUTPUT);
pinMode (motorPinB, OUTPUT);
pinMode (ena, OUTPUT);
pinMode (enb, OUTPUT);
pinMode (encoder0PinA, INPUT);
pinMode (encoder0PinB, INPUT);
Serial.begin (9600);
}
void loop() {
n = digitalRead(encoder0PinA);
if ((encoder0PinALast == LOW) && (n == HIGH)) {
if (digitalRead(encoder0PinB) == LOW) {
encoder0Pos--;
} else {
encoder0Pos++;
}
Serial.print (encoder0Pos);
Serial.print ("/");
}
encoder0PinALast = n;
if (encoder0Pos < 360 * 57) {
digitalWrite (ena, HIGH);
digitalWrite (enb, HIGH);
digitalWrite (motorPinB, HIGH);
analogWrite (motorPinA, 255);
} else {
if (BRAKE) {
analogWrite(ena, BRAKE);
analogWrite(enb, BRAKE);
BRAKE = false;
} else {
if (encoder0Pos < totalRotations) {
digitalWrite (ena, HIGH);
digitalWrite (enb, HIGH);
digitalWrite (motorPinB, HIGH);
analogWrite (motorPinA, 50);
} else {
analogWrite(ena, BRAKE);
analogWrite(enb, BRAKE);
}
}
}
}