Setting up a Raspberry Pi 2 Model B with two DS18B20 temperature sensors to monitor the temperature of two pumps involves several steps, including hardware wiring, software installation, programming, and configuring the system to start automatically on boot. Below is a comprehensive guide to help you achieve this, incorporating your specific requirements.
1. Materials Needed
Hardware Components:
- Raspberry Pi 2 Model B
- 2 x DS18B20 Temperature Sensors
- 3 x LEDs (Green for status, and two for temperature indicators)
- 3 x 220Ω Resistors (for LEDs)
- 2 x 4.7kΩ Resistors (pull-up resistors for DS18B20 sensors)
- Jumper Wires
- Breadboard (optional, for prototyping)
- Power Supply for Raspberry Pi
Software Components:
- Raspbian OS (now called Raspberry Pi OS)
- Python 3
- Required Python Libraries (
w1thermsensor, RPi.GPIO or gpiozero)
2. Hardware Setup
Wiring the DS18B20 Sensors:
Each DS18B20 sensor requires a Data, Ground, and VCC connection. To use separate GPIO pins for each sensor, you'll set up two distinct 1-Wire buses.
Components:
- DS18B20 Sensor Pinout:
- GND: Ground
- DQ: Data
- VDD: Power (3.3V)
Connections for Each Sensor:
-
Power:
- Connect the VDD pin of each DS18B20 to the Raspberry Pi's 3.3V pin.
-
Ground:
- Connect the GND pin of each DS18B20 to the Raspberry Pi's GND pin.
-
Data:
- Sensor 1:
- Connect the DQ pin to GPIO4 (physical pin 7) through a 4.7kΩ pull-up resistor connected between DQ and 3.3V.
- Sensor 2:
- Connect the DQ pin to GPIO17 (physical pin 11) through a 4.7kΩ pull-up resistor connected between DQ and 3.3V.
Wiring Diagram:
[image: Wiring Diagram] open
(Note: Please refer to DS18B20 and Raspberry Pi pinout diagrams for accurate wiring.)
Connecting LEDs:
-
Green LED (Program Status):
- Anode (+): Connect to a GPIO pin (e.g., GPIO27, physical pin 13) through a 220Ω resistor.
- Cathode (-): Connect to GND.
-
Red LED 1 (Sensor 1 Indicator):
- Anode (+): Connect to a GPIO pin (e.g., GPIO22, physical pin 15) through a 220Ω resistor.
- Cathode (-): Connect to GND.
-
Red LED 2 (Sensor 2 Indicator):
- Anode (+): Connect to a GPIO pin (e.g., GPIO10, physical pin 19) through a 220Ω resistor.
- Cathode (-): Connect to GND.
3. Software Configuration
a. Preparing the Raspberry Pi:
-
Update the System Packages:
sudo apt-get update
sudo apt-get upgrade -y
-
Enable 1-Wire Interface:
The Raspberry Pi supports multiple 1-Wire buses. We'll need to configure each GPIO used for the DS18B20 sensors as a separate 1-Wire bus.
-
Open the boot configuration file:
sudo nano /boot/config.txt
-
Add the following lines at the end to enable two separate 1-Wire buses on GPIO4 and GPIO17:
dtoverlay=w1-gpio,gpiopin=4
dtoverlay=w1-gpio,gpiopin=17
-
Save and exit (Ctrl + X, then Y, and Enter).
-
Reboot the Raspberry Pi:
sudo reboot
b. Installing Required Packages:
-
Install Required Libraries:
sudo apt-get install python3-pip git -y
sudo pip3 install w1thermsensor gpiozero
-
Load 1-Wire Modules:
If not already loaded, load the 1-Wire modules:
sudo modprobe w1-gpio
sudo modprobe w1-therm
c. Verifying the Sensors:
After rebooting, check if the sensors are detected.
-
Check 1-Wire Devices:
ls /sys/bus/w1/devices/
You should see directories starting with 28- corresponding to each DS18B20 sensor. Confirm that two sensors are listed.
d. Writing the Python Script:
We'll create a Python script that:
- Reads temperatures from both sensors every 2 minutes.
- Controls three LEDs based on status and temperature readings.
- Displays outputs in a terminal window.
1. Create the Python Script:
mkdir ~/temperature_monitor
cd ~/temperature_monitor
nano temperature_monitor.py
2. Paste the Following Code into temperature_monitor.py:
#!/usr/bin/env python3
import time
import sys
import os
from w1thermsensor import W1ThermSensor, SensorNotReadyError
from gpiozero import LED
from datetime import datetime
# GPIO Pins for LEDs
GREEN_LED_PIN = 27 # Program status
RED_LED1_PIN = 22 # Sensor 1 indicator
RED_LED2_PIN = 10 # Sensor 2 indicator
# Initialize LEDs
green_led = LED(GREEN_LED_PIN)
red_led1 = LED(RED_LED1_PIN)
red_led2 = LED(RED_LED2_PIN)
# Initialize 1-Wire sensors
sensor1 = W1ThermSensor(W1ThermSensor.THERM_SENSOR_DS18B20, "000004a3b7d3") # Replace with your sensor1 ID
sensor2 = W1ThermSensor(W1ThermSensor.THERM_SENSOR_DS18B20, "000004a3b7d4") # Replace with your sensor2 ID
# Temperature threshold
TEMP_THRESHOLD = 35.0 # degrees Celsius
def get_sensor_ids():
sensors = W1ThermSensor.get_available_sensors()
if len(sensors) < 2:
print("Error: Less than two DS18B20 sensors detected.")
sys.exit(1)
return sensors[:2]
def main():
sensors = get_sensor_ids()
global sensor1, sensor2
sensor1 = sensors[0]
sensor2 = sensors[1]
# Turn on Green LED to indicate program is running
green_led.on()
print("Temperature Monitoring Program Started")
print(f"Monitoring Sensor 1 (ID: {sensor1.id}) and Sensor 2 (ID: {sensor2.id})")
while True:
try:
temp1 = sensor1.get_temperature()
temp2 = sensor2.get_temperature()
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
print(f"[{timestamp}] Sensor 1: {temp1:.2f}°C | Sensor 2: {temp2:.2f}°C")
# Control LEDs based on temperature thresholds
if temp1 < TEMP_THRESHOLD:
red_led1.on()
else:
red_led1.off()
if temp2 < TEMP_THRESHOLD:
red_led2.on()
else:
red_led2.off()
except SensorNotReadyError:
print("Error: Sensor not ready.")
red_led1.blink(on_time=0.5, off_time=0.5)
red_led2.blink(on_time=0.5, off_time=0.5)
except Exception as e:
print(f"Unexpected error: {e}")
red_led1.blink(on_time=0.5, off_time=0.5)
red_led2.blink(on_time=0.5, off_time=0.5)
# Wait for 2 minutes
time.sleep(120)
if __name__ == "__main__":
main()
3. Configure Sensor IDs:
Replace "000004a3b7d3" and "000004a3b7d4" with the actual IDs of your DS18B20 sensors. To find sensor IDs:
ls /sys/bus/w1/devices/
Look for directories starting with 28- and use those IDs.
4. Make the Script Executable:
chmod +x temperature_monitor.py
4. Configuring Auto-Start on Boot
To make the script run automatically on startup and open a terminal window showing the outputs, you can create a systemd service or use crontab with @reboot. Here, we'll use crontab to open a terminal.
Using crontab with lxterminal:
-
Edit Crontab:
crontab -e
-
Add the Following Line at the End:
@reboot /usr/bin/lxterminal -e /home/pi/temperature_monitor/temperature_monitor.py &
Adjust the path if your username or script location differs.
-
Save and Exit:
Press Ctrl + X, then Y, and Enter to save.
Alternatively, Using systemd for Better Management:
-
Create a Service File:
sudo nano /etc/systemd/system/temperature_monitor.service
-
Add the Following Content:
[Unit]
Description=Temperature Monitoring Service
After=multi-user.target
[Service]
Type=simple
ExecStart=/usr/bin/python3 /home/pi/temperature_monitor/temperature_monitor.py
WorkingDirectory=/home/pi/temperature_monitor/
StandardOutput=inherit
StandardError=inherit
Restart=always
User=pi
[Install]
WantedBy=multi-user.target
-
Enable and Start the Service:
sudo systemctl daemon-reload
sudo systemctl enable temperature_monitor.service
sudo systemctl start temperature_monitor.service
-
Check Service Status:
sudo systemctl status temperature_monitor.service
Note: Using systemd does not open a terminal window but ensures the service runs continuously and restarts on failure. If you prefer a terminal window display, stick with the crontab method.
5. Final Steps and Testing
-
Reboot the Raspberry Pi:
sudo reboot
-
Observe the LEDs Upon Startup:
- Green LED should be continuously on, indicating the program is running.
- Red LEDs should turn on if the corresponding sensor reads below 35°C or blink if there's an error.
-
Check the Terminal Output:
If using crontab with lxterminal, a terminal window should open displaying temperature readings every 2 minutes with timestamps.
-
Troubleshooting:
- Ensure all connections are secure.
- Verify sensor IDs in the Python script.
- Check the status of the
systemd service if using that method.
- Review any error messages in the terminal or system logs.
Enhancements and Best Practices
-
Use Unique Identifiers: Instead of hardcoding sensor IDs, you can modify the script to automatically detect sensors and assign them dynamically.
-
Error Handling: Enhance the script to handle specific exceptions and possibly send notifications in case of persistent errors.
-
Logging: Implement logging to a file for historical temperature data analysis.
-
Security: Ensure that the script runs with appropriate permissions and consider security implications if accessing the Raspberry Pi remotely.
By following the above steps, you should have a functional Raspberry Pi setup monitoring two pump temperatures with visual indicators and automated startup behavior. This setup provides both real-time monitoring via LEDs and a logged output in a terminal window for easy observation.