To set up your Raspberry Pi 2 Model B with two DS18B20 temperature probes and corresponding LEDs to monitor the temperature of two pumps, follow the steps below. This guide covers hardware connections, software setup, and configuring the system to auto-start your program on boot.
Table of Contents
- Hardware Components
- Hardware Connections
- Software Setup
- Final Testing
- Troubleshooting
Hardware Components
- Raspberry Pi 2 Model B
- 2 x DS18B20 Temperature Probes
- 3 x LEDs (1 Green, 2 of your choice for probes)
- 3 x 330Ω Resistors (for LEDs)
- 1 x 4.7kΩ Resistor (for DS18B20)
- Breadboard and Jumper Wires
- Power Supply for Raspberry Pi
Hardware Connections
1. Connect the DS18B20 Probes
Each DS18B20 probe has three pins: GND, Data, and VCC.
- Data Wiring:
DS18B20s typically share the same data line, but since you want to use individual GPIOs for each probe, we'll connect them to separate GPIOs.
Probe 1:
- VCC: Connect to 3.3V (Pin 1) on Pi.
- GND: Connect to GND (Pin 6) on Pi.
- Data: Connect to GPIO4 (Pin 7) with a 4.7kΩ resistor between Data and VCC.
Probe 2:
- VCC: Connect to 3.3V (Pin 1) on Pi.
- GND: Connect to GND (Pin 6) on Pi.
- Data: Connect to GPIO17 (Pin 11) with a 4.7kΩ resistor between Data and VCC.
Note: DS18B20 usually operates in a single-wire bus configuration, but using separate GPIOs can allow independent monitoring and LED control.
2. Connect the LEDs
Each LED needs a current-limiting resistor (typically 330Ω) in series.
Green LED (Program Status):
- Anode (+): Connect to a GPIO pin (e.g., GPIO27, Pin 13) through a 330Ω resistor.
- Cathode (-): Connect to GND.
LED for Probe 1:
- Anode (+): Connect to GPIO22 (Pin 15) through a 330Ω resistor.
- Cathode (-): Connect to GND.
LED for Probe 2:
- Anode (+): Connect to GPIO23 (Pin 16) through a 330Ω resistor.
- Cathode (-): Connect to GND.
LED Pins Reference:
- GPIO Pins: Choose available GPIOs; the above example uses GPIO27, GPIO22, and GPIO23.
- Ground Pins: Any GND pin will work.
3. Wiring Diagram
Here's a simplified wiring summary:
-
Power:
- 3.3V (Pin 1) → DS18B20 VCC
- GND (Pin 6) → DS18B20 GND and LED cathodes
-
Data Lines:
- DS18B20 Probe 1 Data → GPIO4 (Pin 7) with 4.7kΩ resistor to 3.3V
- DS18B20 Probe 2 Data → GPIO17 (Pin 11) with 4.7kΩ resistor to 3.3V
-
LEDs:
- Green LED Anode → GPIO27 (Pin 13) via 330Ω resistor
- Probe LED1 Anode → GPIO22 (Pin 15) via 330Ω resistor
- Probe LED2 Anode → GPIO23 (Pin 16) via 330Ω resistor
Software Setup
1. Update and Upgrade Your Raspberry Pi
First, ensure your Raspberry Pi's software is up to date.
sudo apt-get update
sudo apt-get upgrade -y
2. Enable One-Wire Interface
The DS18B20 communicates over the One-Wire protocol. To enable it:
-
Edit the boot configuration:
sudo nano /boot/config.txt
-
Add the following lines at the end:
dtoverlay=w1-gpio,gpiopin=4
dtoverlay=w1-gpio,gpiopin=17
Note: Enabling multiple One-Wire buses isn't straightforward on the Raspberry Pi. The One-Wire kernel module isn't designed to support multiple separate data lines easily. Instead, it's recommended to use a single One-Wire data line and handle multiple sensors via unique addresses. However, since you've requested individual GPIOs, the alternative is to manage separate instances or use separate modules like w1thermsensor. For simplicity, we'll proceed with a single One-Wire bus.
-
Reboot the Raspberry Pi:
sudo reboot
-
Load One-Wire Modules:
After reboot, ensure the One-Wire modules are loaded.
lsmod | grep w1
You should see w1_gpio and w1_therm listed.
3. Install Required Python Libraries
We'll use Python to read the temperatures and control the LEDs.
-
Ensure Python and pip are installed:
sudo apt-get install python3 python3-pip -y
-
Install necessary libraries:
pip3 install RPi.GPIO
4. Write the Python Script
Create a Python script that:
- Reads temperatures from two DS18B20 probes.
- Controls three LEDs based on temperature readings.
- Displays output in the terminal.
- Handles errors by blinking the respective LED.
4.1. Identify DS18B20 Addresses
If using a single One-Wire bus, identify each probe’s unique address.
-
Navigate to the One-Wire directory:
cd /sys/bus/w1/devices/
ls
You should see directories like 28-XXXXXXXXXXXX where XXXXXXXXXXXX is the unique address.
-
Note down the addresses for each probe.
4.2. Create the Python Script
Create a script, e.g., temp_monitor.py:
nano temp_monitor.py
Paste the following code, customizing GPIO pins and addresses as necessary:
#!/usr/bin/env python3
import os
import glob
import time
import RPi.GPIO as GPIO
import subprocess
# GPIO pin setup
GREEN_LED = 27
PROBE1_LED = 22
PROBE2_LED = 23
GPIO.setmode(GPIO.BCM)
GPIO.setup(GREEN_LED, GPIO.OUT)
GPIO.setup(PROBE1_LED, GPIO.OUT)
GPIO.setup(PROBE2_LED, GPIO.OUT)
# Turn on the green LED indicating the program is running
GPIO.output(GREEN_LED, GPIO.HIGH)
# DS18B20 setup
os.system('modprobe w1-gpio')
os.system('modprobe w1-therm')
# Base directory for sensors
base_dir = '/sys/bus/w1/devices/'
# Replace with your actual sensor addresses
sensor1 = '28-XXXXXXXXXXXX' # Replace with Probe 1 address
sensor2 = '28-YYYYYYYYYYYY' # Replace with Probe 2 address
def read_temp_raw(sensor):
device_folder = base_dir + sensor
device_file = device_folder + '/w1_slave'
try:
with open(device_file, 'r') as f:
lines = f.readlines()
return lines
except:
return None
def read_temp(sensor):
lines = read_temp_raw(sensor)
if lines is None:
return None
if lines[0].strip()[-3:] != 'YES':
return None
equals_pos = lines[1].find('t=')
if equals_pos != -1:
temp_string = lines[1][equals_pos+2:]
temp_c = float(temp_string) / 1000.0
return temp_c
return None
def control_led(led, temp):
if temp is not None:
if temp < 35:
GPIO.output(led, GPIO.HIGH)
else:
GPIO.output(led, GPIO.LOW)
else:
# Blink LED to indicate error
for _ in range(5):
GPIO.output(led, GPIO.HIGH)
time.sleep(0.5)
GPIO.output(led, GPIO.LOW)
time.sleep(0.5)
def main():
print("Temperature Monitoring Started")
while True:
temp1 = read_temp(sensor1)
temp2 = read_temp(sensor2)
timestamp = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
if temp1 is not None:
print(f"[{timestamp}] Probe 1 Temperature: {temp1}°C")
else:
print(f"[{timestamp}] Probe 1 Temperature: Error reading sensor")
if temp2 is not None:
print(f"[{timestamp}] Probe 2 Temperature: {temp2}°C")
else:
print(f"[{timestamp}] Probe 2 Temperature: Error reading sensor")
# Control LEDs based on temperature
control_led(PROBE1_LED, temp1)
control_led(PROBE2_LED, temp2)
# Wait for 2 minutes
time.sleep(120)
if __name__ == "__main__":
try:
main()
except KeyboardInterrupt:
print("Program terminated by user")
finally:
GPIO.cleanup()
4.3. Customize the Script
-
Replace Sensor Addresses:
- Replace
'28-XXXXXXXXXXXX' and '28-YYYYYYYYYYYY' with your actual DS18B20 sensor addresses identified earlier.
-
Make the Script Executable:
chmod +x temp_monitor.py
5. Set Up Auto-Start on Boot
To ensure your script runs on startup and opens a terminal, you'll use systemd to manage the service.
5.1. Create a Service File
-
Create a new service file:
sudo nano /etc/systemd/system/temp_monitor.service
-
Add the following content:
[Unit]
Description=Temperature Monitoring Service
After=network.target
[Service]
Type=simple
ExecStart=/usr/bin/python3 /home/pi/temp_monitor.py
WorkingDirectory=/home/pi
StandardOutput=inherit
StandardError=inherit
Restart=always
User=pi
[Install]
WantedBy=multi-user.target
Note:
- Replace
/home/pi/temp_monitor.py with the actual path to your script if different.
- Ensure the
User is set correctly (default is pi).
5.2. Enable and Start the Service
-
Reload systemd to recognize the new service:
sudo systemctl daemon-reload
-
Enable the service to start on boot:
sudo systemctl enable temp_monitor.service
-
Start the service immediately:
sudo systemctl start temp_monitor.service
-
Check the status of the service:
sudo systemctl status temp_monitor.service
You should see that the service is active and running.
5.3. Open Terminal on Boot (Optional)
If you want a terminal window to open on desktop showing the script’s output:
-
Edit LXDE autostart file:
sudo nano /home/pi/.config/lxsession/LXDE-pi/autostart
If the file or directory doesn’t exist, create them:
mkdir -p /home/pi/.config/lxsession/LXDE-pi/
nano /home/pi/.config/lxsession/LXDE-pi/autostart
-
Add the following line to open a terminal and run the script:
@lxterminal -e /usr/bin/python3 /home/pi/temp_monitor.py
Note: Adjust the path if your script is located elsewhere.
-
Save and Exit: Press CTRL + X, then Y, and Enter to save.
Note: Having both the systemd service and the terminal running the script might result in duplicate outputs. Choose the method that best fits your monitoring preferences.
Final Testing
-
Reboot the Raspberry Pi:
sudo reboot
-
Verify LEDs and Terminal:
- The green LED should be on, indicating the program is running.
- Probe LEDs should light up if their respective temperatures are below 35°C.
- If a sensor fails, its LED should blink to indicate an error.
- A terminal window should open displaying temperature readings every 2 minutes.
-
Check Service Logs:
To view logs generated by the systemd service:
journalctl -u temp_monitor.service -f
This will stream the logs, helping you verify the program's operation.
Troubleshooting
-
LEDs Not Working:
- Verify GPIO connections and resistor placements.
- Ensure the correct GPIO pins are defined in the script.
-
DS18B20 Not Reading Temperatures:
- Ensure the sensors are properly connected with the 4.7kΩ resistor.
- Confirm sensor addresses are correct.
- Check One-Wire interface is enabled and modules are loaded.
-
Script Not Starting on Boot:
- Ensure the
systemd service is enabled.
- Check for errors using
sudo systemctl status temp_monitor.service.
- Verify script permissions and paths.
-
Terminal Not Opening on Boot:
- Confirm the autostart entry is correct.
- Ensure the LXDE settings are properly configured.
-
General Errors:
- Review the script for syntax errors.
- Check dependencies are installed (
RPi.GPIO library).
- Use
print statements or logs to debug.
Additional Enhancements
By following this guide, you should have a functional Raspberry Pi temperature monitoring system tailored to your requirements. Ensure all connections are secure, and consider enclosures to protect your electronics in operational environments.