通过以太网,IP的简单Arduino客户端服务器通信

问题描述 投票:0回答:1

两个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.

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

tcp arduino client-server ethernet
1个回答
0
投票

首先尝试分配两个不同的MAC地址。然后将这两个示例代码与您的代码进行比较:

WebServerWebClient

© www.soinside.com 2019 - 2024. All rights reserved.