Program to print temperature

Write the following code in Cloud9 and save it as tmp36.js. Run the program and check the printed temperature. Then touch the plastic body of the sensor for a few seconds (avoid touching metal pins). You should see an increase in temperature. The code for tmp36.js is as follows:

var b = require('bonescript'),
var loopTimer = setInterval(readVoltageLoop, loopTime);
var loopTime = 2000;
var TMP36 = 'P9_40';

function readVoltageLoop()
{
  b.analogRead(TMP36, printTemperature);
}

function printTemperature(pinObj)
{
  var volt = pinObj.value * 1.8;
  var temperature = (100 * volt) - 50;
  console.log("Voltage at input pin = " + volt.toPrecision(3) + " Temperature in Celsius =" + temperature.toPrecision(3) );
}

Explanation

We want to print the temperature after every 2 seconds. So, we created a timer using setInterval(). This timer will call the function readVoltageLoop() after every 2 seconds. The function readVoltageLoop() calls analogRead() on pin P9_40. The first parameter specifies that reading is to be done on the 40th pin on the P9 extension header. This pin is connected to output pin of TMP36 which is sensing temperature from physical world. The second parameter specifies the callback function printTemperature() to be called when the analog reading is done. When reading is done, printTemperature() will be called with the parameter of type object. We named it pinObj. Inside the printTemperature() function, the property value of pinObj is the value read from ADC. This value is of float type inside 0 to 1 range. It needs to be converted to voltage. We use the mathematical mapping function seen earlier. We multiply the property value of pinObj by 1.8 and we get voltage sensed at pin P9_40. Then we follow the equation we got from the TMP36 datasheet to convert voltage to degrees Celsius temperature. We have seen that equation in the TMP36 temperature sensor circuit setup section previously. We get voltage and temperature in float data type with a long trail. We formatted it to a human readable format using the JavaScript method toPrecision().

Here, it rounds off numbers and fits it in three-digit length. The + sign inside console.log() does string concatenation. After 2 seconds, the function readVoltageLoop() gets called again. It calls printTemperature() again. The function printTemperature() prints the sensed voltage and temperature. The program will run forever until exited manually. You can also use another popular temperature sensor LM35 from Texas Instruments. The only change in the equation is: Temperature = 100 * Voltage(measured). Now that we made our BeagleBone aware of the outside temperature, let's make it aware of the light intensity outside.

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

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