Skip to content
TheChatArchiveThe Chat Archive
o1-preview-2024-09-12· OpenAIAi2 WildChat-4.8M (AI2)

My arduino now can detect my 2 DS18B20 sensor. How to write a python code to read both…

  1. User

    My arduino now can detect my 2 DS18B20 sensor. How to write a python code to read both sensor every minutes

  2. Assistant

    To read both your DS18B20 sensors every minute using Python, you'll need to set up a two-part system:

    1. Arduino Side: Program your Arduino to read the temperatures from both DS18B20 sensors and send the readings over the serial port every minute.
    2. Python Side: Write a Python script that reads the incoming serial data from the Arduino and processes the temperature readings.

    Here's how you can do it step by step:


    Part 1: Arduino Setup

    Step 1.1: Connect Your DS18B20 Sensors to the Arduino

    Make sure your DS18B20 sensors are properly connected to your Arduino:

    • Data Pin: Connect the data pin of both sensors to a digital input on the Arduino (e.g., digital pin 2).
    • Power and Ground: Connect the VCC and GND pins appropriately.
    • Pull-Up Resistor: Connect a 4.7kΩ resistor between the data line and VCC.

    Step 1.2: Install Required Libraries

    In the Arduino IDE, you'll need the following libraries:

    • OneWire Library: For communication with OneWire devices.
    • DallasTemperature Library: For easy interfacing with the DS18B20 sensors.

    You can install these libraries via the Arduino Library Manager:

    • Go to Sketch > Include Library > Manage Libraries.
    • Search for OneWire and DallasTemperature, then install them.

    Step 1.3: Write the Arduino Code

    Upload the following sketch to your Arduino:

    #include <OneWire.h>
    #include <DallasTemperature.h>
    
    // Data wire is connected to digital pin 2
    #define ONE_WIRE_BUS 2
    
    // Create a OneWire instance
    OneWire oneWire(ONE_WIRE_BUS);
    
    // Pass OneWire reference to Dallas Temperature sensor
    DallasTemperature sensors(&oneWire);
    
    // Device addresses
    DeviceAddress sensor1Address;
    DeviceAddress sensor2Address;
    
    void setup() {
      // Start serial communication
      Serial.begin(9600);
      // Start the DS18B20 sensor
      sensors.begin();
    
      // Locate devices on the bus
      Serial.print("Locating devices...");
      Serial.print("Found ");
      Serial.print(sensors.getDeviceCount());
      Serial.println(" devices.");
    
      // Assign addresses manually or use sensors.getAddress()
      if (!sensors.getAddress(sensor1Address, 0)) {
        Serial.println("Unable to find address for Device 1");
      }
      if (!sensors.getAddress(sensor2Address, 1)) {
        Serial.println("Unable to find address for Device 2");
      }
    
      // Set resolution to 12 bit (default is 9 bit)
      sensors.setResolution(sensor1Address, 12);
      sensors.setResolution(sensor2Address, 12);
    }
    
    void loop() {
      // Request temperature readings
      sensors.requestTemperatures();
    
      // Read temperatures
      float tempC1 = sensors.getTempC(sensor1Address);
      float tempC2 = sensors.getTempC(sensor2Address);
    
      // Send temperatures over serial
      Serial.print("Sensor1:");
      Serial.print(tempC1);
      Serial.print(",Sensor2:");
      Serial.println(tempC2);
    
      // Wait for 1 minute (60000 milliseconds)
      delay(60000);
    }
    

    Explanation:

    • Setup Function: Initializes serial communication and the sensors. It also retrieves the addresses of the connected DS18B20 devices.
    • Loop Function: Requests temperatures from both sensors, reads them, and sends the readings over the serial port every 60 seconds.

    Part 2: Python Script

    Step 2.1: Install pySerial Library

    You'll need the pyserial library to handle serial communication in Python.

    Install it via pip:

    pip install pyserial
    

    Step 2.2: Write the Python Code

    Create a Python script with the following content:

    import serial
    import time
    
    # Update with your Arduino's serial port (e.g., 'COM3' on Windows or '/dev/ttyACM0' on Linux)
    arduino_port = '/dev/ttyACM0'  # Replace with your port name
    baud_rate = 9600  # Must match Arduino baud rate
    
    # Initialize serial connection
    ser = serial.Serial(arduino_port, baud_rate, timeout=1)
    time.sleep(2)  # Wait for the connection to be established
    
    def read_temperatures():
        while True:
            if ser.in_waiting > 0:
                # Read a line from the serial port
                line = ser.readline().decode('utf-8').rstrip()
                # Parse the line
                if line.startswith('Sensor1:'):
                    try:
                        # Split the line into sensor readings
                        parts = line.split(',')
                        temp1_str = parts[0].split(':')[1]
                        temp2_str = parts[1].split(':')[1]
    
                        # Convert to float
                        temp1 = float(temp1_str)
                        temp2 = float(temp2_str)
    
                        # Print readings
                        print(f"Sensor 1 Temperature: {temp1} °C")
                        print(f"Sensor 2 Temperature: {temp2} °C\n")
    
                    except (IndexError, ValueError) as e:
                        print(f"Error parsing line: {line}")
                        print(e)
                else:
                    print(f"Unexpected line: {line}")
    
            # Sleep briefly to prevent high CPU usage
            time.sleep(0.1)
    
    try:
        read_temperatures()
    except KeyboardInterrupt:
        ser.close()
        print("Serial connection closed.")
    

    Explanation:

    • Serial Connection: Establishes a connection to the Arduino via the specified serial port and baud rate.
    • read_temperatures Function: Continuously reads lines from the serial port, parses the temperature readings, and prints them.
    • Error Handling: Includes basic error handling for unexpected data or parsing errors.

    Note: Replace '/dev/ttyACM0' with the actual serial port your Arduino is connected to. On Windows, it might be something like 'COM3'.

    Step 2.3: Run the Python Script

    Ensure the Arduino is connected and the Arduino IDE serial monitor is closed (to free the serial port). Then run your Python script:

    python your_script_name.py
    

    Additional Notes

    • Synchronization: Since the Arduino sends data every minute, the Python script doesn't need to implement its own timing mechanism. It simply reads data as it becomes available.
    • Modify Timing: If you need to change the interval at which readings are taken, adjust the delay(60000); line in the Arduino code (60000 milliseconds = 1 minute).
    • Data Logging: You can extend the Python script to log data to a file, database, or visualize it in real-time.
    • Multiple Sensors: The provided Arduino code is set up for two sensors. If you have more, you can extend the arrays and loops to accommodate additional devices.

    Troubleshooting

    • Serial Port Issues: If you encounter problems with the serial connection, double-check the port name and ensure no other applications (like the Arduino IDE's serial monitor) are using it.
    • Data Parsing Errors: Make sure the format of the serial output from the Arduino matches what's expected in the Python script. Adjust parsing logic if necessary.
    • Sensor Detection: If the Arduino can't find the sensor addresses, check your wiring and connections.

    By following these steps, you'll have a Python script that reads temperatures from both DS18B20 sensors connected to your Arduino every minute. This setup allows for flexibility in processing and utilizing the temperature data within Python for logging, analysis, or triggering other actions.

    Let me know if you have any questions or need further assistance!