Arduino MKR1000 + Sensor DHT11: Demo IoT MQTT no Samsung ARTIK Cloud
Componentes e Materiais
| Arduino MKR1000 | × | 2 |
| Sensor de Temperatura e Umidade DHT11 (4 pinos) | × | 1 |
| LED (genérico) | × | 2 |
Aplicativos e Serviços Online
| Samsung ARTIK Cloud para IoT |
| Arduino IDE |
Sobre o Projeto
Este projeto utiliza dois MKR1000s com DHT11 como sensor e LEDs como atuadores metafóricos. Os atuadores reais poderiam ser ar-condicionado e ventilador de teto. O dispositivo DHT11 de temperatura e umidade envia dados para a nuvem ARTIK. Regras foram configuradas para enviar comandos aos LEDs vermelho e amarelo.
Configurar Arduino IDE
Com o Gerenciador de Bibliotecas da Arduino IDE, instale as seguintes bibliotecas:
- Instale WiFi101 (veja este guia)
- Instale MQTT por Joel Gaehwiler
- Instale ArduinoJson
Nota: Consulte meu post anterior para detalhes sobre como trabalhar com a nuvem ARTIK.
Configurar Sensor DHT11 de Temperatura e Umidade
Crie um tipo de dispositivo (Sensor DHT11)
Conecte um dispositivo (Sensor DHT11 A1)
Conecte os dispositivos físicos
Configure os parâmetros MQTT da nuvem ARTIK
char mqttCloudServer[] = "api.artik.cloud";
int mqttCloudPort = 8883;
char mqttCloudClientName[] = "ARTIK-Arduino";
char mqttCloudUsername[] = "[device-id]";
char mqttCloudPassword[] = "[device-token]";
char mqttCloudDataOut[] = "/v1.1/messages/[device-id]";
WiFiSSLClient ipCloudStack;
MQTTClient mqttCloudClient;
Enviando mensagens para a nuvem ARTIK.
void sendToArtikCloud(float temperature, float humidity) {
loadBuffer(temperature, humidity); // carregar valores atuais no buffer
mqttCloudClient.publish(mqttCloudDataOut, buf);
}
void loadBuffer(float temperature, float humidity) {
StaticJsonBuffer<200> jsonBuffer;
JsonObject& dataPair = jsonBuffer.createObject();
dataPair["temperature"] = temperature;
dataPair["humidity"] = humidity;
dataPair.printTo(buf, sizeof(buf));
}
Configure os atuadores LED de temperatura e umidade
Crie um tipo de dispositivo (Atuador DHT11)
Conecte um dispositivo (Atuador DHT11 A1)
Conecte os dispositivos físicos
Configure parâmetros MQTT da nuvem ARTIK
// Parâmetros MQTT ARTIK Cloud
char mqttCloudServer[] = "api.artik.cloud";
int mqttCloudPort = 1883;
char mqttCloudClientName[] = "ARTIK-Arduino";
char mqttCloudUsername[] = "[device-id]";
char mqttCloudPassword[] = "[device-token]";
char mqttCloudActionsIn[] = "/v1.1/actions/[device-id]";
WiFiClient ipCloudStack;
MQTTClient mqttCloudClient;
Recebendo ações MQTT.
void messageReceived(String topic, String payload, char * bytes, unsigned int length) {
Serial.print("topic=");
Serial.println(topic);
Serial.print("payload=");
Serial.println(payload);
Serial.print("bytes=");
Serial.println(bytes);
Serial.print("length=");
Serial.println(length);
parseBuffer(payload);
}
Analisar e processar ações da nuvem ARTIK.
void parseBuffer(String payload) {
StaticJsonBuffer<200> jsonBuffer;
String json = payload;
JsonObject& root = jsonBuffer.parseObject(json);
const char* nameparam = root["actions"][0]["name"];
const int actionLEDRed = root["actions"][0]["parameters"]["led_red"];
const int actionLEDYellow = root["actions"][0]["parameters"]["led_yellow"];
Serial.print("name=");
Serial.println(nameparam);
Serial.print("led_red=");
Serial.println(actionLEDRed);
Serial.print("led_yellow=");
Serial.println(actionLEDYellow);
Serial.println();
if (actionLEDRed == 1) {
if (savedRedValue != actionLEDRed) {
digitalWrite(LED_RED_PIN, HIGH);
savedRedValue = actionLEDRed;
}
savedRedTime = millis();
} else {
if (savedRedValue != actionLEDRed) {
if (millis() - savedRedTime > RED_DELAY) {
digitalWrite(LED_RED_PIN, LOW);
savedRedValue = actionLEDRed;
}
}
}
if (actionLEDYellow == 1) {
if (savedYellowValue != actionLEDYellow) {
digitalWrite(LED_YELLOW_PIN, HIGH);
savedYellowValue = actionLEDYellow;
}
savedYellowTime = millis();
} else {
if (savedYellowValue != actionLEDYellow) {
if (millis() - savedYellowTime > YELLOW_DELAY) {
digitalWrite(LED_YELLOW_PIN, LOW);
savedYellowValue = actionLEDYellow;
}
}
}
}
Criar Regras
Existem 4 regras:
- SE Sensor DHT11 A1 temperatura > 32 E umidade > 34 ENTÃO enviar para Atuador DHT11 A1 a ação setValue com led_red = 1, led_yellow = 1
- SE Sensor DHT11 A1 temperatura > 32 E umidade < 35 ENTÃO enviar para Atuador DHT11 A1 a ação setValue com led_red = 1, led_yellow = 0
- SE Sensor DHT11 A1 temperatura < 33 E umidade > 34 ENTÃO enviar para Atuador DHT11 A1 a ação setValue com led_red = 0, led_yellow = 1
- SE Sensor DHT11 A1 umidade < 35 E temperatura < 33 ENTÃO enviar para Atuador DHT11 A1 a ação setValue com led_red = 0, led_yellow = 0
Vídeo Demo
Note que você precisará esperar a temperatura aquecer (LED ligado) e esfriar (LED desligado). O LED vermelho liga aos 37 segundos e desliga aos 1:13. O vídeo demo mostra apenas mudanças de temperatura. Usei um secador de cabelo para alterar a temperatura ao redor do sensor DHT11.
Código
artik_dht11_sensor.ino (C/C++)
#include <MQTTClient.h>
#include <ArduinoJson.h>
#include <WiFi101.h>
#include "DHT.h"
#define DHTPIN 2 // pino digital conectado
#define DHTTYPE DHT11 // DHT 11
DHT dht(DHTPIN, DHTTYPE);
const char* _SSID = "[Wi-Fi SSID]";
const char* _PASSWORD = "[Wi-Fi Password]";
// Parâmetros MQTT ARTIK Cloud
char mqttCloudServer[] = "api.artik.cloud";
int mqttCloudPort = 8883;
char mqttCloudClientName[] = "ARTIK-Arduino";
char mqttCloudUsername[] = "[device-id]";
char mqttCloudPassword[] = "[device-token]";
char mqttCloudDataOut[] = "/v1.1/messages/[device-id]";
WiFiSSLClient ipCloudStack;
MQTTClient mqttCloudClient;
char buf[128];
float temperature, humidity;
int n = 0;
void getNextSample(float* Temperature, float* Humidity) {
delay(2000); // aguardar alguns segundos entre medições
*Humidity = dht.readHumidity();
*Temperature = dht.readTemperature(); // Celsius (padrão)
Serial.print("Temperature=");
Serial.println(*Temperature);
Serial.print("Humidity=");
Serial.println(*Humidity);
}
void setup() {
Serial.begin(57600);
dht.begin();
// Configuração WiFi
WiFi.begin(_SSID, _PASSWORD);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println();
Serial.println("WiFi connected");
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
mqttCloudClient.begin(mqttCloudServer, mqttCloudPort, ipCloudStack);
Serial.println("start ARTIK Cloud connect");
Serial.println();
while (!mqttCloudClient.connect(mqttCloudClientName, mqttCloudUsername, mqttCloudPassword)) {
Serial.print("*");
delay(500);
}
}
void messageReceived(String topic, String payload, char * bytes, unsigned int length) {}
void sendToArtikCloud(float temperature, float humidity) {
loadBuffer(temperature, humidity);
mqttCloudClient.publish(mqttCloudDataOut, buf);
}
void loadBuffer(float temperature, float humidity) {
StaticJsonBuffer<200> jsonBuffer;
JsonObject& dataPair = jsonBuffer.createObject();
dataPair["temperature"] = temperature;
dataPair["humidity"] = humidity;
dataPair.printTo(buf, sizeof(buf));
}
void loop() {
if (++n > 10) {
Serial.println("Stopped.");
exit(0);
}
mqttCloudClient.loop();
delay(1000);
getNextSample(&temperature, &humidity);
Serial.println("Publishing...");
Serial.println();
sendToArtikCloud(temperature, humidity);
delay(15000);
}
artik_led_actor.ino (C/C++)
#include <MQTTClient.h>
#include <ArduinoJson.h>
#include <WiFi101.h>
#define LED_RED_PIN 11
#define LED_YELLOW_PIN 13
#define RED_DELAY 5000
#define YELLOW_DELAY 10000
const char* _SSID = "[Wi-Fi SSID]";
const char* _PASSWORD = "[Wi-Fi Password]";
// Parâmetros MQTT ARTIK Cloud
char mqttCloudServer[] = "api.artik.cloud";
int mqttCloudPort = 1883;
char mqttCloudClientName[] = "ARTIK-Arduino";
char mqttCloudUsername[] = "[device-id]";
char mqttCloudPassword[] = "[device-token]";
char mqttCloudActionsIn[] = "/v1.1/actions/[device-id]";
WiFiClient ipCloudStack;
MQTTClient mqttCloudClient;
char buf[128];
int savedRedValue, savedYellowValue;
unsigned long savedRedTime, savedYellowTime;
void setup() {
Serial.begin(57600);
pinMode(LED_RED_PIN, OUTPUT);
pinMode(LED_YELLOW_PIN, OUTPUT);
savedRedValue = savedYellowValue = 0;
// Configuração WiFi
WiFi.begin(_SSID, _PASSWORD);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println();
Serial.println("WiFi connected");
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
mqttCloudClient.begin(mqttCloudServer, mqttCloudPort, ipCloudStack);
Serial.println("start ARTIK Cloud connect");
Serial.println();
while (!mqttCloudClient.connect(mqttCloudClientName, mqttCloudUsername, mqttCloudPassword)) {
Serial.print("*");
delay(500);
}
mqttCloudClient.subscribe(mqttCloudActionsIn);
}
void messageReceived(String topic, String payload, char * bytes, unsigned int length) {
Serial.print("topic=");
Serial.println(topic);
Serial.print("payload=");
Serial.println(payload);
Serial.print("bytes=");
Serial.println(bytes);
Serial.print("length=");
Serial.println(length);
parseBuffer(payload);
}
void parseBuffer(String payload) {
StaticJsonBuffer<200> jsonBuffer;
String json = payload;
JsonObject& root = jsonBuffer.parseObject(json);
const char* nameparam = root["actions"][0]["name"];
const int actionLEDRed = root["actions"][0]["parameters"]["led_red"];
const int actionLEDYellow = root["actions"][0]["parameters"]["led_yellow"];
Serial.print("name=");
Serial.println(nameparam);
Serial.print("led_red=");
Serial.println(actionLEDRed);
Serial.print("led_yellow=");
Serial.println(actionLEDYellow);
Serial.println();
if (actionLEDRed == 1) {
if (savedRedValue != actionLEDRed) {
digitalWrite(LED_RED_PIN, HIGH);
savedRedValue = actionLEDRed;
}
savedRedTime = millis();
} else {
if (savedRedValue != actionLEDRed) {
if (millis() - savedRedTime > RED_DELAY) {
digitalWrite(LED_RED_PIN, LOW);
savedRedValue = actionLEDRed;
}
}
}
if (actionLEDYellow == 1) {
if (savedYellowValue != actionLEDYellow) {
digitalWrite(LED_YELLOW_PIN, HIGH);
savedYellowValue = actionLEDYellow;
}
savedYellowTime = millis();
} else {
if (savedYellowValue != actionLEDYellow) {
if (millis() - savedYellowTime > YELLOW_DELAY) {
digitalWrite(LED_YELLOW_PIN, LOW);
savedYellowValue = actionLEDYellow;
}
}
}
}
void loop() {
mqttCloudClient.loop();
delay(500);
}
Processo de manufatura
- Projeto DHT11: Sensor Temperatura/Umidade com LEDs Indicadores e Buzzer
- Construa um Spybot Controlado por Bluetooth com Arduino
- FlickMote: Controle Remoto IR por Gestos para Casa Inteligente
- DIY Arduino TV B-Gone: Controle Remoto Universal para Todas as TVs
- Construa um Relógio Mestre LED Personalizado com Alarme – Visível a 12 Metros
- Find Me: Localizador Inteligente de Objetos com Arduino e Bluetooth
- Soluções de Energia Otimizadas para Projetos Arduino
- Jogo da Velha com Arduino, Matriz LED MAX7219 e Caixa de Papelão
- Construa um Robô Quadrúpede Inteligente com Arduino: Guia Passo a Passo
- MKR1000 Pinout: A Placa Ideal para Desenvolvimento IoT