Arduinoのネットワーク通信

固定IPアドレスを割り当てる

サーバー用途で使うときは固定IPにした方が楽です。
固定IPアドレスを割り当てるスケッチは以下の様になります。
注意点として、ENC28J60もW5100も固定IPアドレスを使う場合、Ethernet.begin()はvoid型になります。
int型の関数として使うとコンパイルエラーとなります。
正しくIPが取れたかどうかを判定するコードは以下の様になります。

ENC28J60のスケッチ
/*
 * ENC28J60/W5100 Ethernet Module example.
 */

#include <UIPEthernet.h> // https://github.com/UIPEthernet/UIPEthernet
//#include <SPI.h>
//#include <Ethernet.h>

EthernetClient client;

void setup() {
  byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
  IPAddress myIP(192,168,10,190);
   
  Serial.begin(9600);
  Serial.print("Ethernet begin....");
  Ethernet.begin(mac,myIP);
//  int ret = Ethernet.begin(mac);
//  Serial.println("ret =" + String(ret));

  for (byte thisByte = 0; thisByte < 4; thisByte++) {
    // print the value of each byte of the IP address:
//    Serial.println(Ethernet.localIP()[thisByte]);
    if (Ethernet.localIP()[thisByte] != myIP[thisByte] ) {
      Serial.println("fail....");
      while (1) {}
    }
  }

  Serial.println("ok....");
  Serial.print("localIP: ");
  Serial.println(Ethernet.localIP());
  Serial.print("subnetMask: ");
  Serial.println(Ethernet.subnetMask());
  Serial.print("gatewayIP: ");
  Serial.println(Ethernet.gatewayIP());
  Serial.print("dnsServerIP: ");
  Serial.println(Ethernet.dnsServerIP());

  for (byte thisByte = 0; thisByte < 4; thisByte++) {
    // print the value of each byte of the IP address:
    Serial.print(Ethernet.localIP()[thisByte], DEC);
    Serial.print("-");
  }
  Serial.println("");
}

void loop() {
}



W5100のスケッチ
/*
 * ENC28J60/W5100 Ethernet Module example.
 */

//#include <UIPEthernet.h> // https://github.com/UIPEthernet/UIPEthernet
#include <SPI.h>
#include <Ethernet.h>

EthernetClient client;

void setup() {
  byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
  IPAddress myIP(192,168,10,78);
  
  Serial.begin(9600);
  Serial.print("Ethernet begin....");
  Ethernet.begin(mac,myIP);
//  int ret = Ethernet.begin(mac);
//  Serial.println("ret =" + String(ret));

  for (byte thisByte = 0; thisByte < 4; thisByte++) {
    // print the value of each byte of the IP address:
//    Serial.println(Ethernet.localIP()[thisByte]);
    if (Ethernet.localIP()[thisByte] != myIP[thisByte] ) {
      Serial.println("fail....");
      while (1) {}
    }
  }

  Serial.println("ok....");
  Serial.print("localIP: ");
  Serial.println(Ethernet.localIP());
  Serial.print("subnetMask: ");
  Serial.println(Ethernet.subnetMask());
  Serial.print("gatewayIP: ");
  Serial.println(Ethernet.gatewayIP());
  Serial.print("dnsServerIP: ");
  Serial.println(Ethernet.dnsServerIP());

  for (byte thisByte = 0; thisByte < 4; thisByte++) {
    // print the value of each byte of the IP address:
    Serial.print(Ethernet.localIP()[thisByte], DEC);
    Serial.print("-");
  }
  Serial.println("");
}

void loop() {
}

次回は、ネットワーク通信の基本となるSocket通信を紹介します。

続く...