【发布时间】:2019-03-11 01:25:10
【问题描述】:
我正在努力在 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()
【问题讨论】: