Hi. I'm trying to measure some data from rotary encoder. I've done it with interrupts, but the problem is that when the encoder blade is rought half covering the sensor, I get false counts. I was thinking of using analog measurements and make a while loop that checks if millis is big enough to run the code. The problem that occurs is that sometimes it takes more than a millisecond to preform the code, even though when I haven't gave it any conditioning, it performed roughly 8 times per milisecond.
So, my question is, how do i make arduino do the task excatly once every ms (or any other period that I choose). Thanks in advance!
int voltage;
int table[400];
int time[400];
int n;
bool finish;
int ttime;
void setup() {
pinMode(9, OUTPUT);
pinMode(3, OUTPUT);
pinMode(5, OUTPUT);
digitalWrite(5, HIGH);
Serial.begin(115200);
digitalWrite(3, 0);
analogWrite(9, 90);
n = 0;
finish = 0;
ctime = 0;
}
void loop() {
if (n < 400) {
if (millis() - time >= 1) {
voltage = analogRead(A0);
table[n] = voltage;
time[n] = millis();
n++;
ttime = millis();
}
}
else if (!finish) {
finish = true;
analogWrite(9, 0);
for (n = 0; n < 400; n++)
{
Serial.print(time[n]); Serial.print("\t"); Serial.println(table[n]);
}
}
}
GrOnThOs, I'm saving values into array and then print whole array at the end.
If there any other possible workaround? For instance to to add some kind of buffer zone to digitalRead (similar to how flip-flop works), so that it has to reach some low value, before being able to change position? I'm using Pololu optical encoder Pololu - Optical Encoder Pair Kit for Micro Metal Gearmotors, 5V.
The normal millis() counter actually increments every 1024 microseconds; slightly longer than a millisecond. What that means is is that trying to do something every millisecond will be slightly slow, and every 50ms or so, you'll skip a millisecond (millis() result will increment by 2 instead of 1)
If that's not acceptable, you can probably use one of the "timer2" libraries to get interrupts that show up exactly every millisecond (at the expense of losing two PWM outputs.)
westfw:
If that's not acceptable, you can probably use one of the "timer2" libraries to get interrupts that show up exactly every millisecond (at the expense of losing two PWM outputs.)
Robin2, if I use micros(), it takes 223 ms to finish writing an array, compared to 204 ms with millis. Don't know why though.
Possible solution:
Instead of defining a new variable ttimee, I did it like this: When printing out an array, it says it prints it out every ms, so I guess it's all good?
if (millis() >= n) {
voltage = analogRead(A0);
table[n] = voltage;
timee[n] = millis();
n++;
}