python - 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()
解决方案
您没有将正确的 IP 地址放在正确的位置。这是应该在哪里:
- 在
Ethernet.begin
Arduino 上,您应该使用 Arduino 的 IP 地址。 - 在
Udp.beginPacket
Arduino 上,您应该使用计算机的 IP 地址。 - 在
sock.bind
您的计算机上,您应该使用计算机的 IP 地址。
您目前在所有三个地方都使用同一个,这从网络的角度来看是没有意义的。
推荐阅读
- c# - 如何使用 c# 使用 twilio 将 WhatsApp 消息发送到任何号码
- flutter - Dart Analyzer 的排除选项无法正常工作
- python - GeoPandas .to_crs() 方法未转换
- excel - Excel VBA:查找值并仅粘贴颜色(没有颜色的问题)
- javascript - 使用动态键重塑 mongodb 聚合结果
- java - 如何在 DOM Transformer 中禁用换行符和缩进?
- netsuite - 工作流总和 2 个字段值
- python - 读取 RFID_Present 作为字符串对 .txt 文件
- c++ - 为什么结构化绑定不会与变量发生潜在冲突
- asp.net-web-api2 - 如何在 WebApi 2 中登录 Alexa Linked Account?