Design of a Smart Clothesline Control System Based on STM32 and FreeRTOS

Video walkthrough:
Abstract
With the acceleration of urbanization and the increasingly fast pace of modern life, household clothes drying requires timely retraction to avoid being soaked by sudden rain. Traditional fixed clothes hangers lack environmental awareness and remote control capability, so users often fail to retract clothes in time and cannot monitor the drying state. To address these problems, this paper designs and implements an intelligent clothes-hanger control system based on an STM32 microcontroller.
The system takes STM32F103C8T6 as the main controller and adopts FreeRTOS to build a multi-task real-time scheduling framework. A DHT11 temperature-humidity sensor, a BH1750 illuminance sensor and a raindrop detection module collect environmental information. A 28BYJ-48 stepper motor driven by ULN2003A performs the extension and retraction of the drying rod, while a 0.96-inch OLED display and four push buttons form the local human-machine interface. In software, a layered architecture based on an event bus decouples the hardware driver layer from the business decision layer, so that rain-triggered retraction, automatic drying and mode switching are decided uniformly in the service layer. Meanwhile, an ESP-12F module acts as a wireless gateway, providing both web and mobile remote control and reporting environmental data to the OneNET cloud platform through MQTT. Based on a W25Q64 external Flash and a custom bootloader, OTA remote firmware upgrade for both the STM32 application and the ESP-12F firmware is realized, allowing the device to be updated in the field without disassembly.
Test results show that the system enters automatic mode immediately after power-on and can dry clothes autonomously; the response time of rain-triggered retraction is less than 2 s; motor positioning error is below 2% thanks to step accumulation and limit calibration; the end-to-end delay from a remote command to motor action is less than 500 ms; and the OTA upgrade process is complete and reliable. The system runs stably with controllable cost and has good practical value.
Keywords: STM32; FreeRTOS; intelligent clothes hanger; environmental sensing; event bus; OTA upgrade; Internet of Things
1 Introduction
1.1 Background and Motivation
Drying clothes is a frequent and necessary household chore. However, rainfall in most regions of China tends to be sudden and short-lived. If it starts raining while the user is out or asleep, clothes left on the line easily get soaked and may even need to be rewashed, wasting water and degrading the living experience. Moreover, traditional hangers offer a single function: they cannot sense illuminance, temperature or humidity, nor report the drying state while the user is away, and thus fail to meet modern expectations for smart, convenient homes.
As embedded and IoT technologies mature, combining a microcontroller, sensor network and wireless communication into a clothes hanger with environmental awareness, autonomous decision-making and remote interaction has clear practical value. The significance of this work is twofold: first, it solves the real pain point of "auto-retract when it rains, auto-dry after the rain stops" through sensing and automatic control; second, its modular, layered hardware/software design provides a reusable reference for similar small smart-home control systems.
1.2 State of the Art
Smart drying products abroad mostly appear as complete appliances integrating powered lifting, drying and sterilization; they are generally expensive, tied to vendor clouds, and offer limited secondary-development capability. In China, many microcontroller-based smart clothes hanger designs have emerged in recent years, typically using an STM32 or 8051 as the control core together with a stepper motor, raindrop sensor and Wi-Fi module.
Published designs still show several shortcomings. First, their software is mostly a single-task foreground/background structure where business logic, protocol parsing and hardware operations are entangled, hurting maintainability. Second, sensor readings are rarely debounced, so electrical noise at motor start/stop easily causes false rain detection and repeated state-machine switching. Third, remote upgrade is missing, so defects cannot be fixed or features updated without disassembly. This paper addresses precisely these issues with layered decoupling, debounce confirmation and OTA upgrade.
1.3 Main Work
This paper designs a smart clothesline control system centered on the STM32F103C8T6 with environmental awareness and autonomous decision-making, covering hardware circuit design, FreeRTOS multi-task software design, serial protocol design, local interaction design, wireless gateway and cloud platform integration, and OTA remote upgrade, verified by testing.
2 Overall System Design
2.1 Requirements
Functional requirements: ① environmental sensing — real-time temperature, humidity, illuminance and rain status; ② automatic control — retract clothes when it rains, extend them after the rain stops; ③ manual control — local button menu or remote interface; ④ mode management — automatic and manual working modes; ⑤ status display — real-time environmental data, mode and motor state; ⑥ remote interaction — web control and mobile control within the LAN; ⑦ cloud reporting of environmental data; ⑧ remote upgrade of both the main controller and the wireless module firmware.
Non-functional requirements: real time — retraction must start within 2 s after rain is confirmed; reliability — position and mode must survive power loss, and sensor readings must be interference-tolerant; maintainability — clear structure with single-responsibility modules; economy — reasonable BOM cost for small-batch production.
2.2 System Architecture
The system consists of a sensing layer, a control layer, an interaction layer and a cloud platform. The sensing layer contains a DHT11 temperature-humidity sensor, a BH1750 illuminance sensor, a raindrop detection module and a DS3231 real-time clock, converting physical quantities into digital signals. The control layer is built around the STM32F103C8T6 running FreeRTOS, responsible for sensing, automatic decision-making, motor control and protocol parsing. The interaction layer contains a 0.96-inch OLED and four buttons for local interaction, plus the ESP-12F module for web and mobile remote interaction. The cloud layer is the OneNET IoT platform, receiving device data over MQTT.
From the data-flow perspective, environmental data gathered by the control layer is used for local automatic decisions, OLED display and cloud reporting through the ESP-12F; control commands come from local buttons or remote interfaces and are uniformly decided by the service layer before the driver layer executes the motor action. This guarantees "multiple entries, single decision, single execution" consistency.
2.3 Component Selection
Components were selected under the principles of "meeting the functions, controllable cost, easy development":
| Category | Part | Key specs | Rationale |
|---|---|---|---|
| Main MCU | STM32F103C8T6 | ARM Cortex-M3, 72 MHz, 64 KB Flash, 20 KB RAM | Ample resources, rich peripherals, mature ecosystem, low cost |
| Wi-Fi module | ESP-12F | ESP8266EX, 4 MB Flash, 802.11 b/g/n | Small, cheap, runs TCP/MQTT and OTA |
| External storage | W25Q64 | 64 Mbit (8 MB), SPI | Chinese font storage and OTA firmware buffer |
| Display | 0.96" OLED | SSD1306, 128×64, I2C | Self-emissive, low power, simple interface |
| Buttons | TS665CJ | 4 pcs, with hardware debounce caps | Crisp feel, reliable |
| Temp/humidity | DHT11 | 0–50 ℃/±2 ℃, 20–90 %RH/±5 %RH | Single-wire, low cost |
| Illuminance | BH1750 | 0–65535 lx, I2C | Digital output, calibration-free, wide range |
| Rain detection | Rain module | DO digital output, adjustable sensitivity | Fast response, direct EXTI trigger |
| Real-time clock | DS3231 | ±2 ppm, TCXO, battery backup | High accuracy, keeps time through power loss |
| Stepper motor | 28BYJ-48 | 5 V, gear ratio 1:64, step angle 5.625°/64 | Sufficient torque, cheap |
| Motor driver | ULN2003A | 7-channel Darlington array, flyback diodes | Drives coils directly, minimal externals |
| LDO | AMS1117-3.3 | 5 V→3.3 V, 1 A max | Stable, low ripple, cost-effective |
3 Hardware Design
The complete schematic is shown below; each functional block is described in the following sections.

