encoder only counts up

I use the following code from the Arduino playground.

#include "MonsterMoto.h"

MonsterMoto drive ;

int encoder0PinA = 10;
int encoder0PinB = 11;
int encoder0Pos = 0;
int encoder0PinALast = LOW;
int n = LOW;

void setup() 
{ 
  pinMode (encoder0PinA,INPUT);
  digitalWrite(encoder0PinA, HIGH) ;
  
  pinMode (encoder0PinB,INPUT);
  digitalWrite(encoder0PinB, HIGH) ;
  
  Serial.begin (9600);
} 

void loop() 
{ 
  n = digitalRead(encoder0PinA);

  if ((encoder0PinALast == LOW) && (n == HIGH)) 
  {
    if (digitalRead(encoder0PinB) == LOW) 
    {
      encoder0Pos--;
    } 
    else 
    {
      encoder0Pos++;
    }
     
   Serial.print (encoder0Pos);
   Serial.print ("\n");
   } 
   
   encoder0PinALast = n;
 }

Turning left or right only makes the counter go up.

What could be wrong?

Serial.begin(9600); is very very slow. Your unable to read the encoder correctly at speed as a result.

Use 115200 baud and that should improve. Better still don't Serial.print every time through the loop, do it
every second instead:

void loop()
{
  n = digitalRead(encoder0PinA);

  if ((encoder0PinALast == LOW) && (n == HIGH))
  {
    if (digitalRead(encoder0PinB) == LOW)
    {
      encoder0Pos--;
    }
    else
    {
      encoder0Pos++;
    }
     
   }
   
   encoder0PinALast = n;
 }
 if (millis() % 1000 == 0)
 {
   Serial.print (encoder0Pos);
   Serial.print ("\n");
 }
}

(Note the millis() % 1000 trick isn't perfect as millis() sometimes jumps by two, but it should mean something is printed regularly enough to show if the counting is working)

Turning left or right only makes the counter go up.
What could be wrong?

It is not the code. It counts both up and down with my encoder. You have is a hardware/wiring problem

There is something wrong with the wiring or function of the B output. The Arduino pin is set to input pullup and it is always reading high. It is never pulled low by the encoder, so the count only goes in one direction.

Write a very simple sketch which only does a digitalRead of pin B. You need to see it go both HIGH and LOW.

I found out my problem.

My encoder has 2 hall sensors 44E 402.
These are built in on my DC-motor.
On the website it says that these are 3V3 sensors, but it seems that I have to connect minimum 4,4 V.
In my case I use 5V.
That solved my problem for 1 motor.

The other motor I had to re-adjust 1 hall sensor against the magnetwheel.

Now both DC-motors work and their encoders :smiley: