Now it's time to grab some analog data. Wait a second? Analog? Isn't the world we live in—including the BBB's—all digital? Mostly, yes. But the world of sensors is vast, and many of the most ubiquitous, most useful, and least costly sensors are analog devices. A great deal of the embedded sensing world—motion, temperature, humidity, light intensity, pressure, and accelerometers—consists of analog animals. So, how do we capture all that analog data goodness?
With ADC (analog to digital converter) pins, of course. And the BBB comes with seven pre-assigned analog inputs on our board, so it's nearly plug and play! Well, not quite. But at least we don't have to fuss with pin muxing right away.
For this recipe, we're using the TMP36, a very low cost (USD $1.50) analog temperature sensor that you can find at many different electronics stores or suppliers. It outputs an analog voltage that is proportional to the ambient temperature. We will write a script that takes that proportional value and reads back the temperature into the Cloud9 console.
Be sure that you…
Put the GND into the special analog ground GNDA_ADC on the BBB. In our diagram, that's the black wire into pin P9_34.
Put the 3V into the 3V on the BBB. In our case, that's the red wire into pin P9_3.
For the sensor (markings facing you), match up the pins as follows:
Pin 1 (left pin): Power/3.3V
Pin 2 (middle pin): Analog pin on the BBB which in our recipe is pin P9_38, or AIN3
Pin 3 (right pin): Ground pin on the BBB
http
://192.168.7.2:3000
and use the following code to begin capturing temperature readings://Setup var b = require('bonescript'); // Read library var TMP36 = "P9_38"; // Pin location for sensor //Check the temperature every 4 seconds setInterval(readTMP, 4000); //Define the 'readTMP' function function readTMP() { b.analogRead(TMP36, writeTMP); } //Define the 'writeTMP' function function writeTMP(x) { var millivolts = x.value * 1800; // 1.8V var temp_c = (millivolts - 500) / 10; var temp_f = (temp_c * 9/5) + 32; console.log("Current temperature is " + temp_c + " C and " + temp_f + " F"); }
// Setup var b = require('bonescript');
var TMP36 = "P9_38"; // Pin location for sensor
setInterval(readTMP, 4000);
readTMP
function:function readTMP() { b.analogRead(TMP36, writeTMP); }
writeTMP
function, which is where the voltage data captured is turned into temperature readings. We calculate the temperature from the voltage in millivolts with a simple formula, Temp C = 100 x (reading in V) - 50:function writeTMP(x) { var millivolts = x.value * 1800; // 1.8V var temp_c = (millivolts - 500) / 10; var temp_f = (temp_c * 9/5) + 32; console.log("Current temperature is " + temp_c + " C and " + temp_f + " F"); }
Current temperature is 20 C and 68 F Current temperature is 22.4 C and 72.32 F
You can try exactly the same exercise, this time with Python—https://learn.adafruit.com/setting-up-io-python-library-on-beaglebone-black/adc.
18.222.111.24