ESP8266与python实现UDP通信

ESP8266

#include <ESP8266WiFi.h>
#include <WiFiUdp.h>

const char *ssid = "dsx_zj";     //网络名称
const char *password = "dsxbs725"; //网络密码

WiFiUDP Udp;
unsigned int udpPort = 8080; // 本地端口号
char incomingPacket[537];         // 接收缓冲区

void setup()
{
  //以下为基本功能初始化,初始化串口和网络和LED
  pinMode(2, OUTPUT);
  Serial.begin(115200);
  Serial.println();
  Serial.printf("Connecting to %s ", ssid);
  WiFi.mode(WIFI_STA);
  WiFi.setAutoConnect(false);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED)
  {
    delay(500);
    Serial.print(".");
  }
  Serial.println(" connected");

  //以下开启UDP监听并打印输出信息
  Udp.begin(udpPort);
  Serial.printf("Now listening at IP %s, UDP port %d\n", WiFi.localIP().toString().c_str(), udpPort);
}

void loop()
{
  int packetSize = Udp.parsePacket(); //获取当前队首数据包长度
  if (packetSize)                     // 有数据可用
  {
    Serial.printf("Received %d bytes from %s, port %d\n", packetSize, Udp.remoteIP().toString().c_str(), Udp.remotePort());
    int len = Udp.read(incomingPacket, 536); // 读取数据到incomingPacket
    if (len > 0)                             // 如果正确读取
    {
      incomingPacket[len] = 0; //末尾补0结束字符串
      Serial.printf("UDP packet contents: %s\n", incomingPacket);

      if (strcmp(incomingPacket, "Turn off") == 0) // 如果收到Turn off
      {
        digitalWrite(2, HIGH); // 熄灭LED
        Udp.beginPacket(Udp.remoteIP(), Udp.remotePort());
        Udp.write("LED has been turn off"); // 回复LED has been turn off
        Udp.endPacket();
      }
      else if (strcmp(incomingPacket, "Turn on") == 0) // 如果收到Turn on
      {
        digitalWrite(2, LOW); // 点亮LED
        Udp.beginPacket(Udp.remoteIP(), Udp.remotePort());
        Udp.write("LED has been turn on"); // 回复LED has been turn on
        Udp.endPacket();
      }
      else // 如果非指定消息
      {
        Udp.beginPacket(Udp.remoteIP(), Udp.remotePort());
        Udp.write("Data Error!"); // 回复Data Error!
        Udp.endPacket();
      }
    }
  }
}

python_udp

import socket
import threading
import time
import cv2
import numpy as np


# 向所有客户端发送数据
def send_msg():
    while True:
        try:
            server.sendto("Turn off".encode(), host_esp8266)
            time.sleep(2)
            server.sendto("Turn on".encode(), host_esp8266)
            time.sleep(2)
        except Exception as e:
            try:
                print("Send Error!")
            except Exception as e:
                pass


# 接收客户端的数据
def recv_data():
    while True:
        data, addr = server.recvfrom(package_len)
        print(data)
        print(addr)


package_len = 1420  # 一帧数据长度
server = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
host = ('192.168.0.4', 8080)
host_esp8266 = ('192.168.0.6', 8080)
server.bind(host)
t0 = threading.Thread(target=recv_data)
t0.start()
t1 = threading.Thread(target=send_msg)
t1.start()

  • 0
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
2022 / 01/ 30: 新版esptool 刷micropython固件指令不是 esptool.py cmd... 而是 esptool cmd... 即可;另外rshell 在 >= python 3.10 的时候出错解决方法可以查看:  已于2022年发布的: 第二章:修复rshell在python3.10出错 免费内容: https://edu.csdn.net/course/detail/29666 micropython语法和python3一样,编写起来非常方便。如果你快速入门单片机玩物联网而且像轻松实现各种功能,那绝力推荐使用micropython。方便易懂易学。 同时如果你懂C语音,也可以用C写好函数并编译进micropython固件里然后进入micropython调用(非必须)。 能通过WIFI联网(2.1章),也能通过sim卡使用2G/3G/4G/5G联网(4.5章)。 为实现语音控制,本教程会教大家使用tensorflow利用神经网络训练自己的语音模型并应用。为实现通过网页控制,本教程会教大家linux(debian10 nginx->uwsgi->python3->postgresql)网站前后台入门。为记录单片机传输过来的数据, 本教程会教大家入门数据库。  本教程会通过通俗易懂的比喻来讲解各种原理与思路,并手把手编写程序来实现各项功能。 本教程micropython版本是 2019年6月发布的1.11; 更多内容请看视频列表。  学习这门课程之前你需要至少掌握: 1: python3基础(变量, 循环, 函数, 常用库, 常用方法)。 本视频使用到的零件与淘宝上大致价格:     1: 超声波传感器(3)     2: MAX9814麦克风放大模块(8)     3: DHT22(15)     4: LED(0.1)     5: 8路5V低电平触发继电器(12)     6: HX1838红外接收模块(2)     7:红外发射管(0.1),HX1838红外接收板(1)     other: 电表, 排线, 面包板(2)*2,ESP32(28)  

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值