Lyubov Denissova
Lyubov Denissova

Reputation: 1

read messages from RS-485 device connected to raspberry pi

i have a RS-485 device connected to my raspi without a USB adapter. Its datasheet says that all data can be read through holding registers, so I am using ModbusSerialClient from pymodbus library. But as far as i understand i need to manually toggle rx-tx switch on raspi and read_holding_registers function doesn't do it of course. What is the correct approach ?

In testing purposes I am trying to send a request message manually but it doesn't seem to work and device doesn't communicate, even though it is online and is configured correctly. What am i doing wrong? This code returns empty messages just like if i use read_holding_registers() function

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 )


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)


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()

Upvotes: 0

Views: 299

Answers (0)

Related Questions