Designing an STM32-Based Smart Humidity Control System with IoT Integration
This article presents the design of a smart indoor humidity control system built around a 32-bit ARM Cortex-M3 microcontroller and connected through an IoT architecture. It covers the four-layer system structure, hardware selection for sensing, actuation and protection, a dual-mode control strategy with three-state humidification, cloud data exchange, local and remote user interfaces, testing results, and future extensions. Readers will find reusable engineering patterns for environmental monitoring and control projects.
1. Introduction: Where Conventional Humidifiers Fall Short
Humidity is a key parameter in indoor environment management because it directly affects comfort, item preservation, and equipment reliability. Air that is too dry causes static buildup, brittle paper, and dried mucous membranes, while air that is too humid promotes mold growth and metal corrosion. Most humidifiers on the market offer only manual on/off control: they cannot sense the current humidity, cannot adjust humidification intensity against a configured threshold, and require frequent human intervention. Some units also lack over-temperature and fault protection, which becomes a safety concern during long continuous operation.
Combining an embedded controller, multiple sensor types, wireless communication, and mobile interaction makes it possible to build a complete “sense - decide - actuate - connect” loop. This article uses a 32-bit ARM Cortex-M3 core MCU as the control core to design a humidity regulation system that spans the sensing, control, network, and application layers of the IoT model, providing a reusable engineering pattern for similar environmental monitoring and control projects.
2. Overall System Architecture
The system follows the classic four-layer IoT model, from top to bottom:
- Sensing layer: collects environmental parameters, including humidity and temperature, and supplies the inputs for later decisions.
- Control layer: built around the MCU, it handles data filtering, threshold comparison, mode switching, actuator driving, and protection decisions.
- Network layer: a wireless communication module uploads local data to a cloud platform and receives downstream commands, forming a bidirectional data channel.
- Application layer: local human-machine interaction (display and buttons) plus remote mobile interaction, supporting parameter configuration and status monitoring.
The benefit of this layering is clear separation of responsibilities: replacing any single layer, such as swapping the sensor model or the communication module, does not force a redesign of the overall logic, which keeps the system easy to extend.
3. Hardware Selection and Circuit Design
3.1 Main Control Unit
A common 32-bit ARM core MCU serves as the main controller. It integrates multiple general-purpose I/O ports, timers, UARTs, and analog-to-digital conversion peripherals. Its clock frequency and memory resources are sufficient for concurrent tasks such as sensor polling, display refresh, and communication protocol parsing, while the mature toolchain and controllable cost make it a practical choice.
3.2 Temperature and Humidity Acquisition
Humidity is captured with a single-bus digital temperature and humidity sensor. Signal conditioning and digitization are already handled internally, so the MCU needs only one data line to read and write, with strict timing requirements but minimal wiring. Temperature is captured separately by another single-bus digital temperature sensor, providing an independent measurement source and a redundant input for over-temperature protection. The dual temperature sources add value in two ways: they allow cross-validation so that drift in a single sensor does not cause a false judgment, and they keep temperature protection functional if the humidity sensor fails.
The core of the single-bus read timing is to strictly observe the reset pulse, the presence pulse, and the bit read/write windows. A skeleton implementation:
/* Skeleton implementation for reading one raw frame from a single-bus sensor */uint8_t Sensor_ReadByte(void){uint8_t i, dat = 0;for (i = 0; i < 8; i++) {dat <<= 1;if (Sensor_ReadBit()) dat |= 1; /* Read window for each bit */}return dat;}int16_t Temp_ReadRaw(void){Sensor_Reset(); /* Reset and wait for presence pulse */Sensor_WriteByte(0xCC); /* Skip address matching */Sensor_WriteByte(0x44); /* Start temperature conversion */Delay_ms(750); /* Wait for conversion to complete */Sensor_Reset();Sensor_WriteByte(0xCC);Sensor_WriteByte(0xBE); /* Read scratchpad */int16_t raw = (int16_t)((Sensor_ReadByte() | (Sensor_ReadByte() << 8)));return raw; /* Low bits are fractional; scale by resolution */}
3.3 Actuation and Protection
The humidification actuator is an atomizing plate, driven through a driver circuit whose on/off state and duty cycle are controlled by a timer output on the MCU. The protection unit consists of over-temperature decision logic (in software) and an audible-visual alarm channel made up of a buzzer and an indicator LED. It is worth stressing that the atomizing plate is an inductive, high-frequency driven load, so the driver loop must provide proper power isolation and grounding treatment to avoid interfering with the MCU and with sensor sampling.
3.4 Human-Machine Interface
Local interaction consists of an OLED display and several independent buttons. The display shows humidity, temperature, mode, thresholds, and device status; the buttons handle mode switching, threshold increment/decrement, and manual start/stop. The display is typically driven by a software-emulated serial interface, and refresh uses a “partial area update” strategy to reduce bus occupancy.
4. Control Logic: Dual Modes and Three-State Humidification
The system supports two operating modes: automatic and manual.
In automatic mode, the MCU periodically reads the humidity value and compares it against the configured lower and upper limits to form closed-loop control with a dead band, producing three humidification states:
- Measured humidity below the lower limit: continuous humidification, atomizing plate at full speed.
- Measured humidity between the limits: pulsed humidification, operating intermittently by duty cycle to suppress overshoot.
- Measured humidity above the upper limit: humidification stops and the system enters monitoring standby.
Introducing the dead band and the pulsing interval is a key design choice. It avoids frequent start/stop cycling near the threshold, which would shorten actuator life and cause humidity oscillation. Example logic:
void AutoHumidityControl(int16_t hum, int16_t low, int16_t high){if (hum < low) {Mist_SetDuty(100); /* Continuous humidification */State = DEV_ON;} else if (hum <= high) {Mist_SetDuty(PULSE_DUTY); /* Pulsed humidification */State = DEV_PULSE;} else {Mist_SetDuty(0); /* Stop humidification */State = DEV_OFF;}}
In manual mode, the user controls the humidifier start/stop directly. The system only performs protection checks and status reporting, without running the humidity closed loop. The two modes are switched by a button or a remote command, and the actuator state is forcibly reset at the moment of switching to prevent output jitter caused by a mode jump.
The temperature protection mechanism exists independently of the mode and has the highest priority: when either temperature source exceeds the safety limit, the atomizing plate is switched off immediately, the audible-visual alarm is triggered, and an anomaly event is reported. The alarm is cleared only after the temperature falls back below the recovery limit and stays there for a period of time, which avoids repeated tripping around the critical point.
5. Network Layer and Cloud Data Exchange
The wireless communication module connects to the MCU over UART. The MCU drives it with a “command + data” approach to join the wireless network and establish a long-lived connection to the cloud. The data model is best split into three topic-style message types:
- Telemetry uplink: humidity, temperature, device status, and operating mode, reported periodically.
- Threshold configuration downlink: humidity limits, mode switching, and manual start/stop commands.
- Event uplink: over-temperature alarms, sensor faults, and communication reconnect notices.
Uplink messages should use a compact key-value or binary structure, for example:
/* Sketch of telemetry uplink payload construction */char payload[128];snprintf(payload, sizeof(payload),"{\"h\":%d,\"t\":%d,\"mode\":%d,\"state\":%d}",hum, temp_x10, work_mode, dev_state);Uplink_Send(payload);
Three classes of faults must be handled in practice. First, reconnection after a link drop should use exponential backoff. Second, downlink commands need idempotency and length validation so that a partial packet is not misparsed. Third, communication blocking must not affect the main control loop; a non-blocking design based on a “send queue plus timed window” is recommended, so that the real-time local closed loop always takes priority over connectivity features.
6. Application Layer: Local and Remote Channels
The local channel uses the display and buttons as entry points and emphasizes “fully usable without a network”: all local functions remain complete when the network is down. The remote channel uses a mobile application as the entry point and provides real-time viewing of environmental parameters, threshold modification, mode switching, humidifier start/stop, and anomaly alarm push notifications. Both channels share the same configuration data structure; after either side makes a change, the MCU arbitrates and writes it back, avoiding configuration conflicts between the two ends.
7. Testing and Results
Testing was carried out in two steps, at unit level and at full-system level. Unit-level testing verified the stability of sensor readings, the completeness of display refresh, and connectivity of the communication link. Full-system testing covered three scenarios:
- Humidity control accuracy: in a closed space, observe whether humidity converges and stays within the limit range, and record overshoot amplitude and oscillation period.
- Response latency: the time from a button press or a remote command to actuator movement.
- Protection reliability: deliberately raise the temperature above the limit, confirm that the atomizing plate disconnects immediately and the alarm triggers, and confirm correct reset after the temperature falls back.
The results show stable humidity acquisition, three-state regulation logic that matches the design intent, timely local and remote control response, and reliable over-temperature protection, with the system able to run stably over the long term.
8. Extensions and Engineering Recommendations
- Multi-node networking: abstract this design as a terminal node and pair it with a gateway for multi-point monitoring.
- Data persistence and visualization: use general cloud capabilities (such as time-series data storage, logging services, and monitoring and alerting) to provide historical curves and threshold alarms.
- Algorithm upgrade: replace on/off control with a dead band by incremental PID or fuzzy control to further suppress overshoot.
- Low-power optimization: for battery-powered scenarios, adopt sleep and event-driven wake-up mechanisms.
- Security hardening: add integrity checks to the communication link to prevent command tampering.
9. Conclusion
This design achieves local closed-loop humidity regulation and remote manageability with low-cost hardware, and it adds the temperature safety protection that conventional humidifiers lack. It spans the full four-layer IoT architecture and offers direct practical value for understanding the “sense - control - connect - apply” development workflow. It suits settings that require stable humidity, such as homes, archive rooms, and small laboratories, and it can be migrated quickly to other environmental parameter control projects through modular substitution.
