I want to control the accuracy of the motor using a rotary encoder.
For example, I want to move the motor to any side, for example, 70 degrees, and return to its original place using a rotary encoder. I wrote a code, but this code the motor does not move unless the rotary encode is moved.
Used parts
- motor dc with gearbox
- arduino mega
- bts 7960
- encoder rotary
Code:
// Rotary Encoder Inputs
#define inputCLK 3
#define inputDT 2
int LPWM = 6; //
int LEN = 9; //
int RPWM =5; //
int REN = 8; //
int counter = 0;
int currentStateCLK;
int previousStateCLK;
String encdir ="";
void setup() {
// Set encoder pins as inputs
pinMode (inputCLK,INPUT);
pinMode (inputDT,INPUT);
pinMode(LPWM, OUTPUT);
pinMode(RPWM, OUTPUT);
pinMode(LEN, OUTPUT);
pinMode(REN, OUTPUT);
digitalWrite(LEN, HIGH);
digitalWrite(REN, HIGH);
// Setup Serial Monitor
Serial.begin (9600);
// Read the initial state of inputCLK
// Assign to previousStateCLK variable
previousStateCLK = digitalRead(inputCLK);
}
void loop()
{
// Read the current state of inputCLK
currentStateCLK = digitalRead(inputCLK);
// If the previous and the current state of the inputCLK are different then a pulse has occured
if (currentStateCLK != previousStateCLK){
// If the inputDT state is different than the inputCLK state then
// the encoder is rotating counterclockwise
if (digitalRead(inputDT) != currentStateCLK) {
counter --;
encdir ="CCW";
digitalWrite(RPWM,HIGH); //move forward and backward
digitalWrite(LPWM, LOW);
} else {
// Encoder is rotating clockwise
counter ++;
encdir ="CW";
digitalWrite(RPWM,LOW);
digitalWrite(LPWM, HIGH);
}
Serial.print("Direction: ");
Serial.print(encdir);
Serial.print(" -- Value: ");
Serial.println(counter);
}
// Update previousStateCLK with the current state
previousStateCLK = currentStateCLK;
}