1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
| int pulses; //Output pulses.
int deg = 0;
int encoderA = 3;
int encoderB = 2;
const int pwm = 5; //Power of motor.
const int dir = 4; //Direction of the motor.
int pulsesChanged = 0;
#define total 245 //x1 pulses per rotation.
#define motorSpeed 180 //Change speed of the motor.
void setup(){
Serial.begin(115200);
lcd.begin(16,2);
lcd.setCursor(0,0);
lcd.print("x1 ENCODER");lcd.print(" ");
pinMode(encoderA, INPUT);
pinMode(encoderB, INPUT);
pinMode(pwm, OUTPUT);
pinMode(dir, OUTPUT);
analogWrite(pwm,0);
digitalWrite(dir,HIGH);
waitAnyKeyPress();
attachInterrupt(0, A_CHANGE, CHANGE);
}//setup
void loop(){
if (pulses == total) {
analogWrite(pwm, 0);
digitalWrite(dir, HIGH);
}
else {
if (pulses > total) {
analogWrite(pwm, motorSpeed);
digitalWrite(dir, LOW);
}
else if (pulses < total) {
analogWrite(pwm, motorSpeed);
digitalWrite(dir, HIGH);
}
}
if (pulsesChanged != 0) {
pulsesChanged = 0;
lcd.setCursor(0,1);
lcd.print("Pulses:");lcd.print(pulses);lcd.print(" ");
Serial.println(pulses);
}
}
void A_CHANGE(){ //Function that to read the pulses in x1.
if( digitalRead(encoderB) == 0 ) {
if ( digitalRead(encoderA) == 0 ) {
// A fell, B is low
pulses--; // moving reverse
} else {
// A rose, B is low
pulses++; // moving forward
}
}
pulsesChanged = 1;
} |
Partager