3.1 Minimum System and Power
The main controller is the STM32F103C8T6 — an ARM Cortex-M3 running at up to 72 MHz with 64 KB Flash and 20 KB SRAM, providing enough GPIOs, timers, USARTs, SPI and NVIC channels for this system. The minimum system covers power, clock, reset and debug: a 5 V input is regulated to 3.3 V by the AMS1117-3.3; the clock uses the internal 8 MHz RC oscillator PLL-multiplied to 72 MHz, with an external 32.768 kHz crystal for the RTC; reset is RC-based; debugging and flashing use SWD.
Power enters through a 5 V DC jack and a SPDT switch, then splits into two rails: one drives the stepper motor and ULN2003A directly, the other is stepped down to 3.3 V for the STM32, ESP-12F, W25Q64, OLED and sensors. Because the ESP-12F can draw peak currents above 500 mA when transmitting, a large filter capacitor is placed at the 3.3 V output to suppress transient droop and prevent module resets.
3.2 Stepper Motor Drive
The actuator is a 28BYJ-48 five-wire four-phase geared stepper with a built-in 1:64 gearbox and an effective step angle of about 5.625°/64; driven in the four-phase eight-beat sequence it provides sufficient torque and positioning accuracy for slow reciprocating motion.
Since MCU GPIOs cannot drive motor coils directly, the ULN2003A Darlington array is used: PB12–PB15 output the phase sequence into ULN2003A inputs 1B–4B, whose outputs drive the four coils. Its built-in flyback diodes safely dissipate the reverse EMF when coils switch off, protecting both the driver and the MCU. The motor runs on 5 V, isolated from the 3.3 V logic rail except for a common ground.
Instead of external limit switches, the system records the motor position by step accumulation and determines the travel range through one-time calibration of the "origin" and "extended" positions, reducing mechanical complexity and avoiding the reliability issues of limit switches outdoors.
3.3 Environmental Sensor Circuits
Temperature and humidity use a DHT11 on a single-wire bus with DATA on PA8. Its timing is strict, so the driver uses microsecond-level delays for the start signal, response and 40-bit data transfer, with checksum validation before updating values.
Illuminance uses a BH1750 over software I2C with SCL/SDA on PA0/PA1. Compared with an LDR, the BH1750 outputs digital values with no calibration needed and covers 0–65535 lx.
Rain detection uses a rain module whose digital output DO connects to PA2. The comparator output falls from high to low when water is detected, and this edge triggers an external interrupt for immediate capture; a potentiometer adjusts sensitivity for different mounting positions. Note that the raw output is susceptible to electrical noise from motor start/stop, so it must be paired with the software debounce algorithm described in Section 4.4.
The time base is a DS3231 high-accuracy RTC with a temperature-compensated crystal (±2 ppm) and a coin-cell backup that keeps time through power loss. It connects over software I2C (SDA on PB0, SCL on PB1) and provides accurate date/time for the web and mobile interfaces.
3.4 Human-Machine Interface
Local interaction consists of a 0.96-inch OLED and four buttons. The OLED uses an SSD1306 (128×64, I2C) with SCL/SDA on PB8/PB9; its self-emissive panel stays readable in the dark with low power, suitable for always-on display.
Four TS665CJ tactile switches connect to PB4–PB7 as pulled-up inputs, each with a 47 nF capacitor for hardware debounce. They map to "confirm, back, up, down" and drive a menu state machine: confirm on the home page opens the main menu; up/down move the cursor; confirm executes the highlighted item; back returns to the previous level.
3.5 Wireless and Storage
The ESP-12F (ESP8266EX, 4 MB Flash, 802.11 b/g/n) runs TCP, HTTP and MQTT stacks, serving both as a LAN gateway with a built-in web UI and as a cloud client. It links to the MCU over USART1: PA9 (TX) to module RX and PA10 (RX) to module TX, at 115200 bit/s, 8 data bits, no parity, 1 stop bit.
External storage is an 8 MB W25Q64 SPI Flash on SPI1 (NSS/SCK/MISO/MOSI on PA4–PA7). It serves two purposes: storing the Chinese font bitmaps for the OLED, and buffering OTA firmware images. During an upgrade the ESP-12F transfers the new firmware to the W25Q64 in packets; after verification the bootloader moves it into the application area, so a power loss mid-upgrade cannot corrupt the running program.
3.6 Pin Assignment
| Pin | Function | Peripheral / mode | Purpose |
|---|---|---|---|
| PA0 / PA1 | BH1750 SCL / SDA | Open-drain (software I2C) | Illuminance |
| PA2 | Rain module DO | Pull-up input + EXTI | Rain detection |
| PA4–PA7 | SPI1 NSS/SCK/MISO/MOSI | Push-pull / AF push-pull / pull-up input | W25Q64 storage |
| PA8 | DHT11 DATA | Open-drain (single-wire) | Temp/humidity |
| PA9 / PA10 | USART1 TX / RX | AF push-pull / AF floating input | Link to ESP-12F |
| PB0 / PB1 | DS3231 SDA / SCL | Open-drain (software I2C) | Real-time clock |
| PB4–PB7 | Buttons 1–4 | Pull-up input + EXTI | Local interaction |
| PB8 / PB9 | OLED SCL / SDA | Open-drain (software I2C) | Display |
| PB10 / PB11 | USART3 TX / RX | AF push-pull / AF floating input | Debug serial |
| PB12–PB15 | ULN2003A 1B–4B | Push-pull output | Stepper phase control |
The PCB is shown below.

4 Software Design
4.1 Architecture and Task Partitioning
The software uses a layered architecture — user layer, service layer and hardware layer — connected by the event bus. The user layer (main.c) only creates FreeRTOS tasks and wires up event subscriptions, containing no business logic. The service layer handles decisions, state orchestration and priority arbitration; for example, ClotheslineService uniformly decides "whether to retract and when to extend". The hardware layer reads/writes peripherals, executes actions and reports raw events — Motor drives the phase sequence, Rain samples the level, Menu renders the UI. Dependencies are strictly one-way: user → service → hardware, and the hardware layer must never call upwards.
Under this architecture the system is partitioned into four FreeRTOS tasks:
| Task | Priority | Stack | Responsibility |
|---|---|---|---|
| vSensorTask | 3 | 256 words | Environmental sampling and display refresh; first-run initialization of auto mode |
| vUartTask | 4 | 256 words | Serial protocol parsing and command dispatch to service modules |
| vServiceTickTask | 4 | 128 words | Drives ClotheslineService_Process() every 50 ms for decisions and actions |
| vIapTask | 1 | 256 words | Upgrade-flag detection and OTA flow |
vServiceTickTask acts as the system's "metronome": it drives the service layer at a fixed period so that all decisions advance on a unified time base, instead of executing state checks inside interrupts or other tasks — guaranteeing consistent, predictable behavior. The main program flow is shown below.

