← Programming Concepts in Mechanical Engineering (25ME34I)
Sensor Integration and Data Collection
Programming Concepts in Mechanical Engineering (25ME34I) · C-25 Diploma Mechanical, Semester III
Read with diagrams, search and self-test
After studying this chapter you will be able to:
• Explain sensors, transducers and their classification.
• Interface DHT11 (temperature-humidity), BMP180 (pressure), PIR (motion) and HC-SR04 (distance) sensors with Raspberry Pi.
• Write Python programs to read sensors and log data to CSV files.
• Build a simple obstacle-avoiding robot using Raspberry Pi, motors and sensors.
9.1 Sensors and Transducers
A sensor detects a physical quantity (temperature, pressure, motion, distance, light) and converts it into a signal that can be measured. A transducer converts energy from one form to another; most sensors are transducers that produce an electrical output. Sensors are the "eyes and ears" of an automated system: a controller (Raspberry Pi) reads the sensor, decides and commands an actuator (motor, relay).
Classification
| Basis | Types | Examples |
|---|---|---|
| Output signal | Digital (ON/OFF or digital data) / Analog (continuous voltage) | PIR, DHT11 (digital); LM35, potentiometer (analog) |
| Power | Active (need external power) / Passive (self-generating) | Ultrasonic (active); thermocouple (passive) |
| Quantity measured | Temperature, pressure, motion, distance, light, force | DHT11, BMP180, PIR, HC-SR04, LDR, load cell |
| Contact | Contact / Non-contact | RTD (contact); IR thermometer (non-contact) |
The Raspberry Pi has only digital GPIO inputs. Digital sensors connect directly (through single-wire, I²C or SPI protocols). Analog sensors need an ADC (analog-to-digital converter) such as the MCP3008 (SPI) or ADS1115 (I²C).
Communication methods used by sensors
| Method | Wires | Sensors |
|---|---|---|
| Simple digital (HIGH/LOW) | 1 signal | PIR, IR obstacle, float switch, limit switch |
| Timed pulse | Trigger + echo | HC-SR04 ultrasonic |
| Single-wire proprietary | 1 data | DHT11/DHT22 |
| 1-Wire bus | 1 data | DS18B20 |
| I²C | SDA + SCL (shared bus, addresses) | BMP180, BME280, MPU6050, ADS1115 |
| SPI | MOSI, MISO, SCLK, CE | MCP3008 ADC |
Installing sensor libraries
Since Raspberry Pi OS Bookworm, Python packages from pip are installed inside a virtual environment:
python3 -m venv --system-site-packages ~/env source ~/env/bin/activate pip install adafruit-circuitpython-dht sudo apt install python3-smbus i2c-tools
9.2 DHT11 Temperature and Humidity Sensor
The DHT11 is a low-cost digital sensor containing a capacitive humidity element and an NTC thermistor, with a small microcontroller that sends calibrated data over a single wire.
| Parameter | DHT11 | DHT22 (AM2302) |
|---|---|---|
| Temperature range | 0 – 50 °C | −40 – 80 °C |
| Temperature accuracy | ±2 °C | ±0.5 °C |
| Humidity range | 20 – 90 % RH | 0 – 100 % RH |
| Humidity accuracy | ±5 % RH | ±2 % RH |
| Sampling rate | 1 reading per second | 1 reading per 2 seconds |
| Supply | 3.3 – 5 V | 3.3 – 5 V |
Applications: workshop climate monitoring, compressor-room temperature, storage of hygroscopic materials, HVAC control, automatic fan control.
Fig. 9.1 DHT11 connections
Program 9.1 – Read temperature and humidity from DHT11
# Program 9.1: DHT11 temperature and humidity import time import board import adafruit_dht
dht = adafruit_dht.DHT11(board.D4) # data on GPIO4
try:
for i in range(5):
try:
t = dht.temperature
h = dht.humidity
print(f"Temp = {t:.1f} °C Humidity = {h:.0f} %")
except RuntimeError as e: # occasional checksum error
print("Read error:", e.args[0])
time.sleep(2.0)
finally:
dht.exit()Temp = 27.0 °C Humidity = 61 % Temp = 27.0 °C Humidity = 61 % Read error: Checksum did not validate. Try again. Temp = 28.0 °C Humidity = 60 % Temp = 28.0 °C Humidity = 60 %
DHT sensors occasionally fail to read because the timing is critical. This is normal; the program must catch RuntimeError and retry after 2 seconds – a practical use of exception handling from Chapter 6.
9.3 BMP180 Barometric Pressure Sensor
The BMP180 (Bosch) measures absolute atmospheric pressure (300–1100 hPa, resolution 0.01 hPa) and temperature, and communicates over I²C at address 0x77. Altitude can be calculated from pressure. (Its successors BMP280/BME280 are pin-compatible in function and are now more common.)
Altitude from the international barometric formula:
h = 44330 × [1 − (P / P₀)^(1/5.255)] metres, with P₀ = 101325 Pa at sea level.
Fig. 9.2 BMP180 I²C connections
Enable I²C (raspi-config → Interface Options → I2C) and check the sensor with i2cdetect -y 1; "77" appears in the address table.
Program 9.2 – Read pressure, temperature and altitude from BMP180
# Program 9.2: BMP180 using the Adafruit BMP085/180 library # pip install Adafruit-BMP (legacy library, BMP180 compatible) import Adafruit_BMP.BMP085 as BMP085 import time
sensor = BMP085.BMP085(busnum=1)
for _ in range(3):
T = sensor.read_temperature() # °C
P = sensor.read_pressure() # Pa
alt = sensor.read_altitude() # m (P0 = 101325 Pa)
print(f"Temp = {T:.1f} °C Pressure = {P/100:.2f} hPa "
f"Altitude = {alt:.1f} m")
time.sleep(2)Temp = 26.4 °C Pressure = 908.72 hPa Altitude = 914.6 m Temp = 26.4 °C Pressure = 908.70 hPa Altitude = 914.8 m Temp = 26.5 °C Pressure = 908.75 hPa Altitude = 914.3 m
(The sample readings correspond to Bengaluru, about 900 m above sea level.) The altitude formula itself can be checked on any computer:
P0 = 101325.0
for P_hPa in (1013.25, 950.0, 908.7, 800.0):
P = P_hPa * 100
h = 44330 * (1 - (P / P0) ** (1 / 5.255))
print(f"P = {P_hPa:7.2f} hPa -> altitude = {h:7.1f} m")P = 1013.25 hPa -> altitude = 0.0 m P = 950.00 hPa -> altitude = 540.4 m P = 908.70 hPa -> altitude = 909.2 m P = 800.00 hPa -> altitude = 1949.3 m
9.4 PIR Motion Sensor (HC-SR501)
A Passive Infra-Red (PIR) sensor detects the movement of warm bodies (humans, animals) by sensing changes in infrared radiation using a pyroelectric element behind a Fresnel lens. It is "passive" because it emits nothing. Output: HIGH (3.3 V) when motion is detected. Range up to 7 m, 120° cone. Two potentiometers adjust sensitivity and delay time (0.3 s – 5 min); a jumper selects single or repeat trigger.
Applications: machine-guard safety (stop a press when a person enters the danger zone), automatic lighting, intruder alarms, people counting.
Fig. 9.3 PIR sensor connections
Program 9.3 – Motion detection with PIR
# Program 9.3: PIR motion detection with alarm LED from gpiozero import MotionSensor, LED from datetime import datetime
pir = MotionSensor(27)
alarm = LED(17)
print("Waiting for PIR to settle...")
pir.wait_for_no_motion()
print("Ready")
count = 0
while True:
pir.wait_for_motion()
count += 1
alarm.on()
print(f"{datetime.now():%H:%M:%S} Motion detected! #{count}")
pir.wait_for_no_motion()
alarm.off()
print(f"{datetime.now():%H:%M:%S} Area clear")Waiting for PIR to settle... Ready 10:15:02 Motion detected! #1 10:15:09 Area clear 10:17:44 Motion detected! #2 10:17:52 Area clear
9.5 HC-SR04 Ultrasonic Distance Sensor
The HC-SR04 measures distance (2 cm – 400 cm, ±3 mm) using 40 kHz ultrasound. Operation:
1. The Pi sends a 10 µs HIGH pulse to TRIG.
2. The module emits eight 40 kHz ultrasonic pulses.
3. ECHO goes HIGH and stays HIGH until the reflected sound returns.
4. Distance = (echo time × speed of sound) / 2. With speed of sound 343 m/s = 34300 cm/s: distance (cm) = time (s) × 17150. The ECHO pin outputs 5 V, so a voltage divider (1 kΩ and 2 kΩ) reduces it to about 3.3 V for the Pi.
Fig. 9.4 HC-SR04 connections with voltage divider
Program 9.4 – Distance measurement using RPi.GPIO
# Program 9.4: HC-SR04 distance measurement import RPi.GPIO as GPIO import time
TRIG, ECHO = 20, 21 GPIO.setmode(GPIO.BCM) GPIO.setup(TRIG, GPIO.OUT) GPIO.setup(ECHO, GPIO.IN)
def distance_cm():
GPIO.output(TRIG, False); time.sleep(0.05)
GPIO.output(TRIG, True); time.sleep(0.00001) # 10 us
GPIO.output(TRIG, False)
start = stop = time.time()
while GPIO.input(ECHO) == 0:
start = time.time()
while GPIO.input(ECHO) == 1:
stop = time.time()
return (stop - start) * 17150try:
while True:
print(f"Distance = {distance_cm():.1f} cm")
time.sleep(1)
except KeyboardInterrupt:
GPIO.cleanup()The gpiozero version is much shorter – the library handles the timing:
from gpiozero import DistanceSensor
from time import sleep
sensor = DistanceSensor(echo=21, trigger=20, max_distance=4)
while True:
print(f"Distance = {sensor.distance * 100:.1f} cm")
sleep(1)Distance = 52.3 cm Distance = 51.9 cm Distance = 18.6 cm Distance = 7.4 cm
Applications: tank level measurement, obstacle detection in robots and AGVs, parking sensors, part presence detection on conveyors.
9.6 Data Collection and Logging
Collecting sensor data and storing it with time stamps in a CSV file makes it available for analysis in Excel or pandas – linking this chapter to CO-02 and the SQC chapters.
Program 9.5 – Multi-sensor data logger to CSV
# Program 9.5: Log temperature, humidity and distance to CSV import csv, time from datetime import datetime import board, adafruit_dht from gpiozero import DistanceSensor
dht = adafruit_dht.DHT11(board.D4)
us = DistanceSensor(echo=21, trigger=20)
with open("sensor_log.csv", "a", newline="") as f:
w = csv.writer(f)
if f.tell() == 0:
w.writerow(["Time", "Temp_C", "Humidity_pct", "Level_cm"])
for _ in range(10):
try:
row = [datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
dht.temperature, dht.humidity,
round(us.distance * 100, 1)]
w.writerow(row); f.flush()
print(row)
except RuntimeError:
continue
time.sleep(5)
dht.exit()Program 9.6 – Analyse and plot logged data
The following program generates a sample log (as obtained from Program 9.5) and analyses it on a PC.
import csv, random
import matplotlib.pyplot as plt
# create a sample log file for demonstration
with open("sensor_log_demo.csv", "w", newline="") as f:
w = csv.writer(f)
w.writerow(["Minute", "Temp_C", "Humidity_pct"])
for m in range(0, 60, 2):
t = round(26 + m * 0.05 + random.uniform(-.4, .4), 1)
h = round(62 - m * 0.08 + random.uniform(-1, 1))
w.writerow([m, t, h])
mins, temp, hum = [], [], []
with open("sensor_log_demo.csv") as f:
for r in csv.DictReader(f):
mins.append(int(r["Minute"]))
temp.append(float(r["Temp_C"]))
hum.append(float(r["Humidity_pct"]))
print(f"Readings: {len(temp)} Avg temp: {sum(temp)/len(temp):.2f} °C"
f" Max: {max(temp)} °C Min humidity: {min(hum)} %")
fig, ax1 = plt.subplots(figsize=(6, 3))
ax1.plot(mins, temp, "r-o", ms=3, label="Temperature")
ax1.set_xlabel("Time (min)"); ax1.set_ylabel("Temperature (°C)")
ax2 = ax1.twinx()
ax2.plot(mins, hum, "b-s", ms=3, label="Humidity")
ax2.set_ylabel("Humidity (%)")
ax1.set_title("Workshop climate log")
fig.legend(loc="lower right", ncol=2, fontsize=8)
plt.tight_layout(); plt.show()Readings: 30 Avg temp: 27.39 °C Max: 29.1 °C Min humidity: 57.0 %
9.7 Practice: Building a Simple Robot (Week 9)
Obstacle-avoiding robot
Components: Raspberry Pi, robot chassis with two DC gear motors and a castor wheel, L298N driver, HC-SR04 sensor (front), optional PIR and buzzer, 7.4–12 V battery pack for motors, 5 V power bank for the Pi, jumper wires.
Fig. 9.5 Block diagram of the obstacle-avoiding robot
Working logic (algorithm):
1. Start; initialise motors and distance sensor.
2. Measure distance to the obstacle in front.
3. If distance > 30 cm, move forward.
4. Otherwise stop, reverse for 0.5 s, turn right for 0.4 s.
5. Repeat from step 2 until Ctrl+C is pressed; then stop motors.
Program 9.7 – Obstacle-avoiding robot (gpiozero Robot class)
# Program 9.7: Obstacle avoiding robot from gpiozero import Robot, DistanceSensor from time import sleep
robot = Robot(left=(23, 24, 18), right=(5, 6, 13)) # IN,IN,EN sensor = DistanceSensor(echo=21, trigger=20, max_distance=2) SAFE = 0.30 # metres
try:
while True:
d = sensor.distance
if d > SAFE:
robot.forward(0.6)
print(f"Path clear {d*100:5.1f} cm -> FORWARD")
else:
print(f"Obstacle {d*100:5.1f} cm -> AVOID")
robot.stop(); sleep(0.2)
robot.backward(0.5); sleep(0.5)
robot.right(0.6); sleep(0.4)
sleep(0.1)
except KeyboardInterrupt:
robot.stop()
print("Robot stopped")Path clear 85.2 cm -> FORWARD Path clear 61.7 cm -> FORWARD Path clear 34.0 cm -> FORWARD Obstacle 24.6 cm -> AVOID Path clear 97.3 cm -> FORWARD Robot stopped
Robot(left=(23, 24, 18), right=(5, 6, 13)) creates two Motor objects with (forward pin, backward pin, enable pin), using the L298N wiring of Fig. 8.4. right() turns the robot by running the left wheel forward and the right wheel backward.
Program 9.8 – Simulating the robot's decision logic on a PC
readings = [85, 62, 34, 25, 18, 97, 70, 29, 110] # cm
SAFE = 30
for d in readings:
if d > SAFE:
action = "FORWARD"
else:
action = "STOP -> REVERSE -> TURN RIGHT"
print(f"{d:4d} cm : {action}")85 cm : FORWARD 62 cm : FORWARD 34 cm : FORWARD 25 cm : STOP -> REVERSE -> TURN RIGHT 18 cm : STOP -> REVERSE -> TURN RIGHT 97 cm : FORWARD 70 cm : FORWARD 29 cm : STOP -> REVERSE -> TURN RIGHT 110 cm : FORWARD
9.8 Solved Exam Questions
Q1. Explain the interfacing of the DHT11 sensor with Raspberry Pi and write a program to read temperature and humidity. (8 marks)
Answer: DHT11 has VCC, DATA and GND pins; connect VCC to 3.3 V (pin 1), DATA to GPIO4 (pin 7) with a 10 kΩ pull-up (built into modules), GND to pin 9 (Fig. 9.1). Install adafruit-circuitpython-dht. Program 9.1 creates adafruit_dht.DHT11(board.D4), reads .temperature and .humidity every 2 s and handles RuntimeError for occasional failed reads.
Q2. Explain the working of the HC-SR04 ultrasonic sensor. How is distance calculated? (6 marks)
Answer: A 10 µs pulse on TRIG makes the module emit a 40 kHz burst; ECHO stays HIGH for the round-trip time t of the sound. Distance = (t × 343 m/s)/2 = t × 17150 cm. The 5 V ECHO signal is reduced to 3.3 V by a 1 kΩ/2 kΩ divider. Example: t = 2.9 ms → d = 0.0029 × 17150 = 49.7 cm.
Q3. What is a PIR sensor? Give its applications in mechanical engineering. (5 marks)
Answer: A passive infrared sensor detects motion of warm bodies by changes in IR radiation, giving a digital HIGH output. Applications: safety interlock on presses and robots (stop machine when a person approaches), automatic lighting in plants, intrusion detection in stores, counting people at gates.
Q4. Explain the BMP180 sensor and the I²C interface. (5 marks)
Answer: BMP180 measures absolute pressure (300–1100 hPa) and temperature; altitude is computed from pressure. It uses I²C – a two-wire bus (SDA data, SCL clock) where each device has an address (0x77 for BMP180), so many sensors can share two pins (GPIO2, GPIO3). I²C is enabled with raspi-config and checked with i2cdetect -y 1.
Q5. Describe the construction and program of a simple obstacle-avoiding robot using Raspberry Pi. (10 marks)
Answer: Components, block diagram (Fig. 9.5), algorithm and Program 9.7 as given in Section 9.7.
9.9 Multiple Choice Questions
1. DHT11 measures a) pressure and altitude b) temperature and humidity c) distance d) motion
Answer: (b) Reason: It combines a thermistor and a capacitive humidity element.
2. BMP180 communicates with the Raspberry Pi using a) UART b) I²C c) PWM d) analog voltage
Answer: (b) Reason: It is an I²C device at address 0x77 using SDA and SCL lines.
3. PIR stands for a) Passive Infra-Red b) Pressure Indicator Relay c) Power Input Regulator d) Proximity Infra Ray
Answer: (a) Reason: It passively senses infrared radiation from warm bodies.
4. HC-SR04 distance in cm equals echo time (s) multiplied by a) 343 b) 17150 c) 34300 d) 1715
Answer: (b) Reason: 34300 cm/s divided by 2 for the round trip gives 17150.
5. Why is a voltage divider used on the HC-SR04 ECHO pin? a) To increase range b) To reduce 5 V to about 3.3 V for the GPIO c) To generate ultrasound d) To power the sensor
Answer: (b) Reason: GPIO inputs tolerate only 3.3 V.
6. The I²C bus uses which two lines? a) TX and RX b) SDA and SCL c) MOSI and MISO d) TRIG and ECHO
Answer: (b) Reason: SDA carries data and SCL carries the clock.
7. The Raspberry Pi needs an ADC to read a) DHT11 b) analog sensors like LM35 c) PIR d) push buttons
Answer: (b) Reason: The Pi has no analog inputs; MCP3008 or ADS1115 converts analog voltage.
8. Command to detect I²C devices is a) i2cdetect -y 1 b) lsusb c) pinout d) ping
Answer: (a) Reason: It prints a table of responding addresses on bus 1.
9. The temperature range of DHT11 is a) −40 to 125 °C b) 0 to 50 °C c) 0 to 100 °C d) −10 to 85 °C
Answer: (b) Reason: DHT11 covers 0–50 °C with ±2 °C accuracy; DHT22 has a wider range.
10. In gpiozero, DistanceSensor.distance returns the distance in a) mm b) cm c) metres d) inches
Answer: (c) Reason: Multiply by 100 to display centimetres.
11. A PIR sensor's output when motion is detected is a) analog 0–5 V b) digital HIGH c) PWM d) I²C data
Answer: (b) Reason: The HC-SR501 output goes HIGH (3.3 V) for the set delay time.
12. The ultrasonic frequency used by HC-SR04 is a) 20 Hz b) 40 kHz c) 2.4 GHz d) 1 MHz
Answer: (b) Reason: 40 kHz is above the human hearing limit of about 20 kHz.
13. Which gpiozero class drives a two-motor robot? a) Motor b) Robot c) Servo d) LED
Answer: (b) Reason: Robot combines left and right Motor objects with forward, backward, left, right methods.
14. Occasional RuntimeError while reading DHT11 should be a) ignored by removing the sensor b) caught and the reading retried c) fixed by 5 V on GPIO d) solved with sudo reboot
Answer: (b) Reason: Timing glitches are normal; exception handling with retry is the correct approach.
9.10 Exercises
1. Write a program to display "Tank level LOW" when the ultrasonic distance to the water surface exceeds 80 cm.
2. Log BMP180 pressure readings every minute for an hour and plot them.
3. Use a PIR sensor to stop a motor whenever a person enters the machine area.
4. Modify the robot program to sound a buzzer (GPIO26) while avoiding an obstacle.
5. Compare digital and analog sensors with two examples each.