I solved partially my problem. Now I have the following code:
/*ENCODER*/
int encoder0Pos=0;
int encoderA=3;
int encoderB=4;
int encoderPinALast=LOW;
int n= LOW;
void setup() {
// put your setup code here, to run once:
pinMode(encoderA,INPUT);
pinMode(encoderB,INPUT);
Serial.begin(9600);
}
void loop() {
// put your main code here, to run repeatedly:
n= digitalRead(encoderA);
if((encoderPinALast==LOW)&&(n==HIGH)){
if(digitalRead(encoderB)==LOW){
encoder0Pos--;
}
else{
encoder0Pos++;
}
Serial.println(encoder0Pos);
//Serial.print("/");
}
encoderPinALast=n;
}
The output is always starting from 0 and it increases (if I turn the encoder counterclockwise) or decreases (if I turn the encoder clockwise).
The wiring is the following:
ENCODER -> ARDUINO
Signal A -> digital pin 3 Arduino
Signal B -> digital pin 4 Arduino
Signal 0V -> GND Arduino
Signal +V -> 5V Arduino
Now my problem is the following, how can I use the signal 0 of the encoder as reference signal to understand the movement from the home position?
Upload the following code to the Arduino (I have a DUE).
With the following connections:
ENCODER -> ARDUINO
Signal A -> digital pin 3 Arduino
Signal B -> digital pin 4 Arduino
Signal 0 -> digital pin 5 Arduino
Signal 0V -> GND Arduino
Signal +V -> 5V Arduino
To read the value of the encoder you should type an E and press ENTER in the serial monitor. This because otherwise, if the the movement is too fast, it is not possible to print the value every time.
Moreover in the following code is also inserted the zeroIndex signal and so after one entire round (360°) the counting goes to 0.
If you want to see the degrees instead of the pulses . You just have to modify the following line:
Serial.println(encoder0Pos);
in
Serial.println(encoder0Pos*360/n);
where n is the number of pulses of the encoder per revolution (you find this value, for sure, on the datasheet).
#define encoder0PinA 3
#define encoder0PinB 4
#define encoderZeroIndex 5
volatile int encoder0Pos = 0;
void setup() {
pinMode(encoder0PinA, INPUT);
pinMode(encoder0PinB, INPUT);
pinMode(encoderZeroIndex, INPUT);
attachInterrupt(3, doEncoderA, RISING);
attachInterrupt(5, doEncoderZero, RISING);
Serial.begin (9600);
}
void loop(){
if(Serial.available()){
if(Serial.read()=='E'){
Serial.println(encoder0Pos);
}
}
}
void doEncoderA(){
// look for a low-to-high on channel A
//if (digitalRead(encoder0PinA) == HIGH) {
// check channel B to see which way encoder is turning
if (digitalRead(encoder0PinB) == LOW) {
encoder0Pos = encoder0Pos + 1; // CW
}
else {
encoder0Pos = encoder0Pos - 1; // CCW
}
//}
}
void doEncoderZero(){
encoder0Pos=0;
}
I hope this will help someone,
let me know if there is some error or if something is not clear.