4.2 Event Bus and Layered Decoupling
To remove the coupling caused by "many entries calling the execution layer directly" in traditional foreground/background designs, the system introduces a lightweight event bus, AppEvent. Its publish/subscribe mechanism has three elements: publishers only state facts (e.g. the motor publishes APP_EVENT_MOTOR_STOPPED when it stops); subscriptions are registered centrally in main.c so the system's dependencies are visible at a glance; each module implements its own handler (ClotheslineService_OnMotorStopped updates business state, Menu_OnMotorStopped refreshes the UI).
The benefits: one event can be consumed by multiple modules independently; a new subscriber needs just one registration line in main.c with no changes to business modules; drivers no longer care who consumes their events, so responsibility boundaries stay clean.
This also fixes "responsibility inversion". Before refactoring, the UI module decided the mode switch directly in button callbacks while the service layer acted as a mere executor. Afterwards, the UI only reports the fact "the user pressed the auto button", and the service layer decides whether to switch to auto or manual based on the current mode. The rule of thumb: if UI code contains "if the current state is X then do Y" logic, responsibility has been inverted.
4.3 Motor Control and Position Management
Motor stepping is timer-interrupt driven. TIM2 fires roughly every 4 ms; in the ISR the four-phase eight-beat sequence is output on PB12–PB15, one phase step per tick. Motor motion is defined by target steps and direction: after Motor_Run(steps, dir) sets the target and enables the timer, each ISR tick decrements the remaining count; at zero the output stops, the timer is disabled, and APP_EVENT_MOTOR_STOPPED is published.
Position is tracked by step accumulation: a motorPosition variable records the offset from the origin, calibrated against two values — motorZeroSteps (origin) and motorMaxSteps (extended position). In the calibration UI the user nudges the motor forward/backward, then records the origin and the extended position; both values are saved to Flash and survive power loss. Range checks use these values — e.g. no retraction when motorPosition ≤ 0 and no extension when motorPosition ≥ motorMaxSteps — preventing stalls without limit switches.
All motor actions are non-blocking. Tasks never busy-wait for the motor to stop; instead a "flag + periodic check" pattern is used: to preempt a running motion, Motor_Stop() halts it and sets a pending flag, and the service-layer tick issues the next action only after observing "motor stopped" — avoiding long CPU occupation that would hurt other tasks' responsiveness. The motor control flow is shown below.

