Python Modbus TCP client library for pico

Does anyone know a good library supporting Modbus TCP client mode for the pico in python? I have implemented a client that writes values to a server based on joystick movements. This is the code I wrote:

import pygame
import pymodbus
from pymodbus.client import ModbusTcpClient

# Initialize pygame and the joystick

joystick_count = pygame.joystick.get_count()
print(f'[+] {joystick_count} joystick(s) found!')
joystick = pygame.joystick.Joystick(0)

# Create a Modbus TCP client
client = ModbusTcpClient('')
while True:
    # Poll the joystick for events
    for event in pygame.event.get():
        if event.type == pygame.JOYHATMOTION:
            # Get the joystick axis and value
            # Handle joyhatmotion UP event
            if event.value[1] == 1:
                client.write_registers(0x1, 2)
                print('[+] UP Event Handled')
            # Handle joyhatmotion DOWN event
            if event.value[1] == -1:
                client.write_registers(0x1, 8)
                print('[+] DOWN Event Handled')
            # Handle joyhatmotion LEFT event
            if event.value[0] == -1:
                client.write_registers(0x1, 4)
                print('[+] LEFT Event Handled')
            # Handle joyhatmotion RIGHT event
            if event.value[0] == 1:
                client.write_registers(0x1, 6)
                print('[+] RIGHT Event Handled')
            # Handle joyhatmotion NEUTRAL POSITION event
            if event.value == (0,0):
                client.write_registers(0x1, 0)
        elif event.type == pygame.JOYBUTTONDOWN:
            # Handle joyhatmotion RIGHT TRIGGER event
            if event.button == 5:
                client.write_registers(0x1, 6842)
                print('[+] RIGHT TRIGGER Event Handled')
            # Handle joyhatmotion LEFT TRIGGER event
            if event.button == 4:
                client.write_registers(0x1, 6248)
                print('[+] LEFT TRIGGER Event Handled')
        elif event.type == pygame.JOYBUTTONUP:
            client.write_registers(0x1, 0)
# Close the Modbus TCP client when the program is finished

For instance, I have tried GitHub - brainelectronics/micropython-modbus: Micropython Modbus RTU Slave/Master and TCP Server/Slave library but it doesn’t seem to provide a simple way to connect to the
Modbus master device by IP and issue a read register command.

Any help would be greatly appreciated.



1 Like

Hi Ricardo,

I haven’t implemented TCP (Modbus-TCP) on a microcontroller before, but my instincts say you might want to find a MODBUS-RTU implementation for the pico, and use a TCP gateway if you can’t find a native client for the Pico W.

I’m only just getting into Modbus myself, and I can say that writing a port is not too easy, though I constrained myself by choosing a chip with flash too small (2K).