Update: 1st truly succesful counter
It has been really hard to get the encoder to stop occasionally counting transitions more than once. But I just had a rather succesful run at that. My test setup is simple. I put a small piece of red sticky tape on the wheel so I can see when it has performed a full rotation. I then start counting steps and every time it made a full rotation I stop for ~2 secs. I let it run for some 10 minutes and it only got misplaced by a few millimeters. Best so far.
Here is the (rather ugly) code I used:
----------------------------------------------
int val;
int old_val;
int count = 0;
unsigned long int time;
void setup() {
Serial.begin(115200);
Serial.print(“START”); // sync with scope
pinMode(2, INPUT);
val = digitalRead(2);
old_val = val;
time = millis(); // initialize timer
}
void loop() {
analogWrite(5, 100); // move motor
val = digitalRead(2);
if(val == 1) val = 255; // max scope value
//Serial.println(val); // serial monitor
Serial.print(val, BYTE); // scope
if(val != old_val && millis() > time+5) {
if(count < 38) {
count++;
old_val = val;
}
else {
count = 0;
delay(5);
analogWrite(5, 0);
delay(2000);
}
time = millis(); // reset timer
}
delay(1);
}
----------------------------------------------
As you can see I had to make a rather nasty workaround to get it to stop counting some transitions several times. I only count a change if minimum 5 millisecs have past since the last change:
if(val != old_val && millis() > time+5)
Besides that it’s rather odd that I’m using an encoder wheel with 40 clicks per rotation BUT I seem to be only counting 39 clicks per rotation:
if(count < 38)
When I tried it with 39 as it SHOULD be it simply didn’t work?! Strange
I guess making your own encoder isn’t that easy at all. I still have some tweaking and fiddleing to do but it’s starting to look like something
Aniss … Over and out