# ex_3_3_04_moving_average.py (จำลอง: https://wokwi.com/projects/469816418886949889)
from machine import ADC, Pin
import time
soil = ADC(Pin(34)) # เซนเซอร์ความชื้นดินที่ GPIO34 (ADC1, input เท่านั้น)
soil.atten(ADC.ATTN_11DB)
DRY_CAL = 3700 # ค่าดิบเมื่อแห้งสนิท (วัดกลางอากาศ) — ต้องสอบเทียบเองทุกตัว
WET_CAL = 1250 # ค่าดิบเมื่อจุ่มน้ำ — ต้องสอบเทียบเองทุกตัว
def read_filtered(samples=12):
# อ่านซ้ำหลายครั้งแล้วเฉลี่ย เพื่อเกลี่ยยอดสัญญาณรบกวน
total = 0
for _ in range(samples):
total += soil.read()
time.sleep_ms(10) # เว้นจังหวะให้จุดสุ่มกระจาย
return total / samples
while True:
raw = soil.read()
smooth = read_filtered()
print("ดิบ: {} กรองแล้ว: {:.0f}".format(raw, smooth))
percent = (DRY_CAL - smooth) / (DRY_CAL - WET_CAL) * 100 # แห้ง=0%, เปียก=100%
percent = max(0.0, min(100.0, percent)) # จำกัดขอบเขต 0-100
print("ค่าดิบ: {} ความชื้นดิน: {:.1f}%".format(smooth, percent))
time.sleep(1)