Hi All.
I amm trying to create quadrature encoder simulator.
While getting it done with delayMicrosecods() seems to be ok, then repurposing millis() to do the same thing do not seems to work at all.
Can someone suggest what I`m missing in this code?
This should in theory produce 90deg separate square waves.
Thanks for any help.
const int PhaseA = 3;
const int PhaseB = 4;
unsigned long previousMicrosPhaseA = 0;
unsigned long previousMicrosPhaseB = 0;
const long interval = 300;
void setup() {
pinMode(PhaseA, OUTPUT);
pinMode(PhaseB, OUTPUT);
}
void loop() {
unsigned long currentMicrosPhaseA = micros();
unsigned long currentMicrosPhaseB = micros();
if (currentMicrosPhaseA - previousMicrosPhaseA >= interval) {
digitalWrite(PhaseA, HIGH);
previousMicrosPhaseA = currentMicrosPhaseA;
}
if (currentMicrosPhaseB - previousMicrosPhaseB >= interval) {
digitalWrite(PhaseB, LOW);
previousMicrosPhaseB = currentMicrosPhaseB;
}
if (currentMicrosPhaseA - previousMicrosPhaseA >= interval) {
previousMicrosPhaseA = currentMicrosPhaseA;
digitalWrite(PhaseA, LOW);
}
if (currentMicrosPhaseB - previousMicrosPhaseB >= interval) {
previousMicrosPhaseB = currentMicrosPhaseB;
digitalWrite(PhaseB, HIGH);
}
}
@alto777 What i was hoping to get using these 2 are to write phaseA LOW, then delay with the set time, then write phaseB and so on. I have no clue how to tackle that without stopping the processor.
Stop thinking about it in terms of delay, or delay().
Look into FSM or finite state machines. This is a very simple matter.
By using a 4 state switch/case mechanism, you would only have to code one millis() based timer, which would look like your code only just one frequency, as you might see in BOD blink without delay or any number of examples.
Someone will be along soon to just write the code for you. Don't let that happen, you can do this.
Four cases, each case writes both digital pins as required to achieve the Quadra true <-- haha quadrature phase for that step, like you delay-based code HH HL LL LH if I am awake.
Inside a millis based timing mechanism.
You can even get this to work with delay() as a first version.
Switch/case to set the pins. A counter that runs 0, 1, 2, 3, 0 or that same counter modulo 4 (% modulo operator) selects the case.
Then delay(xx), the time for one phase.
Either approach just plopped into you loop(), which will do its job and, well, loop over that.
At the top of the loop, interrogate any input that changes the frequency as it appears you doing with analaogRead().
Using different previousMillis values for timing the two phases is a truly terrible idea. There is nothing to prevent them getting out of phase due to accumulated timing errors. Use a SINGLE previousMillis value to generate BOTH.