首页 > 解决方案 > 通过以太网、IP 进行简单的 Arduino 客户端服务器通信

问题描述

两个 Arduino 板之间的简单以太网通信。我使用了两个 Arduino UNO 板,两个 Arduino 以太网扩展板。

这是我的服务器代码

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

// network configuration.  gateway and subnet are optional.

 // the media access control (ethernet hardware) address for the shield:
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };  
//the IP address for the shield:
byte ip[] = { 192,168,1,180 };    
// the router's gateway address:
byte gateway[] = { 192, 168, 1, 1 };
// the subnet:
byte subnet[] = { 255, 255, 255, 0 };


EthernetServer server = EthernetServer(10001);

void setup()
{
  // initialize the ethernet device
  Ethernet.begin(mac, ip, gateway, subnet);

  // start listening for clients
  server.begin();

}

void loop()
{
  // if an incoming client connects, there will be bytes available to read:
  EthernetClient client = server.available();
  if (client == true) {
    // read bytes from the incoming client and write them back
    // to any clients connected to the server:
    server.write(client.read());
  }
}

这是我的客户代码

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


byte mac[] = {0xDE,0xAD,0xBE,0xEF,0xFE,0xEC};
IPAddress ip(192,168,1,177);
IPAddress server(192,168,1,180);

EthernetClient client(10001);

void setup()
{

  Ethernet.begin(mac, ip);
  Serial.begin(9600);
  delay(1000);

  Serial.println("connecting...");

  if (client.connect(server, 10001)) {
    Serial.println("connected");
    client.println("GET /search?q=arduino HTTP/1.0");
    client.println();
  } else {
    Serial.println("connection failed");
  }
}

void loop()
{
  if (client.available()) {
    char c = client.read();
    Serial.print(c);
  }

  if (!client.connected()) {
    Serial.println();
    Serial.println("disconnecting.");
    client.stop();
    for(;;)
      ;
  }
}

我将这两个代码输入到两个 Arduino 板上。接线及其他连接正确可靠。但我从客户端串行监视器得到了这个输出

connecting...
connection failed

disconnecting.

根据我的观点,客户端代码中可能会发生错误。你能帮我找出错误吗?

标签: tcparduinoclient-serverethernet

解决方案


推荐阅读