我想使用旋转编码器控制电机的精度。
例如,我想将电机移动到任意一侧,例如 70 度,并使用旋转编码器返回其原始位置。我写了一个代码,但是这个代码电机不会移动,除非旋转编码器移动。
二手零件
- 带变速箱的直流电机
- arduino 巨型
- 防弹少年团 7960
- 编码器旋转
代码:
// 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;
}