MODBUS write multiple register script

Hello,

How can I write a script for MODBUS to write on multiple register?
Similar to the packet below, but in a scrip.
Screenshot 2025-01-07 171555.png
I have a script for single register but I can't find the field "value" for multiple registers.

Code for single register:

ModbusRtuWritePacket packetWS;
packetWS.initialize();
packetWS.m_adu.m_deviceAddress = addr;
packetWS.m_pdu.m_func = io.ModbusFunc.WriteSingleRegister;
packetWS.m_pdu.m_address = 0x1006;
packetWS.m_pdu.m_value = 0x5501;
packetWS.updateChecksum();
// Transmit the packet
transmit(&packetWS, sizeof(packetWS));

Thanks for your help.

Hello,

ModbusRtuWritePacket is from the legacy Modbus packet template library; it doesn't support multiple values per packet. The new Modbus plugin uses structures defined in scripts/protocols/io_Modbus.jnc. If you need to do it programmatically, just assemble your packet structure from necessary chunks (ADU hdr, PDU hdr, function-specific params, values, CRC). Important -- be sure to add pragma(Alignment, 1) as to avoid unintended struct paddings!

After the packet structure is defined, fill in the fields and calculate the checksum. Modbus RTU checksum is CRC16 ANSI (with init 0xffff) of the whole frame excluding the checksum itself.

The full script listing is below:

import "io_Modbus.jnc"

void main() {
	enum {
		DeviceAddress   = 1,
		RegisterAddress = 0xA000,
		RegisterCount   = 2,
	}

	pragma(Alignment, 1)
	struct MyPacket:
		io.ModbusRtuAduHdr,
		io.ModbusPduHdr,
		io.ModbusWriteMultipleParams {

		bigendian uint16_t m_registers[RegisterCount];
		uint16_t m_crc;
	}

	MyPacket packet;
	packet.m_deviceAddress = DeviceAddress;
	packet.m_func = io.ModbusFunc.WriteMultipleRegisters;
	packet.m_address = RegisterAddress;
	packet.m_count = RegisterCount;
	packet.m_size = sizeof(packet.m_registers);
	packet.m_registers[0] = 123;
	packet.m_registers[1] = 456;
	// ...
	packet.m_crc = crc16_ansi(packet, offsetof(packet.m_crc), -1);

	transmit(packet, sizeof(packet));
}

@vladimir Thanks so much!