Let there be light!

Now we have everything we need to know to start building our project, let's start by writing the code:

int sensorPin = A0;            // select the input pin for the ldr 
unsigned int sensorValue = 0;  // variable to store the value coming from the ldr 
 
void setup() 
{ 
  pinMode(13, OUTPUT); 
  //Start Serial port 
  Serial.begin(9600);        // start serial for output - for testing 
} 
 
void loop() 
{ 
  // read the value from the ldr: 
  sensorValue = analogRead(sensorPin);      
  if(sensorValue<400) 
       digitalWrite(13, HIGH);   // set the LED on 
  else digitalWrite(13, LOW);   // set the LED off 
   
} 

We start by storing the pin numbers in variables, so that it doesn't become confusing, and then initialize our LED pins for output.

The code consists of a if statement that checks the value of sensorValue. If the values stored in it is less than 400, meaning that the amount of light is less, it will turn the LED on, otherwise, it will turn the LED off. Note how we using another Relational Operator here, the lesser than < operator. Other relational operators include: Greater than (>) Greater or equal to (>=) Lesser or equal to (<=) Not equal to (!=).

Note

Other relational operators include: Greater than (>) Greater or equal to (>=) Lesser or equal to (<=) Not equal to (!=)

Using these Relational operators and Conditional statements, the Arduino has the ability to make fairly advances decisions.

The threshold of 400 may be needing to change depending on the values you get. A good way is to check and determine the threshold using the Serial Monitor code we used earlier, and enter the value that the LDR gives when it's dark.

Hold on to your seats, the best part is yet to come!

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset