RTCの時刻表示がいつの間にか30分遅れる問題(備忘録)
RTCの時刻表示がいつの間にか30分遅れる問題(備忘録)
This project implements a temperature monitoring device using STM32miniShield, integrating DS18B20 sensors for temperature acquisition and RTC for timekeeping. To maintain accurate time, the system synchronizes with an NTP server via Ethernet using the W5500 controller.
However, during long-term operation, the system clock consistently lagged by approximately 30 minutes. This was not random drift but a deterministic, repeatable error. The issue stemmed from a structural flaw in how time was managed within the system.
■ Architecture
The system is composed of three main functional domains:
- Data Acquisition: DS18B20 temperature sensors (1-Wire interface)
- Time Management: Timer interrupt + RTC
- Network Synchronization: W5500-based NTP client
The key interaction lies between the timer-driven time flow, RTC storage, and periodic NTP synchronization.
■ Technical Features
1. Timer-Based Time Flow
- Time progression is generated via a 500ms interrupt
- A software counter (
OperatingTime) accumulates elapsed time
2. NTP Synchronization via W5500
- UDP-based communication with an NTP server
- Periodic RTC updates using external time reference
3. Digital Temperature Sensing
- DS18B20 sensors enable reliable digital temperature acquisition
- Supports multi-sensor configuration on a single bus
4. Critical Design Flaw
- Timer interval changed from 1 second to 0.5 seconds
- Time calculation logic was not updated accordingly
■ WIZnet Insight
The system leverages the W5500 Ethernet controller, which provides hardware TCP/IP offloading. This significantly reduces MCU overhead and ensures stable UDP communication for NTP synchronization. For long-running embedded systems, such reliability is essential.
However, this case demonstrates a crucial point:
Even with a highly reliable network time source, incorrect internal time logic can invalidate the entire system’s accuracy.
WIZnet provides precise time data—but it is the system designer’s responsibility to handle it correctly.
■ Root Cause Analysis
The issue originates from the following line of code:
if(!(OperatingTime % 3600))This was intended to trigger NTP synchronization every hour. However:
OperatingTimeincrements every 0.5 seconds- Therefore:
- 3600 × 0.5 seconds = 1800 seconds = 30 minutes
Actual Behavior
- NTP synchronization occurs every 30 minutes instead of 1 hour
- RTC is updated more frequently than intended
- Internal time flow conflicts with external updates
- Result: consistent 30-minute offset
■ Solution
The fix is straightforward:
if(!(OperatingTime % 7200))- 7200 × 0.5 seconds = 3600 seconds = 1 hour
Key Design Lessons
- Always align timer tick units with time-based logic
- Clearly define time units across the system (tick vs second)
- Re-evaluate all dependent logic when modifying interrupt intervals
■ Business Value
1. Industrial IoT Reliability
Accurate timestamps are critical for logging, analytics, and system coordination—not just sensor accuracy.
2. Reduced Maintenance Risk
Time-related bugs often surface after long operation periods. Early design validation prevents costly field issues.
3. Scalable Network Synchronization
Using W5500 enables stable and scalable NTP-based synchronization across distributed devices.
4. Practical Engineering Insight
This case serves as a real-world example of how small timing mismatches can lead to significant system-level failures.
■ FAQ
Q1. Why can frequent NTP synchronization cause issues?
Excessive synchronization can conflict with internal time progression, leading to instability or offsets.
Q2. How should Timer and RTC roles be defined?
The Timer generates time flow, while the RTC maintains absolute time. They must be clearly decoupled.
Q3. Is W5500 reliable for NTP synchronization?
Yes. It provides stable hardware-based TCP/IP processing. Most issues arise from application-level logic, not the network layer.
Q4. What is the best way to maintain accurate time in embedded systems?
A combination of RTC, periodic NTP synchronization, and drift compensation is recommended.
Q5. Can this issue occur on other MCUs or RTOS systems?
Yes. Any system using timer-based time tracking without proper unit consistency can encounter similar problems.
본 프로젝트는 STM32miniShield 기반의 온도 모니터링 장치로, DS18B20 센서를 통해 온도를 측정하고, RTC를 활용하여 시간 정보를 함께 표시하는 구조입니다. 또한 Ethernet 인터페이스(W5500)를 통해 NTP 서버와 동기화하여 시간 정확도를 유지하도록 설계되었습니다.
그러나 장시간 동작 중, 내부 시계가 약 30분씩 느려지는 현상이 발생했습니다. 이는 단순한 RTC 오차가 아니라, 일정한 패턴을 가진 구조적 오류였습니다. 본 분석은 해당 문제의 원인과 해결 과정을 통해 임베디드 시간 설계의 핵심 포인트를 정리합니다.
■ 아키텍처
시스템은 온도 측정, 시간 관리, 네트워크 동기화의 세 축으로 구성됩니다.
- STM32 MCU: 전체 제어 및 데이터 처리
- DS18B20: 1-Wire 기반 온도 센서
- Timer 인터럽트: 시간 흐름 생성 (0.5초 단위)
- RTC: 기준 시간 유지
- W5500 Ethernet: NTP 서버와 시간 동기화
핵심은 Timer 기반 시간 흐름과 RTC, 그리고 NTP 동기화가 상호작용하는 구조입니다.
■ 기술 특징
1. Timer 기반 시간 관리
- 500ms 인터럽트 기반으로 OperatingTime 증가
- 소프트웨어적으로 시간 흐름 생성
2. NTP 동기화 구조
- W5500 기반 UDP 통신으로 NTP 서버 접근
- 일정 주기로 RTC 갱신
3. DS18B20 활용
- 디지털 방식으로 온도 측정
- 복수 센서 연결 가능
4. 문제 발생 지점
Timer 주기 변경 (1초 → 0.5초)
그러나 시간 계산 로직은 기존 그대로 유지
■ WIZnet Insight
본 시스템은 W5500 Ethernet 컨트롤러를 기반으로 NTP 동기화를 구현하고 있습니다. W5500은 하드웨어 TCP/IP 오프로딩을 제공하여 MCU의 부하를 줄이고, 안정적인 UDP 기반 NTP 통신을 가능하게 합니다. 특히 장시간 동작하는 임베디드 장치에서 네트워크 스택의 안정성은 매우 중요하며, W5500은 이러한 요구를 효과적으로 충족합니다.
그러나 본 사례에서 중요한 점은, 네트워크 계층이 아무리 정확하더라도 시스템 내부의 시간 처리 로직이 잘못 설계되면 전체 시간 정확성이 무너질 수 있다는 점입니다. 즉, WIZnet 기반 네트워크는 “정확한 시간 소스”를 제공하지만, 이를 어떻게 사용하는지는 전적으로 시스템 설계에 달려 있습니다.
■ 기술적 문제 분석
문제의 핵심은 다음 한 줄에서 시작됩니다.
if(!(OperatingTime % 3600))이 코드는 “1시간마다 NTP 동기화”를 의도했지만, 실제로는 다음과 같은 계산이 적용됩니다.
- OperatingTime 증가 주기: 0.5초
- 3600 × 0.5초 = 1800초 = 30분
즉,
1시간이 아니라 30분마다 NTP 동기화가 실행됨
이로 인해 다음 문제가 발생합니다:
- RTC가 과도하게 업데이트됨
- 내부 시간 흐름과 외부 시간 기준이 충돌
- 일정한 30분 오차 발생
■ 해결 방법
문제는 매우 단순하게 수정됩니다.
if(!(OperatingTime % 7200))- 7200 × 0.5초 = 3600초 = 1시간
그러나 중요한 것은 단순한 수정이 아니라 설계 원칙입니다:
- Timer 주기 변경 시 전체 시간 로직 재검토 필요
- 시간 단위(초, tick 등)를 명확히 정의
- NTP 동기화 주기를 신중히 설정
■ 비즈니스 가치
1. 산업용 IoT 장치 설계 관점
- 센서 정확도뿐 아니라 시간 정확도도 핵심 품질 요소
- 로그, 이벤트, 데이터 분석의 신뢰성 확보 가능
2. 유지보수 비용 절감
- 시간 오류는 장기간 누적 시 심각한 문제 발생
- 초기 설계 단계에서 예방 가능
3. 네트워크 기반 장치 확장성
- W5500 기반으로 안정적인 시간 동기화 구조 구축 가능
- 다수 노드 간 시간 정합성 확보
4. 교육 및 개발 레퍼런스
- Timer, RTC, NTP 간 관계를 이해할 수 있는 실전 사례
- 임베디드 설계 오류 유형 학습 가능
■ FAQ
Q1. 왜 NTP를 자주 동기화하면 문제가 발생하나요?
과도한 동기화는 내부 시간 흐름과 충돌을 일으킬 수 있으며, 오히려 시간 왜곡을 초래할 수 있습니다.
Q2. Timer와 RTC는 어떻게 역할을 나눠야 하나요?
Timer는 시간 흐름 생성, RTC는 기준 시간 유지 역할로 분리해야 합니다.
Q3. W5500 기반 NTP는 신뢰할 수 있나요?
네트워크 측면에서는 매우 안정적이며, 문제는 대부분 시스템 내부 시간 처리 로직에서 발생합니다.
Q4. 임베디드 시스템에서 시간 정확도를 높이는 방법은 무엇인가요?
RTC + 주기적 NTP 동기화 + Drift 보정 구조를 사용하는 것이 이상적입니다.
Q5. 이 문제는 다른 MCU에서도 발생할 수 있나요?
네. Timer 기반 시간 관리 구조를 사용하는 모든 시스템에서 동일하게 발생할 수 있습니다.

