回到首页 返回首页
回到顶部 回到顶部
返回上一页 返回上一页

空地联防机器人系统:第四课 TT拓展模块实现UDP通信 简单

头像 总督 2021.01.10 570 0

本项目最重要的思想是通过网络通信实现Robomaster TT和Robomaster EP  的空陆联动,本文采用UDP为通信载体,TT在飞行过程中,扩展模块携带的人体红外传感器发现了红外信号后,就通过udp通知控制EP的主机

代码
#说明:这部分是在Arduino上编写的烧录进TT拓展模块的程序

#include <WiFi.h>
#include <WiFiUdp.h> //引用以使用UDP
#include <RMTT_Libs.h>
#include <Wire.h>

const char *ssid = "****";
const char *password = "****";

WiFiUDP Udp;                      //创建UDP对象
unsigned int localUdpPort = 2333; //本地端口号
unsigned int epUdpPort = 8084; //EP控制端端口号
IPAddress ep_IP(192,168,31,51);

RMTT_RGB tt_rgb;  

struct Button {
    const uint8_t PIN;
    uint32_t numberKeyPresses;
    bool pressed;
};

Button button1 = {26, 0, false};


void IRAM_ATTR isr() {
    button1.numberKeyPresses += 1;
    button1.pressed = true;
    tt_rgb.SetRGB(255, 255, 255);
}
void setup()
{
  Serial.begin(115200);
  Serial.println();

  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);
  while (!WiFi.isConnected())
  {
    delay(5000);
    Serial.print(".");
  }
  Serial.println("Connected");
  Serial.print("IP Address:");
  Serial.println(WiFi.localIP());
  
  pinMode(button1.PIN, INPUT_PULLUP);
  attachInterrupt(button1.PIN, isr, RISING);

  tt_rgb.Init();
  tt_rgb.SetRGB(255, 0, 0); 
  
 }

void loop()
{
  if (button1.numberKeyPresses>=3) {        
        button1.numberKeyPresses=0;
        tt_rgb.SetRGB(0, 255, 0); 
        Udp.beginPacket(ep_IP, epUdpPort); //准备发送数据
        Udp.print("hello ep from tt");    //复制数据到发送缓存
        Udp.endPacket();            //发送数据      
    }
   delay(1000);  
}
代码
//说明:这部分是ep控制主机端的python程序(部分)

    udpSocket = socket(AF_INET, SOCK_DGRAM)
    udpSocket.bind(("192.168.31.51", 8084))
    print("hello world!")
    try:
        while True:
            receiveData = udpSocket.recvfrom(1024)
            print(">%s:%s" % (str(receiveData[1]), str(receiveData[0])))
            if receiveData: break
            time.sleep(0.5)
    except:
        udpSocket.close()
        print("BYBY!!!")
project-image

程序说明:当拓展模块检测到三次以上中断发生后(为了避免噪声设置三次),向ep控制端发送hello ep from tt的字符串,同时RGB灯变绿色用以示意udp信号以发出。ep控制端接受到udp信号后就跳出监听循环,开始执行后续动作。

注:由于时间紧张,本次没有对udp信号内容进行分析和利用,只判断了是否接受到了udp信号,后续有待改进

评论

user-avatar