I've had a look at your code and I see you have a really big decision tree, an external device, and of course getters and setters can be called at any time, so lots of possibilities. My poor little brain has a hard time reading this, but I'll try.
Your getter and setter use different variables, this is a starting point for me. I am thinking out loud, please bear with me...
Code: Select all
byte getPower() {
Serial.print("getPower() # => ");
Serial.println(powerValue);
return powerValue;
}
void setPower(byte value) {
Serial.print("setPower(");
Serial.print(value);
Serial.println(")");
changePower = true;
targetPower = value == 0 ? POWER_OFF : POWER_ON;
}
So it is no surprise the getter and setter can report different values.
If your controller sets the speed, this is what happens:
Code: Select all
if (changePower) {
if (targetPower != powerValue) {
digitalWrite(ONOFF_BUTTON_PIN, HIGH);
delay(BUTTON_WAIT);
digitalWrite(ONOFF_BUTTON_PIN, LOW);
delay(BUTTON_WAIT);
}
changePower = false;
}
I suppose it pushers a button on your fan. Your fan may or may not turn on or change speed, so you have a function to detect this: readState().
Every 50 ms you call this readState, here is a snippet:
Code: Select all
byte readState() {
byte previousPowerValue = powerValue;
byte previousSpeedValue = speedValue;
if (digitalRead(LOW_SPEED_PIN) == HIGH) {
powerValue = POWER_ON;
speedValue = LOW_SPEED;
}
...
I think that is the ONLY part of the code that sets powerValue, used in the getter.
If I understand this correctly, the setter "pushes" the button on the fan then the "getter" reflects the true state of the fan. So it depends on how fast your external device responds. Without timing information on your debug output, I cannot tell if this is correct.
If I where you, I'd add (a lot) more debug printing and see if you can figure out the sequence of events.
If your hub keeps sending the same setter value in less than about one second, it might also be a communication problem. If the controller does not hear an ACK within a certain period of time, it will repeat its last message.