This project implements PWM control for an infrared heating lamp with integrated environmental monitoring and ventilation management. Using a DHT22 temperature and humidity sensor, an Arduino Uno regulates heat output via PWM while automatically triggering exhaust fans when conditions exceed setpoints. The system displays real-time readings on a 16x2 LCD and includes a PID controller to maintain stable temperature and humidity levels with software safety limits.
The guide provides a complete wiring diagram, parts list, and step-by-step assembly instructions starting with sensor calibration and low-voltage testing before connecting the 12V power distribution to the fans. Firmware configuration allows users to adjust temperature and humidity targets through the serial monitor, with detailed explanations of the PID tuning parameters and relay logic for safe operation of the heating and ventilation circuits.
Wiring diagram
Gather all the parts
Assemble it in 6 steps
1. Ligue o sensor
DATA no D2, VCC no 5V e GND no GND. O resistor de 4,7 kΩ vai entre DATA e 5V. Confira a ordem dos terminais no seu DHT22. Instale o sensor fora do jato de névoa e sem receber radiação direta da lâmpada.
2. Teste os comandos em baixa tensão
D3 comanda o LED vermelho (calor); D6 pisca o verde uma vez para ligar a névoa e três vezes para desligar. O LED só testa os pulsos. Passe cada sinal pelo próprio resistor de 330 Ω até o ânodo, e ligue o cátodo ao GND. Os LEDs são indicadores, não acionadores de potência.
3. Ligue o canal de ventilação
Use um módulo de relé de 5 V com entrada ativa em LOW. Ligue VCC a 5V, GND ao GND e IN ao D4. Ligue o resistor de 10 kΩ entre IN e 5V. Sem a fonte de 12 V, confira que COM e NO só fecham quando há comando, inclusive testando o reinício.
4. Alimente a ventilação em 12 V
Com a fonte desligada, ligue o positivo de 12 V a COM e NO aos positivos do ventilador e do exaustor em paralelo. Una os negativos dos dois ao negativo da fonte. Os contatos não precisam compartilhar GND com o Uno. Confira que os contatos são adequados para motores em corrente contínua e que a fonte suporta a partida simultânea.
- Não ligue 12 V ao Uno nem use este canal para a lâmpada de 127 V. Mantenha o circuito fora da área úmida.
5. Ligue o LCD 16x2 I2C
VCC no 5V, GND no GND, SDA no A4 e SCL no A5. Ajuste o contraste no trimpot do módulo se necessário.
6. Ajuste as metas pelo monitor serial
Com a lâmpada e o nebulizador desconectados, conecte o Uno por USB e pressione Deploy. Abra o monitor a 115200 baud com final de linha Nova linha. Envie T 28 ou H 65 para ajustar as metas; elas entram em vigor na próxima janela.
Review all connections
1. Connections between "sensor" and "Arduino"
2. Connections between "pull" and "Arduino"
3. Connections between "ventilacao" and "Arduino"
4. Connections between "repouso" and "Arduino"
5. Connections between "rc" and "Arduino"
6. Connections between "calor" and "Arduino"
7. Connections between "rn" and "Arduino"
8. Connections between "nevoa" and "Arduino"
9. Connections between "fonte" and "Arduino"
10. Connections between "lcd" and "Arduino"
Deploy the firmware
#include <Arduino.h>
#include <DHT.h>
#include <LiquidCrystal_I2C.h>
#include <Wire.h>
constexpr int CALOR = 3, VENT = 4, NEVOA = 6;
int metaT = 28, metaH = 65, umidJanela = 65;
int metaJanela = 28;
constexpr float TEMP_LIMITE = 35; // Corte de software; nao substitui o termostato.
DHT sensor(2, DHT22);
bool bloqueio = false, iniciada = false;
uint32_t ultima, janela, pulsoCalor, pulsoVent, pulsoNevoa;
constexpr uint32_t JANELA = 60000, PULSO_MIN = 5000;
// Saida assinada: positivo adiciona calor/umidade; negativo pede exaustao.
struct PID {
float kp, ki, kd, soma, anterior;
bool pronto;
float atualizar(float alvo, float medida, float dt, bool ventilando) {
const float erro = alvo - medida;
const float base = kp * erro - (pronto ? kd * (medida - anterior) / dt : 0);
anterior = medida;
pronto = true;
// Limita a integral e nao acumula demanda positiva durante a exaustao.
if (ventilando && erro > 0) soma = min(soma, 0.0f);
else if ((base + soma < 100 || erro < 0) && (base + soma > -100 || erro > 0))
soma = constrain(soma + ki * erro * dt, -100.0f, 100.0f);
return constrain(base + soma, -100.0f, 100.0f);
}
};
PID temperatura{20, 0.10f, 5, 0, 0, false};
PID umidade{5, 0.05f, 2, 0, 0, false};
uint32_t pulso(float percentual) {
const uint32_t ms = (uint32_t)(percentual * JANELA / 100.0f);
if (ms < PULSO_MIN) return 0;
if (JANELA - ms < PULSO_MIN) return JANELA;
return ms;
}
LiquidCrystal_I2C lcd(0x27, 16, 2);
void linha(byte n, const char* texto) {
static char anteriorLCD[2][17] = {};
char atual[17];
snprintf(atual, sizeof atual, "%-16.16s", texto);
if (strcmp(atual, anteriorLCD[n]) == 0) return;
strcpy(anteriorLCD[n], atual);
lcd.setCursor(0, n);
lcd.print(atual);
}
// Entrada de comando por pulsos, nao alimentacao do nebulizador.
constexpr uint32_t NEVOA_PULSO_MS = 100, NEVOA_INTERVALO_MS = 150;
void comandarNevoa(bool pedido) {
static bool estado = false; // O modulo deve iniciar desligado.
static bool alvo = false, alto = false;
static byte restantes = 0;
static uint32_t marca = 0;
const uint32_t agora = millis();
if (!restantes) {
if (pedido == estado) return;
alvo = pedido;
restantes = alvo ? 1 : 3;
alto = true;
digitalWrite(NEVOA, HIGH);
marca = agora;
} else if (alto && agora - marca >= NEVOA_PULSO_MS) {
digitalWrite(NEVOA, LOW);
alto = false;
marca = agora;
} else if (!alto && agora - marca >= NEVOA_INTERVALO_MS) {
if (--restantes == 0) estado = alvo;
else {
alto = true;
digitalWrite(NEVOA, HIGH);
marca = agora;
}
}
}
void saidas(bool aquecer, bool ventilar, bool umidificar) {
digitalWrite(CALOR, aquecer);
digitalWrite(VENT, ventilar ? LOW : HIGH);
comandarNevoa(umidificar);
}
void lerSerial() {
static char linhaCmd[16];
static byte n = 0;
static bool longa = false;
for (byte i = 0; i < 32 && Serial.available(); ++i) {
const char c = Serial.read();
if (c != '\r' && c != '\n') {
if (n < sizeof linhaCmd - 1 && c >= 32 && c <= 126) linhaCmd[n++] = c;
else longa = true;
continue;
}
if (!n && !longa) continue;
linhaCmd[n] = 0;
const char tipo = linhaCmd[0];
const bool formato = !longa && n == 4 && linhaCmd[1] == ' ' &&
isDigit(linhaCmd[2]) && isDigit(linhaCmd[3]);
const int valor = formato ? 10 * (linhaCmd[2] - '0') + linhaCmd[3] - '0' : 0;
if (formato && tipo == 'T' && valor >= 20 && valor <= 32) metaT = valor;
else if (formato && tipo == 'H' && valor >= 30 && valor <= 85) metaH = valor;
else {
Serial.println(F("Use T 20..32 ou H 30..85 (ex.: T 28)"));
n = 0; longa = false;
continue;
}
Serial.print(F("Metas solicitadas: T=")); Serial.print(metaT);
Serial.print(F(" C, UR=")); Serial.print(metaH);
Serial.println(bloqueio ? F(" % (protecao ativa)") : F(" % (proxima janela)"));
n = 0; longa = false;
}
}
void setup() {
const int pinos[] = {CALOR, NEVOA};
for (int p : pinos) {
digitalWrite(p, LOW);
pinMode(p, OUTPUT);
}
Serial.begin(115200);
Serial.println(F("Metas iniciais: T 28, H 65. Envie T 20..32 ou H 30..85."));
sensor.begin();
digitalWrite(VENT, HIGH);
pinMode(VENT, OUTPUT);
Wire.begin();
Wire.setWireTimeout(25000, true);
lcd.init();
lcd.backlight();
linha(0, "Aguardando DHT22");
ultima = millis();
}
void loop() {
lerSerial();
const uint32_t agora = millis();
if (!bloqueio && agora - ultima >= 2500) {
const float dt = (agora - ultima) / 1000.0f;
ultima = agora;
const float h = sensor.readHumidity();
const float t = sensor.readTemperature();
const bool invalido = !isfinite(t) || !isfinite(h) || t < -40 || t > 80 || h < 0 || h > 100;
if (invalido || t >= TEMP_LIMITE) {
bloqueio = true;
saidas(false, true, false);
linha(0, invalido ? "Falha DHT22" : "Temperatura alta");
linha(1, "Calor bloqueado");
Serial.println(F("Protecao: calor e nevoa bloqueados ate reiniciar"));
return;
}
const bool ventilando = iniciada && agora - janela < pulsoVent;
const bool novaJanela = !iniciada || agora - janela >= JANELA;
if (novaJanela && metaT != metaJanela) {
metaJanela = metaT;
temperatura.soma = 0;
}
if (novaJanela && metaH != umidJanela) {
umidJanela = metaH;
umidade.soma = 0;
}
const float pt = temperatura.atualizar(metaJanela, t, dt, ventilando);
const float ph = umidade.atualizar(umidJanela, h, dt, ventilando);
if (novaJanela) {
janela = agora;
iniciada = true;
pulsoVent = pulso(max(0.0f, max(-pt, -ph)));
pulsoCalor = pulsoVent ? 0 : pulso(max(0.0f, pt));
pulsoNevoa = pulsoVent ? 0 : pulso(max(0.0f, ph));
}
char temp[10], umid[10], texto[24];
dtostrf(t, 4, 1, temp);
dtostrf(h, 4, 1, umid);
snprintf(texto, sizeof texto, "%s>%dC %s%%", temp, metaT, umid);
linha(0, texto);
snprintf(texto, sizeof texto, "C%3u N%3u V%3u", (unsigned)(pulsoCalor/600),
(unsigned)(pulsoNevoa/600), (unsigned)(pulsoVent/600));
linha(1, texto);
Serial.print(F("Metas ativas T=")); Serial.print(metaJanela);
Serial.print(F(" UR=")); Serial.print(umidJanela);
Serial.print(F(" PID T=")); Serial.print(pt, 1);
Serial.print(F(" PID UR=")); Serial.print(ph, 1);
Serial.print(F(" Janela %: ")); Serial.println(texto);
}
const uint32_t fase = millis() - janela;
saidas(!bloqueio && iniciada && fase < pulsoCalor,
bloqueio || (iniciada && fase < pulsoVent),
!bloqueio && iniciada && fase < pulsoNevoa);
}Remix this project
Make it yours in one click
Open a full copy of this project in your own Schematik workspace, diagram, code, parts, and assembly steps included. Swap the sensor, add features, or redesign the whole thing with AI. The author's original stays untouched.




