The structure of an Arduino programming language must contain at least two functions.
void setup() is the first function runs in the program which contains the declaration of variables. This function is used to set pinMode or initialize serial communication. It must be present in the program even there are no variables to declare.
As the function name suggests, the functionvoid loop() runs continuously which controls the Arduino board.
Whenever there is an obstacle in range, LED will glow.
The digital sensor I am using for this example is Infrared Obstacle Sensor. Connecting the sensor to Arduino is shown below.
The Sensor has 3 pins.
VCC is connected to the 5V pin of the Arduino. GND is connected to GND pin of Arduino. The sensor gives LOW output at OUT pin when there is an obstacle present in some range(10 to 15 cms depends on the sensor). The OUT pin of the sensor is connected to the 2nd pin of the Arduino.
Variable LED is assigned to 12(pin number) and OBSTACLE is assigned to 2(pin number) of Arduino. In functionvoid setup() ,pinMode sets the mode of the pin(Input/Output). OBSTACLE is set to INPUT since we are reading the value of OUT pin of the sensor. LED is set to OUTPUT.
In the void loop function, digitalRead(OBSTACLE) returns HIGH/LOW. Whenever there is an obstacle in range, the function reads LOW. digitalWrite(LED,val); This function writes HIGH/LOW at pin number 12.