I have a programme for a system where my arduino uno will read 2 temperature sensors. if the temperature is above a set point a fan will be turned on and when below will turn off ect. I have a manual start button which will override the function and turn the fan on for 1 hour and one that will turn the fan off for 1 hour if it is on using millis().
I need help finding a shorter way to write this as it is very long winded. And could somebody help as to how I should implement the second button (where) and if I will need to copy the main function code again. Thanks.
Also if you spot any more errors, please could you let me know.
I'd probably structure it like this (pseudocode) :
loop() {
Test override state for time expiry and set as required ;
Read override buttons and set time and state if pressed ;
Read sensors ;
if ( based on override states(s) and sensors the fan should be on ) switch_on_fan() ;
else switch_off_fan ;
}
If you are going to do this then you might just as well use delay() as your current code is just as blocking. I assume that the period of 1 second is only for testing purposes
Personally I would turn the program into a state machine, which sounds scary but isn't. The program will be in one of several states at any time, such as
In each state only certain code needs to be executed and there will also be code common to some/all of them that is executed unconditionally. You can control whether the code for the current state is executed using a series of if/else but personally I like to use switch/case based on the current state. This nicely separates the code into blocks and by defining constants the states can be given meaningful names
Let me know if you want to know more about the techniques suggested
To add to Reply #2, it makes the development of a program much easier if {A} the reading of inputs {B} the analysis of the values from those inputs and {C} the actions to take based on the analysis are each in separate functions. Then each part can be tested separately.
It is in the part I refer to as "analysis" that changes to the state variable(s) would take place and the "action" part would take account of the current state without needing to know anything about how it got to that value.