-
• #2
I don't really understand - so you're saying that the
console.log(sensorValue)
is actually correct, when it gets to that point?Isn't
77 r
coming fromconsole.log(a + " " + c);
? -
• #3
Oh crap, ya its coming from console.log(a + " " + c); I forgot to comment that out.
-
• #4
I'm getting undefined for resTempVal and undefined outputs before console.log(resTempVal); So, i'm assuming there's a small delay while taking the sensor reading and the variable resTempVal isn't set. Is there a way to wait until resTempVal gets set before I continue?
code:
Sensor.prototype.takeReading = function() { var a = this.sensorAddress; var c = this.cmdTable.Reading.R.cmd; var w = this.cmdTable.Reading.R.wait; var d = ""; var sensorStatus = ""; var sensorValue = ""; var captureSensorData = false; I2C1.writeTo(a, c); setTimeout(function () { d = I2C1.readFrom(a, 9); if (d.length > 0) { var dContent = d[0]; switch (dContent) { case 1: sensorStatus = 1; captureSensorData = true; break; case 255: sensorStatus = 255; break; case 254: sensorStatus = 254; break; case 2: sensorStatus = 2; break; } if (captureSensorData === true) { for (i = 1; i < d.length; i++) { sensorValue += String.fromCharCode(d[i]); } } captureSensorData = false; console.log(sensorValue); //<-- I get output return sensorValue; } }, w); }; var restemp = new Sensor("RES TEMP", "temp", 77); var ph = new Sensor("PH", "ph", 78); var ec = new Sensor("EC", "ec", 99); function getAllSensorData() { resTempVal = restemp.takeReading(); console.log(resTempVal); //<-- undefined } setInterval(function () { console.log("Taking Reading: "); getAllSensorData(); }, 5000);
-
• #5
As you say, your problem is that
takeReading
returns immediately - even though it sets a timeout using setTimeout.This is classic JS though. You need to use a callback function:
Sensor.prototype.takeReading = function(callback) { // ... setTimeout(function () { // ... callback(sensorValue); }, w); }; function getAllSensorData() { restemp.takeReading(function(resTempVal) { console.log(resTempVal); }); }
I'm trying to receive a value from my temp sensor. Expect I'm receiving "77 r" (without quotes). I should be receiving a number value.
code: