상세 컨텐츠

본문 제목

026. Arduino 아두이노 - Ethernet Shield 사용하기

embedded/arduino

by ZelKun 2019. 8. 24. 18:58

본문

반응형

아두이노와 이더넷 쉴드

일전에 Ethernet Shield키트를 선물로 받았었는데

귀찮아서 이제서야 꺼내보았다

 

아두이노 IoT 교육 키트1 - 이더넷편 구성품
이더넷 쉴드

구성품이 가격대비로는 괜찮은듯 하다

 

이제서야 꺼내본 이유는

외부 온도는 SolarWeatherStation 만들어서 있지만

내부 온도는 확인이 안되기때문이다

 

간단하게 Ethernet Shield예제를 가지고 WebClient 예제를 진행해보았다

이더넷쉴드와 공유기 연결

우선 공유기에 연결을 하고

예제 > Ethernet > WebClient

client 계속해서 연결해야 한다면 WebClientRepeating 예제를 참고하면 된다

 

IP dns 본인 공유기에 맞춰서 수정해야 하겠지만

대부분 192.168.0.x 일테니 크게 변경할 없다

주소도 부망에 같은 맥을 가진 기기가 없을테니 상관없겠지만

2개 이상의 ethernet Shield 사용한다면 기기마다 수정을 해야한다 알파벳 몇개만 바꿔주면 된다...

WebClient 예제

/*
  Web client

 This sketch connects to a website (http://www.google.com)
 using an Arduino Wiznet Ethernet shield.

 Circuit:
 * Ethernet shield attached to pins 10, 11, 12, 13

 created 18 Dec 2009
 by David A. Mellis
 modified 9 Apr 2012
 by Tom Igoe, based on work by Adrian McEwen

 */

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

// Enter a MAC address for your controller below.
// Newer Ethernet shields have a MAC address printed on a sticker on the shield
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };

// if you don't want to use DNS (and reduce your sketch size)
// use the numeric IP instead of the name for the server:
//IPAddress server(74,125,232,128);  // numeric IP for Google (no DNS)
char server[] = "www.google.com";    // name address for Google (using DNS)

// Set the static IP address to use if the DHCP fails to assign
IPAddress ip(192, 168, 0, 177);
IPAddress myDns(192, 168, 0, 1);

// Initialize the Ethernet client library
// with the IP address and port of the server
// that you want to connect to (port 80 is default for HTTP):
EthernetClient client;

// Variables to measure the speed
unsigned long beginMicros, endMicros;
unsigned long byteCount = 0;
bool printWebData = true;  // set to false for better speed measurement

void setup() {
  // You can use Ethernet.init(pin) to configure the CS pin
  //Ethernet.init(10);  // Most Arduino shields
  //Ethernet.init(5);   // MKR ETH shield
  //Ethernet.init(0);   // Teensy 2.0
  //Ethernet.init(20);  // Teensy++ 2.0
  //Ethernet.init(15);  // ESP8266 with Adafruit Featherwing Ethernet
  //Ethernet.init(33);  // ESP32 with Adafruit Featherwing Ethernet

  // Open serial communications and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  // start the Ethernet connection:
  Serial.println("Initialize Ethernet with DHCP:");
  if (Ethernet.begin(mac) == 0) {
    Serial.println("Failed to configure Ethernet using DHCP");
    // Check for Ethernet hardware present
    if (Ethernet.hardwareStatus() == EthernetNoHardware) {
      Serial.println("Ethernet shield was not found.  Sorry, can't run without hardware. :(");
      while (true) {
        delay(1); // do nothing, no point running without Ethernet hardware
      }
    }
    if (Ethernet.linkStatus() == LinkOFF) {
      Serial.println("Ethernet cable is not connected.");
    }
    // try to congifure using IP address instead of DHCP:
    Ethernet.begin(mac, ip, myDns);
  } else {
    Serial.print("  DHCP assigned IP ");
    Serial.println(Ethernet.localIP());
  }
  // give the Ethernet shield a second to initialize:
  delay(1000);
  Serial.print("connecting to ");
  Serial.print(server);
  Serial.println("...");

  // if you get a connection, report back via serial:
  if (client.connect(server, 80)) {
    Serial.print("connected to ");
    Serial.println(client.remoteIP());
    // Make a HTTP request:
    client.println("GET /search?q=arduino HTTP/1.1");
    client.println("Host: www.google.com");
    client.println("Connection: close");
    client.println();
  } else {
    // if you didn't get a connection to the server:
    Serial.println("connection failed");
  }
  beginMicros = micros();
}

void loop() {
  // if there are incoming bytes available
  // from the server, read them and print them:
  int len = client.available();
  if (len > 0) {
    byte buffer[80];
    if (len > 80) len = 80;
    client.read(buffer, len);
    if (printWebData) {
      Serial.write(buffer, len); // show in the serial monitor (slows some boards)
    }
    byteCount = byteCount + len;
  }

  // if the server's disconnected, stop the client:
  if (!client.connected()) {
    endMicros = micros();
    Serial.println();
    Serial.println("disconnecting.");
    client.stop();
    Serial.print("Received ");
    Serial.print(byteCount);
    Serial.print(" bytes in ");
    float seconds = (float)(endMicros - beginMicros) / 1000000.0;
    Serial.print(seconds, 4);
    float rate = (float)byteCount / seconds / 1000.0;
    Serial.print(", rate = ");
    Serial.print(rate);
    Serial.print(" kbytes/second");
    Serial.println();

    // do nothing forevermore:
    while (true) {
      delay(1);
    }
  }
}

실행을 해보면 google에서 arduino 검색한 결과를 Serial 모니터로 확인할 있다

loop 마지막에 while(true)인걸 확인할 있는데 단발성이라

loop 돌지 않는다고 생각하면된다

WebClient 예제 실행결과

근데 DHCP assigned IP 192.168.0.15

위의 소스에서 177 IP 넣었는데 전혀 다른 IP 찍은걸 있다

 

만약에 서버로 사용한다면 IP 변하면 그야말로 지옥일텐데 말이다

그건  if (Ethernet.begin(mac) == 0) { 에서

Ethernet 시작시 맥주소를 가지고 공유기에 연결하기 때문으로 보인다

IP까지 원하는데로 하려면 Ethernet.begin(mac, ip, myDns) 으로 변경해주면 같다

서버로 쓸게 아니고 인터넷 연결만되면 되기때문에 추가 테스트를 하질 않았다…

 

참고로... 이렇게 변경해도 실행이 된다

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

EthernetClient client;

unsigned long beginMicros, endMicros;
unsigned long byteCount = 0;
bool printWebData = true;  // set to false for better speed measurement

void setup() {
  Serial.begin(9600);

  if (client.connect(server, 80)) {
    Serial.print("connected to ");
    Serial.println(client.remoteIP());
    // Make a HTTP request:
    client.println("GET /search?q=arduino HTTP/1.1");
    client.println("Host: www.google.com");
    client.println("Connection: close");
    client.println();
  } else {
    // if you didn't get a connection to the server:
    Serial.println("connection failed");
  }
  beginMicros = micros();
}

void loop() {
  // if there are incoming bytes available
  // from the server, read them and print them:
  int len = client.available();
  if (len > 0) {
    byte buffer[80];
    if (len > 80) len = 80;
    client.read(buffer, len);
    if (printWebData) {
      Serial.write(buffer, len); // show in the serial monitor (slows some boards)
    }
    byteCount = byteCount + len;
  }

  // if the server's disconnected, stop the client:
  if (!client.connected()) {
    endMicros = micros();
    Serial.println();
    Serial.println("disconnecting.");
    client.stop();
    Serial.print("Received ");
    Serial.print(byteCount);
    Serial.print(" bytes in ");
    float seconds = (float)(endMicros - beginMicros) / 1000000.0;
    Serial.print(seconds, 4);
    float rate = (float)byteCount / seconds / 1000.0;
    Serial.print(", rate = ");
    Serial.print(rate);
    Serial.print(" kbytes/second");
    Serial.println();

    // do nothing forevermore:
    while (true) {
      delay(1);
    }
  }
}

 맥주소랑 IP 전부 빠져있다 하지만 연결이 되었다...

 

무튼 이더넷 쉴드를 이용해서 인터넷 연결이 되는걸 확인했으니 다음 단계로 넘어가야겠다

 

참고

https://www.arduino.cc/en/Reference/Ethernet

반응형

관련글 더보기

댓글 영역