Ir al contenido principal
Todas las coleccionesConecta tus dispositivos
Conecta un imp006 de Electric Imp a Ubidots
Conecta un imp006 de Electric Imp a Ubidots

Envía datos desde una placa imp006 breakout a tu cuenta de Ubidots.

Sergio M avatar
Escrito por Sergio M
Actualizado hace más de una semana

En esta guía, enviaremos datos de temperatura y humedad desde la placa imp006 breakout de Twilio/Electric Imp a Ubidots.

Requisitos

1. Activa el Kit imp006 Breakout

Electric Imp proporciona una guía completa para configurar tu imp006 por primera vez:



NOTA: Aunque el imp006 cuenta con conectividad celular, recomendamos hacer las primeras pruebas utilizando Wi-Fi. Siempre puedes optar por añadir conectividad celular más adelante.

2. Código del dispositivo: Leer sensores de temperatura y humedad

Electric Imp tiene una biblioteca integrada para leer sensores de temperatura y humedad a bordo a través de I2C. Esta guía proporciona el código de ejemplo del dispositivo para leer dichos sensores y enviar las lecturas a impCloud, donde pueden ser gestionados usando el código del agente:



NOTA: Puedes leer la guía completa para entender cómo gestionar dichas lecturas, aunque nos limitaremos a proporcionar el código del dispositivo aquí. Asegúrate de haber seguido estos pasos:

  1. Activa tu dispositivo con BlinkUp.

  2. Inicia sesión en impCentral.

  3. Copia y pega el Código del Dispositivo en el panel de Código del Dispositivo en el editor de código de impCentral.

CÓDIGO DEL DISPOSITIVO:

// Reading a Sensor Device Code
// ---------------------------------------------------

// SENSOR LIBRARY
// ---------------------------------------------------
// Libraries must be included before all other code

// Temperature Humidity sensor Library
#require "HTS221.device.lib.nut:2.0.1"


// SETUP
// ---------------------------------------------------
// The HTS221 library uses the sensor's i2c interface
// To initialize the library we need to configure the
// i2c and pass in the 12c address for our hardware.

// The i2c address for the Explorer Kits and the
// Battery Powered Sensor Node are all 0xBE.
const I2C_ADDR = 0xBE;

// Find the i2c for your hardware from the list below.
// Paste the hardware.i2c for your hardware into the
// i2c variable on line 32.

// imp006 Breakout Board Kit i2c = hardware.i2cLM
// impExplorer Dev Kit 001 i2c = hardware.i2c89
// impExplorer Dev Kit 004m i2c = hardware.i2cNM
// impAccelerator Battery Powered Sensor Node i2c = hardware.i2cAB
// impC001 Cellular Breakout Board Kit i2c = hardware.i2cKL

// Configure i2c
// Paste your i2c hardware in the variable below
local i2c = hardware.i2cLM;
i2c.configure(CLOCK_SPEED_400_KHZ);

// Initialize the temperature/humidity sensor
local tempHumid = HTS221(i2c, I2C_ADDR);

// Before we can take a reading we need to configure
// the sensor. Note: These steps vary for different
// sensors. This sensor we just need to set the mode.

// We are going to set up the sensor to take a single
// reading when we call the read method.
tempHumid.setMode(HTS221_MODE.ONE_SHOT);


// APPLICATION FUNCTION(S)
// ---------------------------------------------------
// The sensor is now configured to taking readings.
// Lets set up a loop to take readings and send the
// result to the agent.

function loop() {
// Take a reading
local result = tempHumid.read();

// Check the result
if ("error" in result) {
// We had an issue taking the reading, lets log it
server.error(result.error);
} else {
// Let's log the reading
server.log(format("Current Humidity: %0.2f %s, Current Temperature: %0.2f °C", result.humidity, "%", result.temperature));
// Send the reading to the agent
agent.send("reading", result);
}

// Schedule next reading in 10sec
// Change the first parameter to imp.wakeup to
// adjust the loop time
imp.wakeup(10, loop);
}

// RUNTIME
// ---------------------------------------------------
server.log("Device running...");

// Start the readings loop
loop();

3. Código del agente: Enviar datos a Ubidots

Gracias a nuestra biblioteca nativa de ElectricImp, enviar datos a Ubidots se puede hacer en solo unas pocas líneas.

Primero, asegúrate de obtener un token de Ubidots desde tu cuenta, en "Mi Perfil" --> "Credenciales API". En este caso, hemos creado uno específicamente para este proyecto:

3.1. Añadiendo un token de Ubidots como Variable de Entorno

Aunque podrías usar este token directamente en el código del agente, tiene más sentido configurarlo como una variable de entorno, para que se pueda gestionar fácilmente desde una única fuente. Para hacerlo, dirígete a tu cuenta de impCentral, luego ve al Grupo de Dispositivos creado en el paso anterior, y haz clic en "Configuración":

En la sección "Variables de Entorno", añade un JSON válido con tu token de Ubidots:

{    "token": "xxxx-xxxxxxxxxxxxxxxxxxxxx"}

Finalmente, ve a la sección de código y pega el siguiente código del agente:

CÓDIGO DEL AGENTE:

// Reading a Sensor Agent Code
// ---------------------------------------------------

// CLOUD SERVICE LIBRARY
// ---------------------------------------------------
// Libraries must be included before all other code
#require "Ubidots.agent.lib.nut:1.0.0"


// RUNTIME
// ---------------------------------------------------
server.log("Agent running...");

// We recommend setting your Ubidots token as an environmental variable.
// See https://developer.electricimp.com/tools/impcentral/environmentvariables
Ubidots <- Ubidots.Client(__VARS.token);

// Open listener for "reading" messages from the device

device.on("reading", function(reading) {

// Log readings coming from the device, to ease debugging
server.log(http.jsonencode(reading));

// The Ubidots library will setup the JSON payload for you. Just add one each reading per row, then use the sendToDevice function:

data <- {};
data.temperature <- reading.temperature;
data.humidity <- reading.humidity;

Ubidots.sendToDevice(data);

})

NOTA: Cuando instancias el objeto cliente de Ubidots, la etiqueta del dispositivo se establece automáticamente en el ID de tu dispositivo. Esto es útil cuando se despliegan muchos dispositivos porque los nuevos dispositivos aparecerán automáticamente en tu cuenta de Ubidots a medida que se añaden a la flota de imps.

¿Ha quedado contestada tu pregunta?