Encoder for Arduino Mega 2560

Hi,
I am new to Arduino and this forum.

I am working on a project where I use an encoder to measure an angle. The code below works well when connecting my encoder to Digital pins 2 and 3. My idea is to use a TFT display to show the angle. But the TFT uses digital pins 2 and 3, and actually all pins from 2 to 13. I wanted to use two digital pins 23 to 53 in the Arduino mega, I have used pins 44 to 46, 52 & 53, pretty much all from 23 to 53, and the readings I got are erroneous. If I connect back to any pin digital 2 to 13, it reads well.

I would be grateful if someone can guide me in solving this.

#include <Encoder.h>

Encoder myEncoder(2, 3);
int inPin = 7;    // pushbutton connected to digital pin 7
const unsigned long timePeriod = 1000;    //1000 miliseconds
unsigned long startTime;


float cpr = 2000;    //Cycles per revolution (from the encoder)
float ppc = 4;       //Pulses per Cycle (from encoder. TYpical 4-> A=0 B=0, A=1 B=0, A=1 B=1 & A=0 B=1
float angperpulse = 360 / (cpr*ppc); // Angle per pulse
void setup() {
  Serial.begin(9600);
  Serial.println("Encoder Test:");
}
long position  = -999;
void loop() {
  int zero = digitalRead(inPin);
  long newPosition;
  newPosition = myEncoder.read();
  if (newPosition != position) {
    Serial.print("Angle = ");
    Serial.print(newPosition * angperpulse, 3);
    Serial.print(", zero = ");
    Serial.print(zero);
    Serial.println();
    position = newPosition;
  }
  // if a character is sent from the serial monitor,
  // reset both back to zero.
  if (zero == 1) {
    Serial.read();
    Serial.println("Reset myEncoder to zero");
    myEncoder.write(0);


  }
}

IO-pins 2 and 3 are interrupt-capable.
So it might be that the encoder is read by interrupts if you use the encoder on interrupt-pins
But I'm not familiar with the Encoder.h-library.

On an arduino Mega 2560 the following IO-pins are interrupt-cabaple
Mega, Mega2560, MegaADK io-pins 2, 3, 18, 19, 20, 21

So if IO-pins 18,19 or 20,21 are not used yet you can try on these IO-pins.

Not using interrupts for encoder-reading means that your main-loop must repeat faster than your fastest encoder-pulsetrain to catch all encoder-pulses.

Me personal I prefer using the NewEncoder-library. This library is interrupt-based.
This means you can use this library only if you connect the encoder to interrupt-capable IO-pins which on a Arduino Mega are IO-pins 2, 3, 18, 19, 20, 21

Arduinos Una/Mega are limited if you want to connect a lot of devices that need interrupts or high-speed communication.
In such cases microcontrollers like ESP32, Seeeduino XIAO or Teensy are better suited because they have

  • more RAM / more flash
  • higher CPU-clock
  • WLAN / Bluetooth on board
  • native USB
    best regards Stefan

Thanks, I was able to run it using IO-pins 18,19 and free the digital pins for the display.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.