Something not good here:
“OFF” and “ON” aren’t strings, they are “symbolic constants” that are defined for you somewhere in the Arduino header files. So they don’t have quotes around them. The quotes are legal in a definition - they become part of the constant - but it makes them look like strings, and they are not. I often define my own:
#define LEDON LOW
#define LEDOFF HIGH
No quotes there. That looks silly but if you have a LED that is active-low, i.e. the LED is connected to the supply and is on when the output is at 0 V, it makes the state of the output that drives the LED ‘sensible’ in the logic. digitalWrite(LEDPin, LEDON);
drives the output low and turns the LED on.
And why test again inside the “else”? What you’re doing is (a) wasting time and effort and adding complication (and maybe confusion), and (b) locking out the possibility of the current being exactly equal to 0.31. I know that’s a practical improbability with real numbers, but if you ever do it with an integer, you could be in big trouble. It’s a habit get out of, fast! But if you were measuring temperature that changed slowly, you would almost certainly need two different values to define a ‘dead band’ so that tiny changes as it crossed the set point didn’t cause the output to flutter. Check how a real thermostat works.
Why not make the states “boolean”? They can have only two values - it makes it clearer and easier to understand.
If you did that, you could shorten those 9 lines to:
currstat = (Irms > 0.31);
Do you understand how that can work? (Irms > 0.31) evaluates to either true or false, and you assign that to a Boolean, which can only be true or false. So currstat will be true for Irms greater than 0.31, false otherwise. If you don’t like currstat being true and false, define two new names at the top of your sketch:
#define CURRENT_ON true
#define CURRENT_OFF false
There’s also redundancy here if(currstat != prevstat)
If it’s ON (or OFF) now and not that the last time, it must be different!
Why divide the current by 2? You could just as easily change the detection level. And it’s bad practice to put numbers like 0.31 buried deep in the code. Much clearer and safer to use a const variable, declared and defined at the top:
const double setpoint = 0.31 // The current at which the appliance is surely running.
(Look up what const
does for you.)
Get rid of all the variables you thought you wanted but never used. The compiler will most likely ignore them, but they’ll confuse you in a few months or years time.