20210616-esp8266-udp

1/第三参数用于led或继电器作为开关状态
用于马达或调光led 时可与第二参数联动
2/第二参数为设备操作接口名称
可以作为pwm脉宽指令
3/操作函数,直接判断第二参数进行对应操作,可无限扩展

在这里插入图片描述
在这里插入图片描述
检查开关指令,将第二参数—开关名称传递给操作函数(马达/led/继电器)且可扩展操作描述

esp8266wifi.h        wifi 接口
wifiudp.h            udp 包处理

人家例程 原文零智

#include <ESP8266WiFi.h>
#include <WiFiUDP.h>
#define PIN_LED 11//定义继电器gpio
unsigned int UDPPort = 8888;      // local port to listen on

char packetBuffer[255]; //buffer to hold incoming packet
char  ReplyBuffer[] = "acknowledged";       // a string to send back
WiFiUDP Udp;

// 复位或上电后运行一次:
void setup() {
    //在这里加入初始化相关代码,只运行一次:
    Serial.begin(115200);
     
    WiFi.softAP("Wi-Fi");
    Udp.begin(UDPPort);
    Serial.println();
    Serial.println("Started ap. Local ip: " +    WiFi.localIP().toString());
      pinMode(PIN_LED, OUTPUT); //初始化PIN_LED引脚模式为输出
        digitalWrite(PIN_LED,HIGH);//上电低电平,按实际改

}

//一直循环执行:
void loop() {
    // 在这里加入主要程序代码,重复执行:
    // if there's data available, read a packet
    int packetSize = Udp.parsePacket();
    if (packetSize) {
            Serial.print("Received packet of size ");
            Serial.println(packetSize);
            Serial.print("From ");
            IPAddress remoteIp = Udp.remoteIP();
            Serial.print(remoteIp);
            Serial.print(", port ");
            Serial.println(Udp.remotePort());
             
            // read the packet into packetBufffer
            int len = Udp.read(packetBuffer, 255);
            if (len > 0) {
                    packetBuffer[len] = 0;  //末位结束符
                    //处理包头包尾协议
                     if(packetBuffer[0] == ’0xaa’ && packetBuffer[1] == ’0x66’)
                     {
                     
                   //检查 gpio指令 开关gpio
                 digitalWrite(PIN_LED, LOW);

                   //延时1秒 gpio 开关状态取反
                   delay(1000)
                     digitalWrite(PIN_LED, HIGH);  
                     }

            }
            Serial.println("Contents:");
            Serial.println(packetBuffer);
            // send a reply, to the IP address and port that sent us the packet we received
            Udp.beginPacket(Udp.remoteIP(), Udp.remotePort());
            Udp.write(ReplyBuffer);
            Udp.endPacket();
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值