Reading Sensor Data with Python

Loading

Reading sensor data with Python is essential for IoT, automation, and embedded systems. Python allows easy integration with sensors like temperature, humidity, motion, and pressure using libraries like GPIO, serial communication (UART, I2C, SPI), and MQTT.


1. Types of Sensors You Can Read with Python

Python can interface with various sensors:

Sensor TypeExample SensorsCommunication Protocol
TemperatureDHT11, DS18B20GPIO, I2C, One-Wire
HumidityDHT22, AM2302GPIO, I2C
Motion (PIR)HC-SR501GPIO
Ultrasonic DistanceHC-SR04GPIO
PressureBMP180, BMP280I2C, SPI
Light IntensityLDR (Photoresistor)Analog (ADC)
Gas SensorsMQ-2, MQ-135Analog (ADC)

2. Setting Up Python for Sensor Data Reading

Before reading sensor data, install required libraries:

pip install RPi.GPIO Adafruit_DHT smbus2 pyserial
  • RPi.GPIO – For Raspberry Pi GPIO pins
  • Adafruit_DHT – For DHT sensors
  • smbus2 – For I2C communication
  • pyserial – For Serial (UART) communication

3. Reading Data from Sensors

3.1 Reading Temperature & Humidity Data (DHT11/DHT22)

DHT sensors use a single-wire protocol and are widely used for temperature and humidity monitoring.

Wiring:

  • VCC → 3.3V/5V
  • GND → GND
  • Data → GPIO Pin

Python Code to Read from DHT11/DHT22:

import Adafruit_DHT

sensor = Adafruit_DHT.DHT11 # Use DHT22 for better accuracy
pin = 4 # GPIO pin connected to the sensor

humidity, temperature = Adafruit_DHT.read_retry(sensor, pin)

if humidity is not None and temperature is not None:
print(f"Temp: {temperature:.1f}°C Humidity: {humidity:.1f}%")
else:
print("Failed to read from sensor")

Reads temperature & humidity from the DHT11/DHT22 sensor.


3.2 Reading Distance Using Ultrasonic Sensor (HC-SR04)

HC-SR04 uses sound waves to measure distance.

Wiring:

  • VCC → 5V
  • GND → GND
  • TRIG → GPIO 23
  • ECHO → GPIO 24

Python Code for HC-SR04:

import RPi.GPIO as GPIO
import time

GPIO.setmode(GPIO.BCM)
TRIG = 23
ECHO = 24

GPIO.setup(TRIG, GPIO.OUT)
GPIO.setup(ECHO, GPIO.IN)

def get_distance():
GPIO.output(TRIG, True)
time.sleep(0.00001)
GPIO.output(TRIG, False)

while GPIO.input(ECHO) == 0:
start_time = time.time()

while GPIO.input(ECHO) == 1:
end_time = time.time()

duration = end_time - start_time
distance = (duration * 34300) / 2
return round(distance, 2)

try:
while True:
print(f"Distance: {get_distance()} cm")
time.sleep(1)
except KeyboardInterrupt:
GPIO.cleanup()

Measures distance in centimeters.


3.3 Reading Analog Data (Light Sensor – LDR) Using ADC

Raspberry Pi doesn’t have an ADC, so use an MCP3008 ADC to read analog data.

Python Code for Reading Light Intensity:

import spidev

spi = spidev.SpiDev()
spi.open(0, 0)
spi.max_speed_hz = 1350000

def read_adc(channel):
adc = spi.xfer2([1, (8 + channel) << 4, 0])
data = ((adc[1] & 3) << 8) + adc[2]
return data

while True:
light_level = read_adc(0)
print(f"Light Intensity: {light_level}")

Reads light intensity from an LDR sensor.


3.4 Reading Serial Data from Arduino Sensors (UART Communication)

Many sensors connect to Arduino, then send data to Python via Serial (USB/UART).

Python Code to Read Serial Data:

import serial

ser = serial.Serial('/dev/ttyUSB0', 9600, timeout=1)

while True:
data = ser.readline().decode().strip()
if data:
print(f"Sensor Data: {data}")

Reads sensor data from Arduino via USB/UART.


4. Storing Sensor Data in a Database

After reading sensor data, store it in SQLite:

Python Code to Store Data in SQLite:

import sqlite3

conn = sqlite3.connect('sensor_data.db')
cursor = conn.cursor()

cursor.execute('''CREATE TABLE IF NOT EXISTS sensor_data
(id INTEGER PRIMARY KEY, temperature REAL, humidity REAL, timestamp DATETIME DEFAULT CURRENT_TIMESTAMP)''')

def insert_data(temp, hum):
cursor.execute("INSERT INTO sensor_data (temperature, humidity) VALUES (?, ?)", (temp, hum))
conn.commit()

# Example: Storing sensor data
insert_data(25.5, 60.2)

Saves temperature & humidity readings in an SQLite database.


5. Sending Sensor Data to the Cloud (MQTT + Python)

Publish data to MQTT Cloud (e.g., HiveMQ, Mosquitto).

Python Code to Send Data to MQTT Broker:

import paho.mqtt.client as mqtt

broker = "broker.hivemq.com"
topic = "home/sensors"

client = mqtt.Client()
client.connect(broker, 1883)

temperature = 25.3
humidity = 60.5
client.publish(topic, f"Temp: {temperature}°C, Humidity: {humidity}%")

Sends sensor data to an MQTT broker.


6. Displaying Sensor Data on a Web Dashboard

You can display real-time sensor data on a Flask web app.

Python Code Using Flask:

from flask import Flask, jsonify
import random

app = Flask(__name__)

@app.route('/sensor')
def get_sensor_data():
temperature = round(random.uniform(20, 30), 2)
humidity = round(random.uniform(50, 80), 2)
return jsonify({"temperature": temperature, "humidity": humidity})

if __name__ == '__main__':
app.run(debug=True)

Runs a REST API to fetch sensor data.

Leave a Reply

Your email address will not be published. Required fields are marked *