w5500 modbustcp例程
时间: 2023-12-02 07:42:41 浏览: 152
modbusTcp例子
以下是W5500模块实现Modbus/TCP协议的例程:
```c
#include <stdio.h>
#include <string.h>
#include "stm32f10x.h"
#include "w5500.h"
#include "socket.h"
#define ETH_MAX_BUF_SIZE 2048
uint8_t ethBuf0[ETH_MAX_BUF_SIZE];
uint8_t ethBuf1[ETH_MAX_BUF_SIZE];
uint8_t macAddr[6] = {0x00, 0x08, 0xdc, 0xab, 0xcd, 0xef};
uint8_t ipAddr[4] = {192, 168, 1, 100};
uint8_t gwAddr[4] = {192, 168, 1, 1};
uint8_t snMask[4] = {255, 255, 255, 0};
uint16_t modbusTcpPort = 502;
uint8_t modbusTcpBuf[ETH_MAX_BUF_SIZE];
void initW5500(void)
{
uint8_t tmp[2];
W5500_Init();
W5500_SetMACAddress(macAddr);
W5500_SetIPAddress(ipAddr);
W5500_SetGatewayAddress(gwAddr);
W5500_SetSubnetMask(snMask);
W5500_GetGatewayAddress(tmp);
printf("Gateway Address: %d.%d.%d.%d\n", tmp[0], tmp[1], tmp[2], tmp[3]);
W5500_GetSubnetMask(tmp);
printf("Subnet Mask: %d.%d.%d.%d\n", tmp[0], tmp[1], tmp[2], tmp[3]);
}
void modbusTcpServer(void)
{
uint8_t socket0, socket1;
uint16_t len;
uint16_t i;
socket0 = socket(0, Sn_MR_TCP, modbusTcpPort, 0);
listen(socket0);
while (1)
{
if (getSn_SR(socket0) == SOCK_ESTABLISHED)
{
len = getSn_RX_RSR(socket0);
if (len > 0)
{
if (len > ETH_MAX_BUF_SIZE)
{
len = ETH_MAX_BUF_SIZE;
}
recv(socket0, ethBuf0, len);
memcpy(modbusTcpBuf, ethBuf0, len);
// Modbus/TCP protocol processing
// ...
send(socket0, modbusTcpBuf, len);
}
}
}
}
int main(void)
{
initW5500();
modbusTcpServer();
return 0;
}
```
阅读全文