Code analysis
Code analysis
Let us analyse below the meaning of the lines of code applied to the smart-streetlight software.
The include command loads the SoftwareSerial library. This library
allows serial communication on digital pins of the Arduino (emulating software
functionality):
#include<SoftwareSerial.h>
A constant sensorPin is set
for pin A0. The sensor's variable sensorValue
is set, and it is assigned an initial value of 0, while a led variable is assigned to the pin to which the LED is connected
(pin 3):
int sensorPin = A0;
int sensorValue = 0;
int led = 3;
Void setup ()
is the function within which we tell Arduino the commands it should execute
(one time only) at boot time. In this case, the pinMode command is executed, indicating the pin number (previously
stored in the led variable) and the type (OUTPUT). With Serial.begin, we indicate the transmission speed of the serial port
(9600):
void setup () {
pinMode(led, OUTPUT);
Serial.begin(9600);
// put your setup code here, to run once:
}
The loop function or void loop() is the main function of the program. It is the place where the Arduino will execute the commands while it is turned on. The MCU starts with the first command, will go to the end and immediately jump to the beginning to repeat the same sequence indefinitely.
The println() method writes data to the serial port. This allows the data produced by the program to be sent to any device connected to that port. The value of pin A0 read by the analogRead() function is stored in the sensorValue variable. The result of the reading is sent to the serial port via Serial.println(sensorValue).
The if() statement compares the value contained in the sensorValue variable. If it is less than 100, it prints the message that the LED is on and then turns it on by sending a high value to port 3 using the digitalWrite instruction. On the contrary, if the sensorValue variable's value is equal to or greater than 100, then use the same instruction to turn off the LED by sending a low signal to port 3:
void loop () {
sensorValue = analogRead(sensorPin);
Serial.println(sensorValue);
if(sensorValue < 100)
{
Serial.println("LED light on");
digitalWrite(led,HIGH);
delay(1000);
}
digitalWrite(led,LOW);
delay(sensorValue);
// put your main code here, to run repeatedly:
}