sensor_reading.py

Download
python 127 lines 3.5 KB
  1#!/usr/bin/env python3
  2"""
  3DHT11 Temperature and Humidity Sensor Reading
  4DHT11 μ˜¨μŠ΅λ„ μ„Όμ„œ 읽기 예제
  5
  6Hardware:
  7- DHT11 VCC  -> 3.3V (pin 1)
  8- DHT11 DATA -> GPIO4 (pin 7) with 10k pull-up resistor
  9- DHT11 GND  -> GND (pin 6)
 10
 11Install:
 12    pip install adafruit-circuitpython-dht
 13    sudo apt install libgpiod2
 14
 15Usage:
 16    python3 sensor_reading.py
 17"""
 18
 19import time
 20import json
 21from datetime import datetime
 22
 23# Try to import DHT library
 24try:
 25    import adafruit_dht
 26    import board
 27    DHT_AVAILABLE = True
 28except ImportError:
 29    DHT_AVAILABLE = False
 30    print("Warning: adafruit_dht not available. Running in simulation mode.")
 31
 32# Configuration
 33SENSOR_PIN = 4  # GPIO4
 34READ_INTERVAL = 5  # seconds
 35
 36class SensorReader:
 37    """DHT11 Sensor Reader"""
 38
 39    def __init__(self, pin: int = SENSOR_PIN):
 40        self.pin = pin
 41        self.dht = None
 42
 43        if DHT_AVAILABLE:
 44            gpio_pin = getattr(board, f"D{pin}")
 45            self.dht = adafruit_dht.DHT11(gpio_pin)
 46
 47    def read(self) -> dict:
 48        """Read temperature and humidity from sensor"""
 49        if not DHT_AVAILABLE or not self.dht:
 50            # Simulation mode
 51            import random
 52            return {
 53                "temperature": round(20 + random.uniform(0, 10), 1),
 54                "humidity": round(40 + random.uniform(0, 30), 1),
 55                "status": "simulated",
 56                "timestamp": datetime.now().isoformat()
 57            }
 58
 59        try:
 60            temperature = self.dht.temperature
 61            humidity = self.dht.humidity
 62
 63            if temperature is not None and humidity is not None:
 64                return {
 65                    "temperature": temperature,
 66                    "humidity": humidity,
 67                    "status": "ok",
 68                    "timestamp": datetime.now().isoformat()
 69                }
 70            else:
 71                return {
 72                    "status": "error",
 73                    "message": "Failed to read sensor",
 74                    "timestamp": datetime.now().isoformat()
 75                }
 76
 77        except RuntimeError as e:
 78            # DHT sensors occasionally fail to read
 79            return {
 80                "status": "error",
 81                "message": str(e),
 82                "timestamp": datetime.now().isoformat()
 83            }
 84
 85    def close(self):
 86        """Clean up sensor resources"""
 87        if self.dht:
 88            self.dht.exit()
 89
 90def main():
 91    """Main function to read and display sensor data"""
 92    print("=== DHT11 Sensor Reader ===")
 93    print(f"Reading from GPIO{SENSOR_PIN}")
 94    print(f"Interval: {READ_INTERVAL} seconds")
 95    print("Press Ctrl+C to exit\n")
 96
 97    sensor = SensorReader(SENSOR_PIN)
 98
 99    try:
100        while True:
101            data = sensor.read()
102
103            if data.get("status") == "ok" or data.get("status") == "simulated":
104                print(f"Temperature: {data['temperature']:.1f}Β°C")
105                print(f"Humidity:    {data['humidity']:.1f}%")
106                print(f"Status:      {data['status']}")
107            else:
108                print(f"Error: {data.get('message', 'Unknown error')}")
109
110            print(f"Time:        {data['timestamp']}")
111            print("-" * 40)
112
113            # Save to JSON file (optional)
114            with open("sensor_log.json", "a") as f:
115                f.write(json.dumps(data) + "\n")
116
117            time.sleep(READ_INTERVAL)
118
119    except KeyboardInterrupt:
120        print("\nStopped by user")
121    finally:
122        sensor.close()
123        print("Sensor cleanup complete")
124
125if __name__ == "__main__":
126    main()