Code analysis
Code analysis
Let us analyse below the meaning of the lines of code applied to the smart watering software.
Full code available at: https://pastebin.com/54hbFX9H
At the beginning of the program, we define some variables (adc_id,
HistoryValue and printBuffer) to store the sensor port number, a historical
value (for further comparison) and a string to send the lectures to the serial
port:
int adc_id = 0;
int HistoryValue = 0;
char printBuffer[128];
The next line define the Arduino pin used to control the relay:
const int RELAY_PIN = A5; // the Arduino pin, which connects to the IN pin of relay
These lines execute once:
- Serial.begin open serial communication at a
9600 baud rate.
- pinMode initialize relay pin (A5) as an output
pin.
- digitalWrite turns the pump off (to be sure the pump is off when Arduino starts).
void setup()
{
Serial.begin(9600);
pinMode(RELAY_PIN, OUTPUT); // initialize digital pin A5 as an output.
digitalWrite(RELAY_PIN, LOW); // turn off pump
}
Let’s now see the void loop()
group of instructions. The following line reads the value from the sensor (A0):
int value = analogRead(adc_id); // get adc value from A0
Here is where we compare the HistoryValue.
These lines execute only if lecture variation is greater than ten (making a
comparison against the last lecture). The objective is to track significant
variations only. The sprintf function
builds and stores a chain to printBuffer
variable, and then (Serial.print)
send the chain to the serial port for monitoring (you can see the values
opening the Monitor tab on the left
of the Arduino Web Editor). Finally, HistoryValue
sets to the last value:
if(((HistoryValue >= value) && ((HistoryValue - value) > 10)) || ((HistoryValue < value) && ((value - HistoryValue) > 10)))
{
sprintf(printBuffer,"ADC%d level is %d\n",adc_id, value);
Serial.print(printBuffer);
HistoryValue = value;
}
The following lines establish the relationship between the sensor (the water level detection sensor) and the actuator (the water pump). Once the sensor is fixed in its final position (in the waterer) and connected to the Arduino Uno controller, we should monitor the lower and higher water level. We then need to edit comparisons and put the correct values where the pump should turn on or off:
if(value < 50) // parameter should be adjusted to the waterer low level
{
digitalWrite(RELAY_PIN, HIGH); // turn on pump
}
if(value > 600) // parameter should be adjusted to the waterer high level
{
digitalWrite(RELAY_PIN, LOW); // turn off pump
}
After the code is compiled and uploaded to the Arduino Uno board, the serial monitor displays the sensor readings’ values:
