Hi, i'm using this script to read encoder (lpd3806) position and writing it to a SD card.
#include <SPI.h>
#include <SD.h>
#define SD_PIN 10
#define encoderPinA 3
#define encoderPinB 2
volatile long pos=0;
File myFile;
void setup() {
Serial.begin(9600);
//setup rotary encoder
pinMode(encoderPinA,INPUT_PULLUP);
pinMode(encoderPinB,INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(encoderPinA),doEncoderA,CHANGE);
attachInterrupt(digitalPinToInterrupt(encoderPinB),doEncoderB,CHANGE);
//setup SD
if(!SD.begin(SD_PIN)){ while(true); }
myFile = SD.open("ok.txt", FILE_WRITE);
Serial.println("setup completed");
}
void loop() {
myFile.print(pos+",");
}
void doEncoderA() {
// look for a low-to-high on channel A
if (digitalRead(encoderPinA) == HIGH) {
// check channel B to see which way encoder is turning
if (digitalRead(encoderPinB) == LOW) {
pos = pos + 1; // CW
} else {
pos = pos - 1; // CCW
}
} else {// look for a high-to-low on channel A
if (digitalRead(encoderPinB) == HIGH) {// check channel B to see which way encoder is turning
pos = pos + 1; // CW
} else {
pos = pos - 1; // CCW
}
}
}
void doEncoderB() {
// look for a low-to-high on channel B
if (digitalRead(encoderPinB) == HIGH) {
// check channel A to see which way encoder is turning
if (digitalRead(encoderPinA) == HIGH) {
pos = pos + 1; // CW
} else {
pos = pos - 1; // CCW
}
} else { // Look for a high-to-low on channel B
// check channel B to see which way encoder is turning
if (digitalRead(encoderPinA) == LOW) {
pos = pos + 1; // CW
} else {
pos = pos - 1; // CCW
}
}
}
Is it possible to write the position of the encoder only x times a seconds? for example 50 times a second?
What throws me off is that i am reading the position with interrupts and for this reason i'm sure delays won't work. I don't know what else to try.
Ok, Do you know how I can calculate how high I can raise the sampling time? I have problems because of interrupts happening. Encoder i'm using have a response frequency of 0-20KHz