I am trying to connect a Turbidity sensor that operates using Modbus to a Raspberry Pi. The sensor is an industrial-grade device and comes with the needed communication protocols (http://www.sonbus.com/upload/pdf/XM8518.pdf). I connected to Raspberry Pi to a Waveshare RS485 (https://thepihut.com/products/rs485-board) module, which was then connected to the Turbidity sensor. The connections are given in the diagram below.
I've also added an image of the setup for reference.
The code I used is given below. I tried minimalmodbus here.
import serial
import minimalmodbus
import RPi.GPIO as GPIO
import time
RSE_PIN = 18
GPIO.setmode(GPIO.BCM)
GPIO.setup(RSE_PIN, GPIO.OUT)
instrument = minimalmodbus.Instrument('/dev/ttyS0', 1)
instrument.serial.baudrate = 9600
instrument.serial.bytesize = 8
instrument.serial.parity = serial.PARITY_NONE
instrument.serial.stopbits = 1
instrument.serial.timeout = 0.5
instrument.mode = minimalmodbus.MODE_RTU
def read_turbidity():
try:
GPIO.output(RSE_PIN, GPIO.HIGH)
time.sleep(0.02)
raw_value = instrument.read_register(0, 3) # registeraddress, functioncode
GPIO.output(RSE_PIN, GPIO.LOW)
turbidity_value = raw_value / 100.0
print(f"Raw Value (decimal): {raw_value}")
print(f"Turbidity Value: {turbidity_value} UNT")
except IOError as e:
print(f"Failed to read from sensor: {e}")
GPIO.output(RSE_PIN, GPIO.LOW)
except Exception as e:
print(f"An unexpected error occurred: {e}")
GPIO.output(RSE_PIN, GPIO.LOW)
if __name__ == "__main__":
try:
print("Starting turbidity sensor reading. Press Ctrl+C to stop.")
while True:
read_turbidity()
time.sleep(5)
except KeyboardInterrupt:
print("Reading stopped by user.")
finally:
GPIO.cleanup()
print("GPIO cleanup complete.")
Problem is, my device is not giving back any response at all. I am getting an IOError. I've done the usual checks, I tried connected my TX directly to RX to see whether I am getting back a response and that works fine. I also tried switching A and B around to no avail. Is there something I need to change in my code or wiring? I would appreciate any help.


