환경 센서 활용 — BME280 온습압·SHT3x·BMP180 비교
#한 줄 요약
“센서 raw value는 그냥 ADC count입니다. 계수와 compensation 공식이 datasheet에 있습니다.” 그걸 따라 적용하면 °C / %RH / hPa가 됩니다.
#어떤 상황에서 쓰나
날씨 스테이션, 실내 공기 monitor, drone barometric altimeter, refrigeration logger, 산업 공정 monitor — 온도·습도·기압 측정은 임베디드의 기본 임무. BME280 (Bosch) 한 chip이 셋을 모두 — I2C/SPI 둘 다 지원. SHT3x (Sensirion)는 온습도만, 더 정확한 ±0.1°C / ±1.5%RH.
이 글은 BME280 SPI driver와 SHT3x I2C driver를 모두 작성합니다.
#핵심 개념
#BME280 chip
Bosch BME280: Temperature: -40 ~ +85°C, ±1°C Humidity: 0~100%RH, ±3% Pressure: 300~1100 hPa, ±1 hPa
I2C address: 0x76 (SDO=GND) or 0x77 (SDO=VDD)SPI: mode 0 or mode 3, max 10 MHz#Register map (요약)
| Address | 이름 | 역할 |
|---|---|---|
| 0xD0 | id | chip ID = 0x60 |
| 0xE0 | reset | 0xB6 write → soft reset |
| 0xF2 | ctrl_hum | humidity oversampling |
| 0xF4 | ctrl_meas | temp/pressure oversampling, mode |
| 0xF5 | config | standby, filter |
| 0xF7-FE | data | raw temp, pressure, humidity (총 8 byte) |
| 0x88-A1 | calib1 | T, P calibration |
| 0xE1-F0 | calib2 | H calibration |
#Compensation 공식
raw ADC → 실제 값 변환은 Bosch가 제공하는 fixed-point 또는 float 공식. datasheet appendix에 있습니다.
// 단순화된 float 공식 (실제는 더 복잡)double t_fine;double compensate_temp(int32_t adc_T, const calib_t *c) { double var1 = (((double)adc_T) / 16384.0 - ((double)c->T1) / 1024.0) * c->T2; double var2 = ((((double)adc_T) / 131072.0 - ((double)c->T1) / 8192.0) * (((double)adc_T) / 131072.0 - ((double)c->T1) / 8192.0)) * c->T3; t_fine = var1 + var2; return t_fine / 5120.0; // °C}손으로 안 짭니다. Bosch BME280 driver (GitHub BoschSensortec/BME280_driver)를 그대로 사용.
#SHT3x — CRC가 들어간 I2C
SHT3x는 모든 measurement에 CRC-8 byte. error detection.
Read response: [MSB] [LSB] [CRC]
CRC-8 polynomial: 0x31init: 0xFFCRC가 안 맞으면 재시도. I2C noise 환경에서 중요.
#코드 예제
#1. BME280 SPI driver
#include "bme280_defs.h"
// CS=PA4#define CS_LOW() GPIOA->BSRR = (1u << (4+16))#define CS_HIGH() GPIOA->BSRR = (1u << 4)
static uint8_t bme_read(uint8_t reg) { uint8_t v; CS_LOW(); spi_xfer8(reg | 0x80); // read = bit7 set v = spi_xfer8(0xFF); while (SPI1->SR & SPI_SR_BSY); CS_HIGH(); return v;}
static void bme_read_n(uint8_t reg, uint8_t *buf, uint16_t n) { CS_LOW(); spi_xfer8(reg | 0x80); for (uint16_t i = 0; i < n; i++) buf[i] = spi_xfer8(0xFF); while (SPI1->SR & SPI_SR_BSY); CS_HIGH();}
static void bme_write(uint8_t reg, uint8_t val) { CS_LOW(); spi_xfer8(reg & 0x7F); // write = bit7 clear spi_xfer8(val); while (SPI1->SR & SPI_SR_BSY); CS_HIGH();}
// Calibrationtypedef struct { uint16_t T1; int16_t T2, T3; uint16_t P1; int16_t P2, P3, P4, P5, P6, P7, P8, P9; uint8_t H1; int16_t H2; uint8_t H3; int16_t H4, H5; int8_t H6;} bme_calib_t;
static bme_calib_t cal;
void bme_init(void) { if (bme_read(0xD0) != 0x60) { printf("BME280 not found!\n"); return; }
// Read calibration uint8_t buf[26]; bme_read_n(0x88, buf, 26); cal.T1 = buf[0] | (buf[1] << 8); cal.T2 = buf[2] | (buf[3] << 8); cal.T3 = buf[4] | (buf[5] << 8); cal.P1 = buf[6] | (buf[7] << 8); // ... P2-P9, H1 cal.H1 = buf[25];
bme_read_n(0xE1, buf, 7); cal.H2 = buf[0] | (buf[1] << 8); cal.H3 = buf[2]; cal.H4 = (buf[3] << 4) | (buf[4] & 0xF); cal.H5 = (buf[5] << 4) | (buf[4] >> 4); cal.H6 = buf[6];
// Configuration: humidity ×1, temp ×1, pressure ×1, normal mode bme_write(0xF2, 0x01); // ctrl_hum bme_write(0xF4, (1<<5)|(1<<2)|3); // ctrl_meas: T×1, P×1, normal bme_write(0xF5, (4<<5)|(0<<2)); // config: 500 ms standby, no filter}
void bme_read_measurements(float *temp_c, float *pres_hpa, float *rh) { uint8_t buf[8]; bme_read_n(0xF7, buf, 8);
int32_t adc_P = ((int32_t)buf[0] << 12) | ((int32_t)buf[1] << 4) | (buf[2] >> 4); int32_t adc_T = ((int32_t)buf[3] << 12) | ((int32_t)buf[4] << 4) | (buf[5] >> 4); int32_t adc_H = ((int32_t)buf[6] << 8) | buf[7];
*temp_c = compensate_temp(adc_T, &cal); *pres_hpa = compensate_pres(adc_P, &cal) / 100.0; *rh = compensate_humid(adc_H, &cal);}(compensate_* 함수는 Bosch reference에서 그대로 가져옴.)
#2. SHT3x I2C driver
#define SHT3X_ADDR 0x44 // 또는 0x45
static uint8_t crc8(const uint8_t *data, size_t n) { uint8_t crc = 0xFF; for (size_t i = 0; i < n; i++) { crc ^= data[i]; for (int j = 0; j < 8; j++) { crc = (crc & 0x80) ? (crc << 1) ^ 0x31 : (crc << 1); } } return crc;}
int sht3x_read(float *temp_c, float *rh) { // Trigger single shot, high repeatability uint8_t cmd[] = {0x24, 0x00}; i2c_write(SHT3X_ADDR, cmd, 2);
delay_ms(20); // high repeatability: max 15.5 ms
uint8_t buf[6]; i2c_read(SHT3X_ADDR, buf, 6);
// Check CRC if (crc8(&buf[0], 2) != buf[2] || crc8(&buf[3], 2) != buf[5]) return -1;
uint16_t t_raw = (buf[0] << 8) | buf[1]; uint16_t h_raw = (buf[3] << 8) | buf[4];
*temp_c = -45.0f + 175.0f * t_raw / 65535.0f; *rh = 100.0f * h_raw / 65535.0f; return 0;}SHT3x는 공식이 단순 — 곱셈·덧셈만. BME280과 대조적.
#3. 평균과 outlier 필터
센서는 noise spike가 있습니다. moving average + median filter가 표준.
#define BUF 16static float temp_buf[BUF];static int buf_idx;
float temp_smooth(float new) { temp_buf[buf_idx++] = new; if (buf_idx >= BUF) buf_idx = 0;
// sort copy, take median float sorted[BUF]; memcpy(sorted, temp_buf, sizeof(sorted)); for (int i = 1; i < BUF; i++) { float k = sorted[i]; int j = i - 1; while (j >= 0 && sorted[j] > k) { sorted[j+1] = sorted[j]; j--; } sorted[j+1] = k; } return sorted[BUF/2];}#측정 / 동작 확인
값이 합리적인 범위(20-25°C, 40-60%RH, 1000-1020 hPa)에서 정상 변동해야 합니다.
정상 측정:
- T = 23.4 °C
- P = 1013.2 hPa
- RH = 47.3 %
이상 측정:
- T = -40.0 °C (sensor 미연결 또는 spi 오류)
- T = +85.0 °C (calibration 잘못)
- P = 0 (i2c address 잘못)
검증: 손으로 sensor를 잡으면 온도가 1-2°C 올라야 함. 입김을 불면 RH가 80%+로 튐. 안 변하면 sensor가 동작 안 함.
#자주 보는 함정
⚠️ Calibration data를 읽지 않음
raw ADC만 출력해서 나쁜 값. 항상 calibration 먼저 읽고 compensation 적용.
⚠️ SHT3x command 후 대기 안 함
15 ms 안 기다리고 read하면 이전 measurement 또는 NACK. delay 필수.
⚠️ I2C pull-up 약함
400 kHz fast mode에 internal pull-up만 쓰면 rise time 부족. 4.7 kΩ external.
⚠️ Self-heating
센서 자체 발열로 측정 오차. continuous mode + high oversampling이면 +0.5°C 오차. intermittent mode (1초 한 번 측정 후 sleep) 권장.
⚠️ Calibration overflow
float이 아닌 int 공식에서 overflow. Bosch reference의 int32_t·int64_t 형식 정확히 따라야.
⚠️ CRC를 무시
I2C error가 가끔 발생. CRC 안 보면 spike value가 정상으로 보고됨.
#정리
- BME280 = T + P + H 통합, I2C/SPI 둘 다, calibration + compensation 공식 필수.
- SHT3x = T + H, CRC-8 byte가 모든 measurement에 포함.
- Bosch driver를 그대로 사용, compensation 공식 직접 안 짬.
- moving average + median filter로 spike 제거.
- 외부 pull-up 4.7 kΩ, 400 kHz fast mode 안전.
다음 편은 **IMU (가속도·자이로·지자기)**입니다. MPU6050, BMI270 driver와 sensor fusion 입력 단계를 다룹니다.
#관련 항목
- 4-08: SPI 드라이버
- 4-09: I2C 드라이버
- 5-09: IMU 센서
- 9-05: PID 제어 기본
Modern Embedded Recipes · 57 of 152
- 1Modern Embedded Recipes — 모던 임베디드 실전 레시피 시리즈 소개
- 2디지털 신호 기초 — Voltage Level·Edge·Setup/Hold 분석
- 3임베디드 클럭과 타이밍 — Skew·Jitter·PLL·MMCM 분석
- 4GPIO 내부 구조 분해 — Push-Pull·Open-Drain·Schmitt Trigger
- 5UART 하드웨어 동작 분석 — Baud Rate·Framing·FIFO
- 6SPI 하드웨어 분석 — Clock Mode·MOSI/MISO·Chip Select
- 7I2C 하드웨어 분석 — Open-Drain·Clock Stretching·Arbitration
- 8ADC 동작 원리 — SAR·Sigma-Delta·Pipelined 비교
- 9DAC 동작 원리 — R-2R Ladder·Sigma-Delta·Settling Time
- 10PWM 신호 생성 분석 — Duty·Frequency·Dead Time·Center-Aligned
- 11CAN 버스 전기적 특성 — Differential·Termination·Dominant/Recessive
- 12RS-485·RS-422 차동 신호 분석 — Termination·Biasing·Topology
- 13LVDS 차동 신호 분석 — Common-Mode·Impedance·Eye Pattern
- 14ARM Cortex-M 시리즈 비교 — M0·M3·M4·M7·M33·M55 분석
- 15ARM Cortex-A 시리즈 비교 — A53·A55·A72·A78·X1 분석
- 16ARM 레지스터 구조 분석 — R0~R15·CPSR·SPSR·Banked Registers
- 17Cortex-M 예외 처리 — Vector Table·NVIC·Tail-Chaining 추적
- 18ARM 메모리 맵 분석 — Normal·Device·Strongly-Ordered Region
- 19ARM L1·L2 캐시 분석 — Set Associative·Inclusive·Maintenance
- 20ARM MPU 활용 — Region·Attribute·Privilege Separation
- 21ARM MMU 기초 분석 — Translation Table·TLB·ASID
- 22ARM TrustZone-M 기초 — Secure/Non-Secure·NSC·MPC
- 23ARM Memory Barrier 실전 — DMB·DSB·ISB·DMA·MMIO
- 24임베디드 크로스 컴파일러 분석 — GCC·Clang·Sysroot 구성
- 25C 컴파일 4단계 — Preprocess·Compile·Assemble·Link 추적
- 26ELF 파일 구조 분석 — Section·Segment·Symbol Table·DWARF
- 27링커 스크립트 기초 — SECTIONS·MEMORY·entry point
- 28링커 스크립트 고급 — Overlay·BSS·init_array·LMA/VMA
- 29임베디드 스타트업 코드 분석 — Reset_Handler·Vector Table·SystemInit
- 30C 런타임 crt0 분석 — Stack·BSS Zero·Data Copy·atexit
- 31임베디드 메모리 레이아웃 — .text·.rodata·.data·.bss·.heap·.stack
- 32임베디드 컴파일러 최적화 분석 — -O0~-O3·-Os·-LTO 비교
- 33Map 파일 분석 — Symbol·Section·Size 추적으로 코드 크기 진단
- 34Make·CMake 크로스 컴파일 — Toolchain File·Sysroot 통합
- 35임베디드 Bootloader 체인 — BootROM·SPL·U-Boot·Kernel·Secure Boot
- 36첫 bare-metal 프로그램 작성 — Linker·Startup·main의 최소 구성
- 37MMIO 레지스터 직접 접근 — volatile·Memory Map·Aliasing 분석
- 38GPIO 드라이버 직접 구현 — STM32 HAL 없이 레지스터로
- 39임베디드 클럭 설정 분석 — HSE·PLL·SYSCLK·AHB/APB 분주
- 40Cortex-M 인터럽트 핸들링 — NVIC·Priority·Vector·EXTI
- 41SysTick 타이머 활용 — 24-bit Counter·1ms Tick·delay 구현
- 42UART 드라이버 구현 — polling·interrupt·DMA 3가지 방식 비교
- 43SPI 드라이버 구현 — Master·Slave·CRC·DMA
- 44I2C 드라이버 구현 — Master·7-bit/10-bit·Clock Stretching 처리
- 45임베디드 DMA 기초 — Memory-to-Memory·Peripheral·Circular Mode
- 46저전력 모드 분석 — Sleep·Stop·Standby·Wake-up Source
- 47IWDG·WWDG 워치독 구현 — Independent vs Window 비교
- 48임베디드 Flash 프로그래밍 — Erase·Program·Read While Write
- 49DDR 초기화 실패 진단 — Timing·Calibration·Walking Bit Test
- 50PWM 출력 실전 — LED 밝기·모터 속도 제어
- 51DC 모터 제어 — H-Bridge·PWM Duty·Encoder Feedback
- 52스테퍼 모터 제어 — Full Step·Half Step·Microstepping
- 53서보 모터 제어 — PWM 1ms~2ms·Closed Loop·PID
- 54Character LCD 제어 — HD44780·4-bit Mode·Custom Char
- 55SPI OLED 제어 — SSD1306·Frame Buffer·Page 단위 갱신
- 56TFT 디스플레이 구동 — RGB565·FSMC·LTDC·DMA2D
- 57환경 센서 활용 — BME280 온습압·SHT3x·BMP180 비교
- 58IMU 센서 활용 — MPU6050·LSM6DSO·Sensor Fusion
- 59CAN 통신 구현 — bxCAN·Filter·Mailbox·CAN-FD
- 60USB Device 기초 — Descriptor·Enumeration·Endpoint·HID/CDC
- 61Ethernet MAC+PHY 통합 — RMII·lwIP·DMA Descriptor
- 62SD Card + FatFs 구현 — SPI/SDIO 모드·CSD/CID·Wear
- 63RTC 활용 — Calendar·Alarm·Wake-up Timer·Backup Domain
- 64RTOS 도입 결정 분석 — Super Loop vs RTOS 트레이드오프
- 65RTOS Task 설계 패턴 — 우선순위·스택·State Machine
- 66RTOS Scheduler 동작 분석 — Tick·Context Switch·Yield
- 67RTOS Semaphore 활용 — Binary·Counting·ISR Give
- 68RTOS Mutex 활용 — Recursive·Priority Inheritance 적용
- 69RTOS Queue 활용 — By-Value·By-Reference·Timeout 패턴
- 70RTOS Event Group 활용 — Bit Wait·Sync·Notify
- 71RTOS Software Timer 활용 — One-shot·Auto-reload·Daemon Task
- 72ISR-Safe API 설계 — Reentrant·Atomic·Defer 패턴
- 73Priority Inversion 진단·예방 — Mars Pathfinder Lesson 추적
- 74Timer Wheel 분석 — Hashed·Hierarchical·O(1) Tick
- 75RTOS 디버깅 기법 — Tracealyzer·SystemView·Stack 추적
- 76임베디드 Linux 부팅 흐름 분석 — BootROM·U-Boot·Kernel·init
- 77U-Boot 활용 — bootcmd·env·tftp·boot.scr 분석
- 78Device Tree 실전 — DTS·DTB·Overlay·Phandle 추적
- 79Device Tree Overlay 적용 — Runtime fragment·dtoverlay
- 80임베디드 커널 빌드 — defconfig·menuconfig·Image·zImage
- 81커널 모듈 기초 — init/exit·Parameter·KBuild·DKMS
- 82캐릭터 드라이버 작성 — file_operations·cdev·register_chrdev
- 83Platform 드라이버 작성 — probe·remove·of_match·DT 바인딩
- 84mmap 4가지 모드 — Anonymous·File·Shared·Huge Page
- 85epoll 실전 — LT·ET·ONESHOT·EXCLUSIVE 비교
- 86UIO·VFIO 분석 — User-Space Driver와 IOMMU 격리
- 87sysfs·configfs 활용 — kobject 기반 User 인터페이스
- 88IRQ Affinity 튜닝 — smp_affinity·isolcpus·irqbalance
- 89루트 파일시스템 구축 — Buildroot 기초·Package·Toolchain
- 90임베디드 동적 메모리 — malloc 위험·결정성·대안 분석
- 91메모리 정렬과 패딩 분석 — Natural·Strict Alignment·Trap
- 92Cache Line Alignment — alignas·Padding·SoA 적용
- 93DMA-Friendly Allocator — dma_alloc_coherent·IOMMU·Pool
- 94Zero-Copy Pipeline — DMA-BUF·sendfile·io_uring·splice
- 95NUMA Memory Topology — numactl·numa_alloc·HBM 적용
- 96SIMD 활용 분석 — Intrinsics·Auto-Vectorization·OpenMP SIMD
- 97ARM NEON 심화 — Matrix Multiply·FFT·Image Filter 적용
- 98임베디드 스택 분석 — high-water·overflow 탐지
- 99임베디드 코드 크기 최적화 — -Os·LTO·Section Garbage Collection
- 100임베디드 전력 최적화 — Sleep Mode·Clock Gating·DVFS
- 101WCET 분석 기법 — Static·Measurement·Hybrid 방법론
- 102Lock-Free Ring Buffer 구현 — SPSC·Power-of-2·Memory Order
- 103Wait-Free Signaling — Atomic Flag·Sequence·Latest-Value
- 104RCU (Read-Copy-Update) 기초 — Quiescent State·Grace Period
- 105Hazard Pointer 분석 — Lock-Free Memory Reclamation
- 106Compare-And-Swap 패턴 — Stack·Counter·Linked List 적용
- 107Atomic Operation 비용 분석 — Fence·Cache Line·Contention
- 108Spinlock vs Mutex 결정 가이드 — Context Switch·Hold Time
- 109ABA 문제 회피 — Tagged Pointer·Hazard·Generation Counter
- 110False Sharing 해결 — Cache Line Padding·SoA 적용
- 111MPMC Queue 구현 — Multi-producer Multi-consumer Lock-Free
- 112임베디드 디버깅 마인드셋 — 가설·격리·재현·이분탐색
- 113JTAG·SWD 안 붙을 때 — 핀·전압·속도·세션 진단
- 114GDB 원격 디버깅 — OpenOCD·J-Link·target remote 구성
- 115Cortex-M 하드폴트 분석 — Stacked Frame·CFSR 읽기
- 116UART 안 찍힐 때 — Bare-metal 체크리스트
- 117임베디드 부팅 실패 진단 — 단계별 Isolation
- 118인터럽트 누락·중복 진단 — Priority·Pending·Re-entry 추적
- 119메모리 오버플로우·오염 진단 — Canary·MPU·Pattern 분석
- 120타이밍·Race 진단 — Heisenbug 잡는 법
- 121통신 프로토콜 분석 — Logic Analyzer와 Protocol Decoder
- 122임베디드 로깅 시스템 설계 — 레벨·버퍼·SWO·Deferred
- 123임베디드 포스트모템 분석 — Core Dump와 Field Crash
- 124FPGA 기초 분석 — LUT·FF·BRAM·DSP 자원 구조
- 125Vivado 사용법 — Project·Constraint·Synth·Impl·Bitstream
- 126PCIe BAR 매핑 분석 — Config Space·Enumeration·MMIO 접근
- 127AXI 인터페이스 — AXI4·AXI4-Lite·AXI-Stream 비교
- 128Zynq PS-PL 통신 — GP·HP·ACP 인터페이스 선택
- 129Mailbox Protocol 분석 — Host와 Accelerator를 잇는 Doorbell
- 130Command Queue·Submission Queue — NVMe·XDMA 공통 패턴
- 131DMA Completion 메커니즘 — Interrupt·Polling·Completion Ring
- 132PCIe Streaming 분석 — BAR Type·MSI-X·Kernel Bypass
- 133Vitis HLS 분석 — Pragma·Pipeline II·Dataflow 실전 감각
- 134HLS 최적화 기법 — Pipeline·Unroll·Partition·Dataflow
- 135Vitis AI 분석 — DPU·xmodel·VART
- 136OpenCL on FPGA — Kernel·Channel·Burst Memory 분석
- 137Intel Quartus 사용법 — Platform Designer·Nios II·HLS
- 138Edge Inference 분석 — Cloud vs Edge·Latency·Privacy
- 139NPU 아키텍처 분석 — Ethos·Hexagon·Systolic Array 비교
- 140딥러닝 Quantization 분석 — PTQ·QAT·INT8·INT4·Calibration
- 141TensorRT 분석 — ONNX→Engine·FP16·INT8·DLA·Multi-Stream
- 142TFLite Micro 분석 — Op Resolver·Tensor Arena·Cortex-M
- 143ONNX Runtime 분석 — Execution Provider와 Cross-Platform 배포
- 144Edge Thermal Management — Throttling·DVFS·Fan Curve·Sustained
- 145NVIDIA Jetson 분석 — Nano·Xavier·Orin·Thor·JetPack·DLA·VPI
- 146Zero-Copy Camera Pipeline — V4L2·DMA-BUF·GPU Import·NPU 직결
- 147온디바이스 LLM 추론 — llama.cpp·GGUF·MLX·KV Cache·NPU Backend
- 148Cortex-M33 TF-M·TrustZone — Secure Firmware·PSA·MCUboot
- 149Matter·Thread 분석 — IoT 통합 표준·Commissioning·Multi-Fabric
- 150PCIe → CXL 진화 — 같은 PHY 위 cache-coherent 프로토콜 추가
- 151QEMU CXL Type 3 디바이스 에뮬레이션 — 노트북에서 CXL 개발 환경 구축
- 152Linux CXL 드라이버 분석 — cxl_pci·cxl_core·region·DAX