Leitura de Temperatura DHT22 via SMS com Arduino Mega 2560
Componentes e Materiais
| Componente | Quantidade |
|---|---|
| Arduino Mega 2560 | 1 |
| Sensor de Temperatura DHT22 | 1 |
| SIM800L | 1 |
| Resistor 10k ohm | 1 |
| Protoboard (genérica) | 1 |
| Fios jumpers (genéricos) | 1 |
Sobre o Projeto
Este projeto é parte de um projeto maior. Tive muitos problemas com esta parte e, ao encontrar solução, decidi compartilhar para ajudar a comunidade.
Descrição do Projeto
Envie SMS para o Arduino e receba a temperatura da casa.
Software
Para o módulo SIM800L, usei a biblioteca "Seeeduino_GPRS-master". Tive que alterar no arquivo "sim800.h" para funcionar no MEGA:
#define SIM800_TX_PIN 8
#define SIM800_RX_PIN 7
Para TX_PIN 10 e RX_PIN 11. Mudar a biblioteca de "SoftwareSerial" para uma das portas seriais do Mega (Serial3) era muito difícil, então usei o caminho mais fácil.
O Problema
Meu código é basicamente copiar/colar de exemplos de duas bibliotecas: "DHT.h" e "Seeeduino_GPRS-master". O problema: o exemplo "gprs.h" só mostrava como enviar mensagem pré-determinada entre aspas. Não consegui descobrir como enviar o valor float variável do sensor de temperatura. O mesmo ocorreu com outras bibliotecas: "GPRS_SIM900-master" e "SIM800L-master".
Gastei semanas buscando exemplos na web e não encontrei nenhum. Encontrei posts em fóruns sobre o mesmo assunto, e para aqueles que não obtiveram respostas, espero que este post ajude.
A Solução
Converter o valor float para String e depois a String para Char Array - simples!
Trecho de Código
MyString = String(temp, 0); // Converte float para String
MyString = (MyString + " Graus C");
// Converte string para char array
int str_len = MyString.length() + 1;
char char_array[str_len];
MyString.toCharArray(char_array, str_len);
gprs.sendSMS("04++++++++", char_array); // Define número e texto
Ligação
Usei bateria ULTRAFIRE 18650 para alimentar o módulo SIM. Depois adicionarei regulador de tensão. Veja este tutorial.
Material de Referência
- https://www.ayomaonline.com/programming/quickstart-sim800-sim800l-with-arduino/
- https://www.sparkfun.com/datasheets/Sensors/Temperature/DHT22.pdf
Bibliotecas
- https://github.com/Seeed-Studio/Seeeduino_GPRS
- https://github.com/adafruit/DHT-sensor-library
Código Completo
DHT_SIMPosting.ino
// Exemplo de teste para sensores DHT umidade/temperatura
// Escrito por ladyada, domínio público
#include "DHT.h"
#define DHTPIN 2
#define DHTTYPE DHT22
DHT dht(DHTPIN, DHTTYPE);
#include
#include
#define TIMEOUT 5000
GPRS gprs;
bool ITemp = false;
float temp;
String MyString;
#define LED_PIN 13
bool ledStatus;
char currentLine[500] = "";
int currentLineIndex = 0;
bool nextLineIsMessage = false;
void Reply() {
Serial.println("GPRS - Send SMS Test ...");
gprs.preInit();
delay(1000);
while(0 != gprs.init()) {
delay(1000);
Serial.print("init error\r\n");
}
Serial.println("Init success, start to send SMS message...");
if (ITemp == true) {
float t = dht.readTemperature();
temp = t;
ITemp = false;
}
MyString = String(temp, 0);
MyString = (MyString + " Graus C");
int str_len = MyString.length() + 1;
char char_array[str_len];
MyString.toCharArray(char_array, str_len);
gprs.sendSMS("04++++++++", char_array);
}
void setup() {
Serial.begin(9600);
Serial.println("DHTxx test!");
dht.begin();
gprs.preInit();
delay(1000);
while(0 != gprs.init()) {
delay(1000);
Serial.print("init error\r\n");
}
if(0 != gprs.sendCmdAndWaitForResp("AT+CMGF=1\r\n", "OK", TIMEOUT)) {
ERROR("ERROR:CNMI"); return;
}
if(0 != gprs.sendCmdAndWaitForResp("AT+CNMI=1,2,0,0,0\r\n", "OK", TIMEOUT)) {
ERROR("ERROR:CNMI"); return;
}
Serial.println("Init success");
}
void loop() {
delay(2000);
float h = dht.readHumidity();
float t = dht.readTemperature();
Serial.print("Umidade: "); Serial.print(h); Serial.println(" %\t");
Serial.print("Temperatura: "); Serial.print(t); Serial.println(" *C ");
SIM();
}
void SIM() {
digitalWrite(LED_PIN, ledStatus);
Serial.println("Procurando SMS");
if(gprs.serialSIM800.available()) {
char lastCharRead = gprs.serialSIM800.read();
if(lastCharRead == '\r' || lastCharRead == '\n') {
String lastLine = String(currentLine);
if(lastLine.startsWith("+CMT:")) {
Serial.println(lastLine);
nextLineIsMessage = true;
} else if (lastLine.length() > 0) {
if(nextLineIsMessage) {
Serial.println(lastLine);
if(lastLine.indexOf("InTemp") >= 0) {
Serial.println("InTemp");
ITemp = true;
Reply();
}
nextLineIsMessage = false;
}
}
for(int i = 0; i < sizeof(currentLine); ++i) currentLine[i] = (char)0;
currentLineIndex = 0;
} else {
currentLine[currentLineIndex++] = lastCharRead;
}
}
}
Esquemático
Diagrama de ligação disponível na seção de esquemáticos.
Processo de manufatura
- Ventilador Controlado por Temperatura: Sistema DIY com Relé para Resfriamento de Móveis de Mídia
- Construa um Registrador de Temperatura com Raspberry Pi e Sensor I2C de $5
- Como Ler Temperatura com DS18B20 no Raspberry Pi 2
- Monitoramento Profissional de Temperatura com Raspberry Pi e DS18B20
- Medição de Temperatura no Raspberry Pi com Sensores Maxim 1‑Wire e Bridge I2C DS2482
- Monitoramento Preciso de Temperatura em Closet de Servidores com Raspberry Pi
- Tutorial IoT Iniciante: Streaming de Dados de Temperatura de um Raspberry Pi
- Construa uma Estação Meteorológica de Laboratório Habilitada para Rede com Raspberry Pi
- Construa Monitor de Temperatura Doméstico com Raspberry Pi, MCP9808, InfluxDB e Grafana
- Construa um Rover Windows IoT Core com Raspberry Pi 2 – Guia do Iniciante ao Avançado