4.4 Environmental Sensing and Auto-Dry Decision
Rain sensing combines "interrupt trigger + periodic polling". An edge on the rain module's DO pin fires an external interrupt whose ISR only releases a semaphore and makes no business decisions; the service tick task tries to take the semaphore each cycle and, if no event arrived, actively reads the level every 500 ms as a fallback, so state changes are still detected even if an interrupt is lost.
To suppress electrical noise, a consecutive-consistency debounce algorithm is used: a rain-state change (dry→rain or rain→dry) is confirmed only after three consecutive identical readings, taking about 1.5 s. This effectively eliminates false rain detections caused by level jitter at motor start/stop and prevents the state machine from oscillating on transient noise. The debounced state isRaining is the single source of truth for business decisions; the service layer never reads the raw interface. The rain detection and debounce flow is shown below.

The auto-dry decision is unified in ClotheslineService_Process(): ① when rain is detected while clothes are extended, Motor_RetractForRain() retracts them; ② when rain has stopped, the system is in auto mode and clothes are retracted, a delay timer starts (5 s by default, configurable over serial); when it expires, Motor_DryOutForAuto() extends the clothes — the delay prevents oscillation from short showers; ③ if a pending user command (pendingUserOpen / pendingUserClose) exists, it is executed accordingly.
An important rule governs action sources versus modes: sensor-triggered automatic actions (rain retraction, post-rain extension) never change the working mode; only user commands issued in manual mode switch the system to manual mode. This constraint prevents the defect where an automatic rain retraction would silently switch the system to manual and block the automatic post-rain extension.
Power-up behavior in auto mode is also handled specially: the device boots into auto mode by default, and the service layer reuses the same "post-rain delay" window — if it is not raining and the clothes are retracted, it waits for the confirmation window and then extends them automatically, so the user needs no interaction after power-on. The auto-dry decision flow is shown below.

4.5 Serial Protocol
The STM32 and ESP-12F speak a custom text-line protocol. Every downstream command starts with "@" and ends with CRLF, e.g. @CLOSE, @AUTO, @MOTOR_QUERY; the STM32 receives it with a state machine inside the USART interrupt, buffers characters after the start marker, and sets a completion flag on CRLF for vUartTask to dispatch through a command routing table. Upstream responses carry no "@" prefix and use "key:value" form for easy parsing. Being plain text, the protocol is readable and can be exercised directly with a serial terminal. The main commands:
| Command | Direction | Purpose | Response |
|---|---|---|---|
| @CLOSE | ESP → STM32 | Manual retract | Motor action |
| @OPEN | ESP → STM32 | Manual extend (blocked while raining) | Motor action |
| @AUTO / @MANUAL | ESP → STM32 | Switch auto / manual mode | MODE:AUTO or MODE:MANUAL |
| @MOTOR_QUERY | ESP → STM32 | Query motor state | MOTOR_STATUS:zero=,max=,pos=,mode= |
| @MOTOR_FWD:n / REV:n | ESP → STM32 | Move n steps forward / back (calibration) | none |
| @MOTOR_SAVE_ZERO | ESP → STM32 | Record current position as origin | MOTOR_SAVED:0 |
| @MOTOR_SAVE_MAX | ESP → STM32 | Record current position as extended | MOTOR_SAVED:n |
| @TIME_QUERY / TIME_SET:… | ESP → STM32 | Read / set DS3231 time | TIME_NOW:… or TIME_SET_OK |
| @MQTT_ON / @MQTT_OFF | ESP → STM32 | Enable / disable sensor reporting | SENSOR_REPORT:ON / OFF |
| @STM32_UPGRADE | ESP → STM32 | Start OTA upgrade | OTA:PROGRESS etc. |
Upstream, once reporting is enabled the STM32 sends a SENSOR:temperature,humidity,light,rain line every 500 ms, and during upgrades OTA:PROGRESS|percent and OTA:DONE|result status lines. The ESP-12F parses these into its internal state for web queries and cloud reporting. The serial dispatch flow is shown below.

