Optical endoder gives two steps

Hello,
I have bought an optical encoder like this :

To read it, I have tried this sketch :

 #define outputA 6
 #define outputB 7
 int counter = 0; 
 int aState;
 int aLastState;  
 void setup() { 
   pinMode (outputA,INPUT);
   pinMode (outputB,INPUT);
   
   Serial.begin (9600);
   // Reads the initial state of the outputA
   aLastState = digitalRead(outputA);   
 } 
 void loop() { 
   aState = digitalRead(outputA); // Reads the "current" state of the outputA
   // If the previous and the current state of the outputA are different, that means a Pulse has occured
   if (aState != aLastState){     
     // If the outputB state is different to the outputA state, that means the encoder is rotating clockwise
     if (digitalRead(outputB) != aState) { 
       counter ++;
     } else {
       counter --;
     }
     Serial.print("Position: ");
     Serial.println(counter);
   } 
   aLastState = aState; // Updates the previous state of the outputA with the current state
 }

It works well but the encoder bouton has some "clicks" (100 per revolution) and each click gives not one pulse but two, the console shows for the 1st one clik :

Position: 0
Position: 1

Then :

Position: 2
Position: 3

etc...

How can I divide by two, and have only one position change each click?
Thanks for your help

Hi,
Code looks fine ...
How is the encoder connected?. Does it give sometimes 3 steps -insteado of two?. Or just one?. Does it behave different if you turn it quicker?.
Regards.

How is the encoder wired? Maybe you need to use pinMode(pin,INPUT_PULLUP) or a debounce library, or (last resort) interrupts.
https://www.pjrc.com/teensy/td_libs_Encoder.html

outsider:
How is the encoder wired? Maybe you need to use pinMode(pin,INPUT_PULLUP) or a debounce library, or (last resort) interrupts.
Encoder Library, for Measuring Quadarature Encoded Position or Rotation Signals

Hi,

I ask for the physical wiring (i mean, has it some filtering, or pull up's, ...). May be the problem is a bounce ...

Regards

Lots of encoders do that. The mechanical clicker has half as many steps as the electrical side. You may find that it always stops in a position where outputA is always HIGH.

Some encoders have a 1:4 ratio so they always stop with both outputs high.

The division operator is the forward-slash.

int realPosition = counter/2;