Comment pouvons-nous aider ?
HMI script that uses the Modbus FC06 function to write only the LW registers in the ACE PLC
Only these parameters to be completed at the end of the script:
int PortID = 0; // com1:0 com2:1
unsigned char slaveAddr = 1; // Remote device address (adjust as needed)
unsigned short startRegAddr = 0; // Starting register address (adjust as needed)
int numRegs = 10; // Number of registers to write
#include "MacroInit.h"
#include
// Modbus CRC16 calculation
unsigned short CalculCRC16(unsigned char *data, int len)
{
unsigned short crc = 0xFFFF;
int i, j;
for (i = 0; i < len; i++)
{
crc ^= data[i];
for (j = 0; j < 8; j++) { if (crc & 0x0001) crc = (crc >> 1) ^ 0xA001;
else
crc = crc >> 1;
}
}
return crc;
}
// Function to send Modbus Write Multiple Registers command (FC 16)
void ModbusWriteMultipleRegisters(unsigned char slaveAddr, unsigned short startRegAddr,
unsigned short *registers, int numRegs, int portID)
{
unsigned char frame[256];
unsigned short crc;
int byteCount = numRegs * 2;
int frameLen;
int i;
// Modbus RTU frame construction
frame[0] = slaveAddr; // Slave address
frame[1] = 0x10; // Function code 16 (Write Multiple Registers)
frame[2] = (startRegAddr >> 8) & 0xFF; // Starting register address (MSB)
frame[3] = startRegAddr & 0xFF; // Starting register address (LSB)
frame[4] = (numRegs >> 8) & 0xFF; // Number of registers (MSB)
frame[5] = numRegs & 0xFF; // Number of registers (LSB)
frame[6] = byteCount; // Byte count
// Add register values (Big Endian)
for (i = 0; i < numRegs; i++) { frame[7 + (i * 2)] = (registers[i] >> 8) & 0xFF; // MSB
frame[8 + (i * 2)] = registers[i] & 0xFF; // LSB
}
// Calculate total frame length before CRC
frameLen = 7 + byteCount;
// CRC16 calculation
crc = CalculCRC16(frame, frameLen);
frame[frameLen] = crc & 0xFF; // CRC (LSB)
frame[frameLen + 1] = (crc >> 8) & 0xFF; // CRC (MSB)
// Send frame over serial port
PUTCHARS(portID, frame, frameLen + 2);
}
// SEND BUTTON - Write registers LocalWord[0] to LocalWord[9]
void Macro_main(IN *p)
{
MarcoInit
int PortID = 0; // com1:0 com2:1
unsigned char slaveAddr = 1; // Remote device address (adjust as needed)
unsigned short startRegAddr = 0; // Starting register address (adjust as needed)
int numRegs = 10; // Number of registers to write
// Write "numRegs" registers in a single frame
ModbusWriteMultipleRegisters(slaveAddr, startRegAddr, &LocalWord[0], numRegs, PortID);
LocalBit[16] = 0; // End of transmission
}