Expose sensor values as an API
Now that we have an endpoint, let's go one step further and api the room's room temperature
Connect the LM35 analog temperature sensor like this
We'll create an API that returns this kind of data
{
"status" : "success",
"temperature" : 25.3
}
If obniz was not connected, it returns
{
"status" : "failed",
"error" : "Cannot connect to obniz."
}
So let's write the code.
// Runkit Endpoint Example
const Obniz = require("obniz");
const express = require("@runkit/runkit/express-endpoint/1.0.0");
const app = express(exports);
const yourObnizId = "OBNIZ\_ID\_HERE"; // write your obniz id
app.get("/", async (req, res) => {
let obniz = new Obniz(yourObnizId);
let connected = await obniz.connectWait({timeout:10});
if(connected){
let tempSensor = obniz.wired('LM35', { gnd: 0, output: 1, vcc: 2 });
await obniz.wait(100); //wait for stabilizing
let temp = await tempSensor.getWait();
obniz.close();
res.json({ status: "success", temprature : temp});
}else{
res.json({ status: "failed", error : "Caonnot connect to obniz."});
}
});
Let's run it and access the URL. The temperature should be measured and a response should be returned.