Attached to this post is the entire source code (fn_modbusTcp.c) and a sample illustrating it's use (ModbusTcpTest.c). We have made an effort to make it's usage similar to that of the Moacon RTU slave.
The function that does the vast majority of work is processModbusTcpRequest() in fn_modbusTcp.c. This function will attempt to read a Modbus TCP frame from the Ethernet module's receive buffer, parse it, read or write to the coil and register buffers, and generate a response. It takes a socket, a pointer to register memory, and a pointer to coil memory.
- Code: Select all
void processModbusTcpRequest(u8 socket, u16* registerMemory, u8* coilMemory)
Because connections in TCP/IP are more virtual than physical, some kind of connection management needs to be performed in software. In the attached example you can see this connection management in doModbusTcp() in ModbusTcpTest.c.
- Code: Select all
void doModbusTcp(u8 socket, u16 port, u16* registerMemory, u8* coilMemory)
{
switch(netStatus(socket))
{
case SOCK_CLOSED:
//Open socket if closed
socketOpen(socket, port);
break;
case SOCK_INIT:
//Start listening if socket is open
listen(socket);
break;
case SOCK_ESTABLISHED:
//process any modbus TCP requests if client is connected
processModbusTcpRequest(socket, registerMemory, coilMemory);
break;
}
}
The Ethernet module does not provide a receive interrupt to listen for, so you'll have to service the Modbus TCP slave in a timer, or in a never-ending loop. In the attached example we have chosen the latter.
- Code: Select all
void cmain(void)
{
//Network Settings
u8 gatewayIP[]={192,168,0,2};
u8 subnetMask[]={255,255,255,0};
u8 macAdr[]={0,0,34,53,12,0};
u8 moaconIp[]={192,168,0,12};
netBegin(gatewayIP, subnetMask, macAdr, moaconIp);
//Modbus Settings
u8 socket = 0;
u16 port = 502;
static u8 coilMemory[8];
static u16 registerMemory[8];
//make sure the socket is closed before starting
disConnect(socket);
socketClose(socket);
//Continually poll the socket to process modbus TCP requests
while(1)
{
doModbusTcp(socket, port, registerMemory, coilMemory);
}
}
To use, choose "Project" --> "Add Files to Project..." in Moacon Studio, and add fn_modbusTcp.c to your project.