Page 1 of 1

Modbus on ESP32

Posted: Fri Oct 02, 2020 7:23 am
by Duality
Hi all,

I am new to Modbus on RS485 and trying to build Micropython code for Modbus RTU slave and master. I have gone through pycom modbus library and tried it. However, I couldnt get any success. I feel that there might be some issue in my connections. So I want to get some expert advice from you all.
My connections are:
Esp32 (tx=17, rx=16, 3.3v, GND and GPIO4 - as RTS) :arrow: SP3485 (breakout board from Sparkfun) :arrow: Connected to PC through a USB to RS485 converter.

My PC is running the slave and master simulator as and when needed. I have built my own code as well (inspired from pycom modbus library). This is given below:

from machine import UART
import functions
import machine, time
import const
# 16bit CRC -> 8 byte: addr, fc, 00,register_addr,00,number of registers to read,CRC LSB, CRC MSB

#setup serial connection
def send_receive(pdu):
ctrl_pin.value(1)
time.sleep(0.01)
uart.write(pdu)
while True:
ctrl_pin.value(0)
time.sleep(0.01)
print('received: ', uart.read())
time.sleep(0.1)

def create_req_pdu(slave_addr,fc,register_addr, register_count):
pdu = bytearray()
pdu.append(slave_addr)
pdu.append(fc)
pdu.append(0x00)
pdu.append(register_addr)
pdu.append(0x00)

pdu.append(register_count)
pdu.extend(functions.calculate_crc16(pdu))
print('request pdu: ', pdu)
return pdu

def get_request_pdu():
ctrl_pin.value(0)
while True:
req = uart.read()
print('req: ')
time.sleep(0.5)

uart = UART(1,tx=17,rx=16,baudrate=9600,parity=None,stop=1)
ctrl_pin = machine.Pin(4,machine.Pin.OUT)

slave_addr=0x01
fc=const.READ_HOLDING_REGISTERS
register_addr=0x00
register_count = 0x0A
send_receive(create_req_pdu(slave_addr,fc,register_addr,register_count))


What am I missing here?

Thanks and regards.

Re: Modbus on ESP32

Posted: Tue Oct 06, 2020 5:53 am
by Duality
It work now! :)
I checked with the oscilloscope and saw that the transmission voltage levels were very weak. I changed the MAX485 and now, it is working great. Although, now I have run into other issues. :|

Thanks

Re: Modbus on ESP32

Posted: Tue May 18, 2021 5:28 am
by chiasang
Same issue I have, I know the const lib in your code, could you tell me about the lib name of const. or how to read holdingregisters,thx

Re: Modbus on ESP32

Posted: Tue Jun 08, 2021 10:59 pm
by BetterAutomations
chiasang wrote:
Tue May 18, 2021 5:28 am
Same issue I have, I know the const lib in your code, could you tell me about the lib name of const. or how to read holdingregisters,thx
I'm going to attempt an answer even though I've never used Duality's library. I'm guessing const is just a file with constants in it. Something like this.

Code: Select all

# const.py
# This value is entirely guessed, just for an example
READ_HOLDING_REGISTERS=0xFFF