arduino与python通过udp通信(测试通过 初级简单)
本帖最后由 zhaopengxslc 于 2014-9-10 20:31 编辑Arduino代码
/*
UDPSendReceive.pde:
This sketch receives UDP message strings, prints them to the serial port
and sends an "acknowledge" string back to the sender
A Processing sketch is included at the end of file that can be used to send
and received messages for testing with a computer.
created 21 Aug 2010
by Michael Margolis
This code is in the public domain.
*/
#include <SPI.h> // needed for Arduino versions later than 0018
#include <Ethernet.h>
#include <EthernetUdp.h> // UDP library from: [email protected] 12/30/2008
// Enter a MAC address and IP address for your controller below.
// The IP address will be dependent on your local network:
byte mac[] = {
0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
IPAddress ip(192, 168, 2, 177);
unsigned int localPort = 8000; // local port to listen on
// buffers for receiving and sending data
char packetBuffer; //buffer to hold incoming packet,
charReplyBuffer[] = "acknowledged"; // a string to send back
// An EthernetUDP instance to let us send and receive packets over UDP
EthernetUDP Udp;
void setup() {
// start the Ethernet and UDP:
Ethernet.begin(mac,ip);
Udp.begin(localPort);
Serial.begin(9600);
}
void loop() {
// if there's data available, read a packet
int packetSize = Udp.parsePacket();
if(packetSize)
{
Serial.print("Received packet of size ");
Serial.println(packetSize);
Serial.print("From ");
IPAddress remote = Udp.remoteIP();
for (int i =0; i < 4; i++)
{
Serial.print(remote, DEC);
if (i < 3)
{
Serial.print(".");
}
}
Serial.print(", port ");
Serial.println(Udp.remotePort());
// read the packet into packetBufffer
Udp.read(packetBuffer,UDP_TX_PACKET_MAX_SIZE);
Serial.println("Contents:");
Serial.println(packetBuffer);
memset(packetBuffer,'\0',UDP_TX_PACKET_MAX_SIZE);
// send a reply, to the IP address and port that sent us the packet we received
Udp.beginPacket(Udp.remoteIP(),Udp.remotePort());
Udp.write(ReplyBuffer);
Udp.endPacket();
}
delay(10);
}
python代码
from socket import *
HOST="192.168.2.177"
PORT=8000
BUFSIZE=1024
ADDR=(HOST,PORT)
udpCliSock=socket(AF_INET,SOCK_DGRAM)
while True:
data=raw_input(">")
if not data:
break
udpCliSock.sendto(data,ADDR)
data,ADDR=udpCliSock.recvfrom(BUFSIZE)
if not data:
break
print data,ADDR
udpCliSock.close()
说明:
arduino作为UDP服务器
python作为UDP客户端
页:
[1]