Hardware Reference
In-Depth Information
Listing 19-1 ( continued)
101 delay(60 * 60 * 1000 / 255); //Sleep for a few seconds
102 }
103
104 //Wait for 4 hours
105 delay(4 * 60* 60 * 1000);
106 }
This sketch begins by importing the Scheduler library. On lines 3 and 4, the
input and output pins are dei ned. On lines 6, 7, and 8, the pins used to con-
trol the color components are declared. On lines 10 and 11, two temperatures
are dei ned; the minimum and maximum temperature. When the minimum
temperature is reached, the heating element is turned on. When the maximum
temperature is reached, the heating element is turned off. Change the values
to suit your aquarium.
On line 13 a variable is declared, containing the status of the output pin. By
default, the status is set to LOW. On line 15 a temporary value is declared. It
will be used later by one of the functions.
setup() is declared on line 17. It coni gures the serial port at 9600 baud; it sets
the sensor pin to input; and it registers two functions as threads: heatloop()
and lightloop() .
loop() is declared on line 30 and contains a single instruction: yield() .
Every time the CPU gives control to this function, it immediately gives control
back to the sketch, allowing the CPU to control the two other scheduled loops.
On line 36, heatloop() is declared. This is the function that supervises the
heating element; taking measurements from the LM35 and acting upon that
information. First, on line 40, it reads the temperature on the analog input in
degrees Celsius. On lines 43 and 44, this temperature is printed to the serial
port. On line 47, program execution enters an if statement depending on the
state of the output pin. If the pin is set to LOW , it compares the current tem-
perature to the minimum temperature. If the current temperature is too low,
the pin status is inverted, and the pin is set to HIGH . If the pin is already HIGH ,
the current temperature is checked against the maximum temperature. If the
temperature is too high, the pin status is again inverted, the pin is set LOW , and
program execution continues. On line 7, another comparison is made. If the
current temperature is lower than the minimum allowed temperature minus 2
degrees, the serial port issues a warning; maybe the heating element is defec-
tive and can no longer heat the water, in which case immediate action should
be taken. Finally, the function sleeps for 10 seconds before continuing. Because
the Scheduler library has been imported, this is no longer a blocking function;
instead, control is given to other threads.
On line 76, lightloop() is declared. This function relies heavily on delay() ,
something that can be tricky when using threads. It has i ve phases. First, it runs
delay() for 7 hours. Remember, this application will be plugged in at midday,
Search WWH ::




Custom Search