4.6 OLED Menu and Buttons
Local interaction uses a menu state machine with four display modes: home, menu, action and upgrade. The home page shows temperature, humidity, light condition, rain status and the working mode. The menu lists three items — "retract, extend, auto" — with a ">" cursor. The action mode shows Working, Retracting or Extending prompts (or Rain! Wait when an extension is blocked by rain). The upgrade mode shows progress percentage.
Button handling happens in external-interrupt callbacks, which only navigate the UI and report commands — no business decisions. For example, confirm on the home page opens the menu; confirm in the menu reports the highlighted command to the service layer (retract / extend / auto); if an extension is requested while raining, the UI shows a prompt and returns to the menu after a delay; confirm in action mode stops the motor and returns home. Back returns to the previous level (stopping the motor first in action mode). Up/down only work in the menu to move the cursor.
UI refresh is event-driven: when the motor stops, Motor publishes MOTOR_STOPPED and the UI returns home and refreshes in the callback; mode changes publish MODE_CHANGED and the UI updates the mode field. The UI therefore never polls hardware, reducing coupling and CPU load. The button and menu flow is shown below.

4.7 OTA Remote Upgrade
For maintainability, the system implements dual-channel OTA for both the main-controller application and the wireless-module firmware. Overall scheme: the ESP-12F acts as the network-side agent that downloads firmware, while the STM32's bootloader writes it into the application area; the two cooperate over the serial link.
Main-controller upgrade: after the user triggers it from the web or mobile UI, the ESP-12F downloads the new application over HTTP, then sends @STM32_UPGRADE to start the flow. The STM32 first performs a safety action — retracting the clothes if extended — then enters upgrade state and receives the firmware from the ESP-12F via YMODEM, packet by packet into the W25Q64 buffer partition, reporting progress in real time. Once all data is received and flagged, the bootloader verifies integrity on the next boot, moves the image into the application area and jumps to it.
The wireless-module upgrade is simpler: the ESP-12F downloads its own new firmware into an internal OTA partition and switches to it after reboot, reporting progress to the STM32 so the OLED can display it.
The "buffer first, move later" two-phase strategy means that even if power or the network drops mid-upgrade, the application area remains intact and the device reboots normally — no bricking — greatly improving upgrade reliability. The OTA flow is shown below.

