Quantcast
Viewing all articles
Browse latest Browse all 1234

Python • Re: Cant read holding registers from rs485 connection

I need to read holding registers from Bender Isometer that is connected to my raspi via RS-485 connector (no USB adaptor). Isometer is connected, online, its address is set to 4, baudrate is set to 9600 and parity to none. I am using ModbusSerialClient from pymodbus library, but i can't apply its read_holding_registers because i need to toggle pin 6 manually. I am trying to mnaually send a request for holding registers in the following code, but the device doesnt communicate and i have an empty return


import time
import RPi.GPIO as GPIO
from pymodbus.client.sync import ModbusSerialClient as ModbusClient
import logging


logging.basicConfig()
log = logging.getLogger()
log.setLevel(logging.DEBUG)


# GPIO configuration
EN_485 = 6 # GPIO pin to control RS-485 direction
unit_id = 4
start_address = 1003 # Register to read
register_count = 1

GPIO.setmode(GPIO.BCM)
GPIO.setup(EN_485, GPIO.OUT)
GPIO.output(EN_485, GPIO.LOW) # Start with receive mode

ser = ModbusClient(method='rtu', port='/dev/ttyAMA0', baudrate=9600, stopbits=1, timeout=5, bytesize=8, parity='N', retry_on_empty=True)
print(ser )


# Function to control the direction pin for RS-485
def enable_tx():
GPIO.output(EN_485, GPIO.HIGH)
time.sleep(0.01)


def enable_rx():
GPIO.output(EN_485, GPIO.LOW)
time.sleep(0.01)


# Helper function to send and receive Modbus RTU message
def send_modbus_rtu_message(ser, message):

enable_tx() #transmit data

ser.socket.write(bytearray(message))
time.sleep(0.1)

enable_rx()#receive data

# Wait and read the response
time.sleep(1)
response=ser.socket.read(8)
print(f"Received: {response}")



def main():


if not ser.connect():
print("Failed to connect to the Modbus server")
else:

print(f'port name: {ser.is_socket_open()}')
ser.debug_enabled()

try:

message = [0x4, 0x3, 0x3, 0xeb, 0x0, 0x1, 0xf4, 0x2f]

while True:
send_modbus_rtu_message(ser, message)


finally:
ser.close()
GPIO.cleanup()

main()
Hello,
In your code, you have defined enable_tx() and enable_rx() functions to control the direction pin (EN_485). However, you are not calling these functions before and after sending the Modbus RTU message. Modify your code to call enable_tx() before transmitting data and enable_rx() before receiving data.

Statistics: Posted by courtneystah — Tue Jun 04, 2024 3:37 am



Viewing all articles
Browse latest Browse all 1234

Trending Articles