一、实现功能
1、创建串口连接,将接收的Udp数据通过串口发送出去。
2、创建Udp连接,用以接收Udp数据和对发送数据的Udp机器反馈Udp数据
3、对接收到的Udp数据进行解析,然后对8路IO进行输出控制。
4、'1'对应IO输出低电平,‘0’对应IO输出高电平。
(0,1是串口1。10、11引脚无法控制,不知道什么原因)
二、代码
#include <string.h>
#include <Ethernet.h>
#include <EthernetUdp.h>//8路IO输出控制:$1,0,0,0,0,0,0,0%
char OutsCmd[13]; //输出控制EthernetUDP Udp;
char packetBuffer[UDP_TX_PACKET_MAX_SIZE]; // 用于保存读取的Udp数据包的缓冲区
char ReplyBuffer[] = "Received,Over"; // 本机Udp给发送信息的Udp发送字符串//定义单片机本地Mac、IP地址和端口号
byte localMac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED};
IPAddress localIp(192, 168, 1, 177);
unsigned int localPort = 9999;void setup()
{//IO引脚:2-9输出控制for(int i=2;i<10;i++){pinMode(i,OUTPUT);delay(10); digitalWrite(i, LOW); //初始,低电平delay(10); }//网口 Ethernet.begin(localMac, localIp);//打开串口Serial.begin(9600);while (!Serial) {; //等待串口连接。仅本机USB口使用。}//检查以太网硬件情况if(Ethernet.hardwareStatus() == EthernetNoHardware) //检查W5500模块是否存在{Serial.println("Ethernet shield was not found. Sorry, can't run without hardware. :(");while (true) {delay(1); // do nothing, no point running without Ethernet hardware}} if(Ethernet.linkStatus() == LinkOFF) //检查网口是否连接{Serial.println("Ethernet cable is not connected.");} //启动UDPUdp.begin(localPort);
}void loop()
{int packetSize = Udp.parsePacket(); //Udp接收到的数据长度if(packetSize>0){//给串口发送,Udp接收的数据Serial.print("Received packet of size "); Serial.println(packetSize); //串口打印,Udp接收到的数据长度Serial.print("From ");IPAddress remote = Udp.remoteIP(); //串口打印,发送消息Udp的ip地址、端口号for (int i=0; i < 4; i++) //ip地址{Serial.print(remote[i], DEC);if (i < 3) {Serial.print(".");}}Serial.print(", port "); Serial.println(Udp.remotePort()); //端口号//将Udp接收到的消息,通过串口打印出来Udp.read(packetBuffer, UDP_TX_PACKET_MAX_SIZE); //Udp接收到的字符串消息Serial.println("Udp Message:");Serial.println(packetBuffer);//本机,给发送消息的Udp机器发送反馈消息Udp.beginPacket(Udp.remoteIP(), Udp.remotePort());Udp.write(ReplyBuffer);Udp.endPacket(); //8路IO输出控制:$1,0,0,0,0,0,0,0%if(packetBuffer[0]=='$'){OutsCmd[0]=packetBuffer[1];OutsCmd[1]=packetBuffer[3];OutsCmd[2]=packetBuffer[5];OutsCmd[3]=packetBuffer[7];OutsCmd[4]=packetBuffer[9];OutsCmd[5]=packetBuffer[11];OutsCmd[6]=packetBuffer[13];OutsCmd[7]=packetBuffer[15];//IO引脚:2-9输出控制for(int i=0;i<8;i++){if(OutsCmd[i]=='1'){digitalWrite(i+2, HIGH);}if(OutsCmd[i]=='0'){digitalWrite(i+2, LOW);}}}//使用memset函数将字符串数组清零memset(packetBuffer, '\0', sizeof(packetBuffer)); memset(OutsCmd, '\0', sizeof(OutsCmd));}delay(10);
}
三、测试
1、第一路、第三路输出
2、第一路、第二路、第三路输出