PaulStoffregen / Encoder

Quadrature Encoder Library for Arduino
http://www.pjrc.com/teensy/td_libs_Encoder.html
561 stars 242 forks source link

Wrong sign after sleep mode on Atmel SAM #70

Closed pauljurczak closed 3 years ago

pauljurczak commented 3 years ago

I'm using Encoder library on Adafruit Feather M0 (Atmel SAM) with PlatformIO on Visual Studio Code. My test program runs a DC motor with a quadrature encoder in the same direction. In normal power mode, the counting is accurate. When I put the microcontroller into sleep at each iteration of the loop, the count changes its sign, which is an error. Here is the code:

#include <Arduino.h>
#include <Adafruit_SleepyDog.h>
#include <Encoder.h>

constexpr int ENCODER_VCC = 11;
constexpr int MOTOR_ENABLE = 10;
constexpr int MOTOR_PHASE = 6;
constexpr int MOTOR_SLEEP = 5;

Encoder encoder(12, 13);

void setup()
{
  pinMode(LED_BUILTIN,  OUTPUT);
  pinMode(ENCODER_VCC, OUTPUT);
  pinMode(MOTOR_ENABLE, OUTPUT);
  pinMode(MOTOR_PHASE,  OUTPUT);
  pinMode(MOTOR_SLEEP,  OUTPUT);
  digitalWrite(ENCODER_VCC, LOW);
  digitalWrite(MOTOR_ENABLE, LOW);
  digitalWrite(MOTOR_PHASE,  LOW);
  digitalWrite(MOTOR_SLEEP,  LOW);

  Serial.begin(9600);
  Serial.println("Basic Encoder Test:");
}

void loop()
{
  digitalWrite(LED_BUILTIN,  HIGH);
  digitalWrite(ENCODER_VCC,  HIGH);
  digitalWrite(MOTOR_ENABLE, HIGH);
  digitalWrite(MOTOR_PHASE,  LOW);
  digitalWrite(MOTOR_SLEEP,  HIGH);

  delay(5000);

  digitalWrite(LED_BUILTIN,  LOW);
  digitalWrite(ENCODER_VCC,  LOW);
  digitalWrite(MOTOR_ENABLE, LOW);
  digitalWrite(MOTOR_PHASE,  LOW);
  digitalWrite(MOTOR_SLEEP,  LOW);

  Serial.println(encoder.read());
  // Watchdog.sleep(5000);
  delay(5000);
}

Incorrect output with Watchdog.sleep(5000);:

-8831
17677
-26537
35401
-44269

Correct output with delay(5000);:

-8855
-17723
-26595
-35461
-44335
pauljurczak commented 3 years ago

This may have been a problem with Serial truncating part of the massage, i.e. - character, when the microcontroller is put into sleep mode.