Program to check light intensity

Write the following code in Cloud9 and save it as ldr.js. Run the program and check the output voltage. If the LDR is exposed to bright sunlight, you may get the output message—Looks like a bright sunny day. If this is not possible, point a torch on the LDR surface. You should see the voltage has increased. Based on voltage value, you can guess the light brightness and respond by sending an SMS/e-mail or turn on a smart bulb in case of low light condition. You can also change the intensity of bulb according to the light intensity detected. The code for ldr.js is as follows:

var b = require('bonescript'),
var loopTime = 2000;
var LDR = 'P9_38';
var loopTimer = setInterval(readVoltageLoop, loopTime);

function readVoltageLoop()
{
  b.analogRead(LDR, printVoltage);
}

function printVoltage(pinObj)
{
  var volt = pinObj.value * 1.8;
  console.log("Voltage at input pin = " + volt.toPrecision(3));
  if( volt > 1.6 )
  {
    console.log("Looks like bright sunny day");
  }
}

Explanation

We set the timer to call the function readVoltageLoop() on pin P9_38 after every 2 seconds. Inside the readVoltageLoop() function, we called analogRead(). We specified the callback function printVoltage() to be called when the analog reading is done. So, when analogRead() finishes, printVoltage() is called with the parameter pinObj. The object pinObj has the property value that tells us the value read from the ADC. This value is float type inside the 0–1 range. We multiplied it by 1.8 to get the voltage sensed at pin P9_38. Then we used the JavaScript method toPrecision() to format the float value to a three-digit value and printed it. When this value is high, the LDR is facing bright light. When the value is low, the LDR is in a dark area.

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

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