const int PWM = 9; // PWM pin
const int motorPin1 = 10; // motor in1
const int motorPin2 = 11; // motor in2
const int encoderPinA = 2; // encoder PinA
const int encoderPinB = 3; // encoder PinB
volatile long encoderPos = 0;
const float ratio = 360.0 / 19.0 / 52.0; // 엔코더
void setup() {
pinMode(motorPin1, OUTPUT);
pinMode(motorPin2, OUTPUT);
pinMode(PWM, OUTPUT);
pinMode(encoderPinA, INPUT_PULLUP);
pinMode(encoderPinB, INPUT_PULLUP);
attachInterrupt(0, doEncoderA, CHANGE);
attachInterrupt(1, doEncoderB, CHANGE);
Serial.begin(115200);
}
void doEncoderA() { encoderPos += (digitalRead(encoderPinA) == digitalRead(encoderPinB)) ? 1 : -1; }
//Serial.println("doEncoderA");
//Serial.println(encoderPos);
void doEncoderB() { encoderPos += (digitalRead(encoderPinA) == digitalRead(encoderPinB)) ? -1 : 1; }
//Serial.print("doEncoderB");
//Serial.println(encoderPos);
void loop() {
if (Serial.available()) {
float targetAngle = 0;
targetAngle = Serial.parseFloat();
Serial.print("targetAngle: ");
Serial.println(targetAngle);
float motorDeg = abs(float(encoderPos) * ratio);
Serial.print("motorDeg: ");
Serial.println(motorDeg);
float angleDifference = targetAngle - motorDeg;
Serial.print("angleDifference: ");
Serial.println(angleDifference);
if (angleDifference > 0) { // clockwise rotation
analogWrite(PWM, 100);
digitalWrite(motorPin1, HIGH);
digitalWrite(motorPin2, LOW);
Serial.println("clockwise");
Serial.println(motorDeg);
Serial.println(encoderPos);
}
if (angleDifference < 0) { // counterclockwise rotation
analogWrite(PWM, 100);
digitalWrite(motorPin1, LOW);
digitalWrite(motorPin2, HIGH);
Serial.println("counterclockwise");
Serial.println(motorDeg);
Serial.println(encoderPos);
}
if (angleDifference == 0) {
analogWrite(PWM, 0); // when motor arrives at targetDeg, the motor will stop.
digitalWrite(motorPin1, LOW);
digitalWrite(motorPin2, LOW);
Serial.println("END");
}
}
}
I want to create a sketch that defines the target angle based on the values I input in the serial monitor and makes the encoder DC motor move according to the difference in the current encoder motor angle.
With the code I have written above, the DC motor doesn't move the desired angle and keeps rotating.
Please help me.

