首页 > 解决方案 > Arduino 和 Python 之间通过 UDP 进行通信

问题描述

我正在努力在 Arduino 和 Python 之间建立沟通桥梁。Arduino 应该向 python 发送一个整数值。为了启用 Udp 通信,我在 Arduino 上使用以太网屏蔽 2,并且必须连接到 IP“192.168.137.30”。现在,当我尝试连接以绑定此 IP 地址时,会发生错误,因为“192.168.137.30”是外部 IP 地址。

下面是我的 Arduino 和 python 代码:

#include <SPI.h>
#include <SD.h>
#include <Ethernet2.h>
#include <EthernetUdp2.h>         // UDP library from: bjoern@cs.stanford.edu 12/30/2008

byte mac[] = {
  0xA8, 0x61, 0x0A, 0xAE, 0x2A, 0x12
};
IPAddress ip(192.168.137.30);

unsigned int localPort = 8880;      // local port to listen on

// An EthernetUDP instance to let us send and receive packets over UDP
EthernetUDP Udp;


void setup()
{


  Ethernet.begin(mac, ip);
  Udp.begin(localPort);
  Serial.begin(115200);

  }

void loop()
{

   char  ReplyBuffer[] = "acknowledged";    
    Udp.beginPacket(ip, localPort);
    Udp.write(ReplyBuffer);
    Udp.endPacket();

}

Python :

import serial
import time 
import socket

sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind(('192.168.137.30', 8880))
data, addr = sock.recvfrom(1024) # buffer size is 1024 bytes
sock.close()

我仍然无法将数据从 Arduino 发送到 Python。但是,可以将数据从 Python 发送到 Arduino。

IPAddress ip(169, 254, 114, 130);
IPAddress my_PC_ip(169, 254, 94, 133);
unsigned int localPort = 7476; 
unsigned int pythonPort= 7000; 

void setup()
{
  Ethernet.begin(mac, ip);
  Udp.begin(localPort);
  Serial.begin(115200);

  }

void loop()
{
    Udp.beginPacket(my_PC_ip,pythonPort);
    Udp.print("hello");
    Udp.endPacket();
}

Python:导入串行导入时间导入套接字

sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind(('169.254.94.133', 7000))
data, addr = sock.recvfrom(1024) # buffer size is 1024 bytes
sock.close()

标签: pythonarduinoudp

解决方案


您没有将正确的 IP 地址放在正确的位置。这是应该在哪里:

  • Ethernet.beginArduino 上,您应该使用 Arduino 的 IP 地址。
  • Udp.beginPacketArduino 上,您应该使用计算机的 IP 地址。
  • sock.bind您的计算机上,您应该使用计算机的 IP 地址。

您目前在所有三个地方都使用同一个,这从网络的角度来看是没有意义的。


推荐阅读