用python实现温湿度传感器消除数据抖动
时间: 2023-09-25 11:09:21 浏览: 77
以下是一个简单的Python程序,可以消除温湿度传感器的数据抖动:
```python
import Adafruit_DHT
import time
DHT_SENSOR = Adafruit_DHT.DHT22
DHT_PIN = 4
def read_dht():
while True:
humidity, temperature = Adafruit_DHT.read_retry(DHT_SENSOR, DHT_PIN)
if humidity is not None and temperature is not None:
return humidity, temperature
time.sleep(0.1)
def filter_data(humidity, temperature):
# 使用滑动平均滤波器消除数据抖动
window_size = 5
humidity_samples = [humidity] * window_size
temperature_samples = [temperature] * window_size
while True:
humidity_samples.pop(0)
temperature_samples.pop(0)
humidity_samples.append(humidity)
temperature_samples.append(temperature)
filtered_humidity = sum(humidity_samples) / window_size
filtered_temperature = sum(temperature_samples) / window_size
return filtered_humidity, filtered_temperature
while True:
humidity, temperature = read_dht()
filtered_humidity, filtered_temperature = filter_data(humidity, temperature)
print(f"Humidity: {humidity:.2f}%, Temperature: {temperature:.2f}°C")
print(f"Filtered Humidity: {filtered_humidity:.2f}%, Filtered Temperature: {filtered_temperature:.2f}°C")
```
该程序使用Adafruit_DHT库读取DHT22传感器的温度和湿度数据,并使用滑动平均滤波器来消除数据抖动。滑动平均滤波器是一种简单的滤波器,它计算最近一些样本的平均值,并将其用作过滤器的输出。在这个例子中,我们使用一个窗口大小为5的滑动平均滤波器,即使用最近的5个样本来计算平均值。您可以根据需要调整窗口大小。
阅读全文