使用arduino客户端/ python服务器通过以太网转储数据

时间:2013-11-07 18:20:16

标签: python client-server arduino

我正在使用arduino以太网来读取数据传感器,然后想要将数据发送到另一个建筑物中的计算机以驱动一个python软件中的逻辑/控制。我决定在python / arduino中绘制一个简单的草图,它只是通过以太网将arduino中的文本发送到我的python程序:

arduino客户端代码主要来自EthernetClient示例:

#include <SPI.h>
#include <Ethernet.h>

byte mac[] = {0x90, 0xA2, 0xDA, 0x0E, 0x40, 0x9F};
byte ip[] = {192, 168, 0, 172};
byte server[] = {192,168,0,17};
int port = 1700;

EthernetClient client;

void setup() {
  Serial.begin(9600);
  while (!Serial) {
    ;
  }

  Ethernet.begin(mac, ip);
  delay(1000);
  Serial.println("connecting...");

  // if you get a connection, report back via serial:
  if (client.connect(server, port)) {
    Serial.println("connected.");
    //print text to the server
    client.println("This is a request from the client.");
  } 
  else {
    // if you didn't get a connection to the server:
    Serial.println("connection failed");
  }
}

void loop()
{
  // if there are incoming bytes available 
  // from the server, read them and print them:
  if (client.available()) {
    char c = client.read();
    Serial.print(c);
  }

  // if the server's disconnected, stop the client:
  if (!client.connected()) {
    Serial.println();
    Serial.println("disconnecting.");
    client.stop();

    // do nothing forevermore:
    while(true);
  }
}

然后是我的python代码:

import socket

host = ''
port = 1700
address = (host, port)

server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind((address))
server_socket.listen(5)

print "Listening for client . . ."

conn, address = server_socket.accept()

print "Connected to client at ", address

//pick a large output buffer size because i don't necessarily know how big the incoming packet is
output = conn.recv(2048);
print "Message received from client:"
print output

conn.send("This is a response from the server.")
conn.close()

print "Test message sent and connection closed."

服务器的响应是我所期望的:

Listening for client . . .
Connected to client at  ('192.168.0.172', 1025)
Message received from client:
This is a request from the client.
Test message sent and connection closed.

但客户收到:

connecting...
connected.
This
disconnecting.

似乎停止在流后从我的服务器接收文本。那是为什么?

另一个问题:为什么我要求我的arduino连接端口1700,但是python声称它正在接收来自端口1025的请求?

谢谢!

0 个答案:

没有答案