SukkoPera:
Non credo di avere capito... Dove l'hai inserita?PS: Per favore premite CTRL+T nell'IDE e riposta lo sketch com'è ora.
Ecco lo sketch. Non va bene perchè ora lo spostamento è così veloce che si ferma un bel po' dopo, invece di fermarsi a 100 passi si ferma oltre i 200
//--------------sezione encoder ------------------
int encoderPin1 = 2;
int encoderPin2 = 3;
int encoderPinZero = 4;
int led = 5;
volatile int lastEncoded = 0;
volatile long encoderValue = 0;
long lastencoderValue = 0;
int lastMSB = 0;
int lastLSB = 0;
//-----------------sezione X----------------------
int AD = 9;
int CB = 8;
int passi = 100;
void setup() {
//--------------sezione encoder------------------
Serial.begin (9600);
pinMode(encoderPin1, INPUT);
pinMode(encoderPin2, INPUT);
pinMode(encoderPinZero, INPUT_PULLUP);
attachInterrupt(0, updateEncoder, CHANGE);
attachInterrupt(1, updateEncoder, CHANGE);
//--------------sezione X------------------------
pinMode(AD, OUTPUT);
pinMode(CB, OUTPUT);
pinMode(led, OUTPUT);
}
//--------------------sezione X----------------------
void sx() {
digitalWrite(AD, LOW);
delay(1);
digitalWrite(CB, HIGH);
if (encoderValue > passi) {
digitalWrite(CB, LOW);
}
}
void dx() {
digitalWrite(CB, LOW);
delay(1);
digitalWrite(AD, HIGH);
}
void loop() {
//-----------sezione encoder----------
Serial.print(encoderValue);
Serial.print(" - ");
Serial.println(passi);
int val = digitalRead(encoderPinZero);
if (val == LOW) {
encoderValue = 0;
}
//-----------sezione x---------------
sx();
}
//----------------sezione encoder ------------------
void updateEncoder() {
int MSB = digitalRead(encoderPin1); //MSB = most significant bit
int LSB = digitalRead(encoderPin2); //LSB = least significant bit
int encoded = (MSB << 1) | LSB; //converting the 2 pin value to single number
int sum = (lastEncoded << 2) | encoded; //adding it to the previous encoded value
if (sum == 0b1101 || sum == 0b0100 || sum == 0b0010 || sum == 0b1011) encoderValue ++;
if (sum == 0b1110 || sum == 0b0111 || sum == 0b0001 || sum == 0b1000) encoderValue --;
lastEncoded = encoded; //store this value for next time
}