4.8 Wireless Gateway, Web UI and Cloud
The ESP-12F plays two roles: wireless gateway and host of the web UI. As the gateway it converts the STM32 serial protocol into network services: a lightweight HTTP server serves the control page to LAN devices, and an MQTT client connects to the OneNET platform, packaging environmental data as OneJSON every 15 s and receiving cloud commands.
The web page draws data from three sources: local ESP-12F configuration (OneNET parameters, MQTT switch) from local storage; live hardware state (motor calibration and position) queried from the STM32 over serial; and clock data read by the STM32 from the DS3231. These are fetched asynchronously in a defined order after page load to avoid jank from slow serial round-trips.
The web UI offers: control buttons (retract / extend / auto); calibration controls (nudge forward/backward, record origin and extended position); RTC sync and setting; the sensor-reporting switch; upgrade entries for both firmwares; and firmware/network info. When a button is clicked, the browser or app sends an HTTP request to the ESP-12F, which converts it into a serial command for the STM32; the service layer decides and drives the motor or updates state, returning the result over serial to the ESP-12F and finally to the UI. The mobile app reuses the same HTTP interface and therefore behaves identically to the web page.
To cut latency, the ESP-12F polls motor state from the STM32 every 10 s in the background and caches it, so page queries return instantly without a serial round-trip; after page initialization, MQTT status, motor state and RTC time are fetched at staggered 1 s / 1.5 s / 2 s offsets so the critical information appears first.
With this design the system realizes a three-level "device—gateway—controller" path for data and commands: sensing flows up through the gateway to the web, app and cloud; commands flow down from the web, app or local buttons to the controller, closing the interaction loop.
5 Testing and Results
5.1 Environment and Method
Testing took place indoors at room temperature with a 5 V/2 A DC supply, ST-Link programmer, USB-TTL adapter, serial terminal, and a PC and phone on the same LAN. The device under test was the assembled prototype. Functional tests verified local button interaction, automatic drying, remote control, data reporting and remote upgrade item by item; performance tests focused on rain response time, motor positioning error, end-to-end command latency and long-run stability.
5.2 Functional Tests
| Test item | Procedure | Result |
|---|---|---|
| Home display | Observe home page after power-on | Temp/humidity, light, rain and mode all shown correctly |
| Button menu | Confirm opens menu, up/down move cursor, confirm executes | Cursor correct; all items execute as required |
| Manual retract / extend | Select from menu, observe motor | Motor runs in the requested direction; returns home when done |
| Entering auto mode | Select auto, observe | Auto-extends when dry and at origin; stays retracted while raining |
| Rain auto-retract | Wet the rain sensor, observe motor | Clothes auto-retract; OLED still shows auto mode |
| Post-rain auto-extend | Dry the sensor, observe | Motor auto-extends after 5 s delay; mode unchanged |
| Web remote control | Click retract / extend / auto on the web page | Motor acts as commanded; UI state syncs |
| Mobile control | Same operations in the app | Behavior identical to web |
| Data reporting | Enable reporting, watch the cloud | Environmental data reported periodically, continuous curves |
| Main-controller OTA | Trigger upgrade from web, wait | Progress reported; new firmware runs after reboot |
| Wi-Fi module OTA | Trigger ESP-12F upgrade from web | Self-downloads and switches firmware; OLED shows progress |
All functional items passed; local interaction, automatic decisions and remote control behave consistently, with no state conflicts or failures.
5.3 Performance Tests
| Metric | Method | Result |
|---|---|---|
| Rain response time | Time from confirmed rain to motor start | avg 1.6 s (incl. 1.5 s debounce), max 1.8 s |
| Motor positioning error | Compare target vs. measured position after repeated travel | max ≈ 1.6%, below 2% |
| End-to-end command latency | Time from web click to motor start | avg 320 ms, max 480 ms |
| Button response latency | Time from press to UI switch | below 100 ms |
| Long-run stability | 72-hour continuous run, watch for resets and false actions | no abnormal reset, no rain false positives |
| Standby power | Measure total current with motor idle and display on | ≈ 95 mA at 5 V |
The data shows: the 1.5 s debounce slightly increases rain response time but drastically cuts false detections in the rain — a reasonable trade-off given environmental interference and mechanical wear; motor positioning error stems mainly from stepper accumulation and gear backlash, and 1.6% is fully acceptable for drying, further reducible via calibration; end-to-end latency is dominated by the Wi-Fi link and serial polling, and 320 ms average feels instant in remote control.
5.4 Analysis
Overall the system met its design goals in three respects. First, control consistency: the same action issued from local buttons, the web UI or the app is governed by the same service-layer rules, with identical behavior and no "same operation, different result" issues. Second, interference immunity: sensor debouncing, non-blocking actions and event-driven UI refresh keep the system stable through motor start/stop and sensor jitter — 72 hours of continuous running without abnormal resets. Third, maintainability: both firmware levels support remote upgrade, so field devices can be updated without disassembly.
Remaining improvement areas found during testing: the DHT11's accuracy and response are limited and lag in high humidity; motor current is not sampled, so stall detection is missing; and the cloud merely relays data without history-based intelligence. These are left for future work.
6 Conclusion and Outlook
6.1 Summary
Addressing the practical problem of clothes being soaked by sudden rain, this paper designed and implemented an STM32-based smart clothesline control system, covering the full process from requirements and architecture to hardware, software and testing. The main contributions:
First, a complete hardware platform: the STM32F103C8T6 with DHT11, BH1750, the rain module and DS3231 for sensing; the 28BYJ-48 stepper and ULN2003A for actuation; OLED and four buttons for interaction; and W25Q64 plus ESP-12F for storage and wireless — with a full pin-assignment plan.
Second, a FreeRTOS software architecture: user–service–hardware layers decoupled by an event bus, with four single-responsibility tasks, thoroughly separating business decisions from hardware drivers and greatly improving readability and maintainability.
Third, solutions to key engineering problems: a consecutive-consistency debounce against motor-noise rain false positives; a flag-plus-polling non-blocking pattern against blocking waits; a "UI reports facts, service layer decides" principle against responsibility inversion; and a "buffer first, move later" two-phase OTA strategy for upgrade reliability.
Fourth, complete remote interaction and cloud integration: web and mobile control through the ESP-12F with asynchronous multi-source page data and background state caching; environmental reporting to OneNET over MQTT — closing the IoT loop end to end. Tests show the system is feature-complete and stable, meeting design targets.
6.2 Future Work
Possible improvements: higher sensing accuracy (e.g. SHT30, plus wind speed and UV index for richer drying decisions); actuation safety (motor current sampling for stall/overcurrent protection, limit switches or an encoder for closed-loop positioning); deeper data analysis (predictive "retract before rain" using accumulated cloud data and weather forecasts); and productization (enclosure, waterproofing, power design, possibly solar charging).
In summary, the system achieves the core functions of smart drying at low cost, and its layered decoupled architecture and two-phase upgrade strategy offer a useful reference for similar small smart-home control systems.
References
- Liu Huoliang, Yang Sen. STM32 Library Development in Practice [M]. 2nd ed. Beijing: China Machine Press, 2017.
- Zhang Yang, Liu Jun, Yan Song. Playing with STM32 [M]. 2nd ed. Beijing: Beihang University Press, 2015.
- He Bin, Zhang Yanhui. STM32 Embedded System Development [M]. Beijing: Publishing House of Electronics Industry, 2018.
- Zhou Hangci. Common Algorithms in Embedded Software Design [M]. Beijing: Beihang University Press, 2010.
- Wang Wei, Li Qiang. Design of an STM32-based smart home control system [J]. Electronic Design Engineering, 2020, 28(15): 110-114.
- Chen Ming, Zhao Lei. Design of an IoT-based smart clothes hanger system [J]. IoT Technology, 2021, 11(4): 45-48.
- Li Ning. Design of a wireless data transmission system based on ESP8266 [J]. MCU & Embedded System Applications, 2019, 19(8): 60-63.
- Sun Xiaoming. Research on multi-task scheduling optimization for FreeRTOS-based embedded systems [J]. Computer Engineering and Design, 2021, 42(6): 1620-1626.
- STMicroelectronics. RM0008 Reference Manual: STM32F101xx, STM32F102xx, STM32F103xx, STM32F105xx and STM32F107xx Advanced ARM-based 32-bit MCUs [Z]. 2021.
- Espressif Systems. ESP8266EX Datasheet [Z]. 2020.
- Maxim Integrated. DS3231 Extremely Accurate I2C-Integrated RTC/TCXO/Crystal Datasheet [Z]. 2015.
- Winbond Electronics. W25Q64FV 3V 64M-Bit Serial Flash Memory with Dual/Quad SPI Datasheet [Z]. 2017.
- China Mobile IoT Co., Ltd. OneNET Platform Documentation [EB/OL]. https://open.iot.10086.cn, 2023.
- Analog Devices. ULN2003A High-Voltage High-Current Darlington Transistor Arrays Datasheet [Z]. 2018.
- FreeRTOS. FreeRTOS Kernel Reference Manual [EB/OL]. https://www.freertos.org, 2023.