본문 바로가기

IT이야기/아두이노

아두이노 http 통신 예제

출처:https://daru-daru.tistory.com/10

 

이 글은 차후 직접 테스트를 적은 후 좀더 자세하게 초보자 중심으로 수정 보완될 예정임.

 

이왕이면 서버쪽에서 처리하는 부분까지 적어보도록 해보겠음 

 

 

 

기존에 만들었던 서버에서 데이터를 가져오기 위하여 아두이노에서도 서버를 연결해야 한다.

 

아두이노에서 서버를 연결하기 위해서는 WiFi Shield 또는 Ethernet Shield가 필요하다.

 

우리는 Ethernet Shield를 사용하겠다. (WiFi Shield도 비슷하게 사용하시면 됩니다.)

 

먼저 Ethernet Shield를 아두이노에 연결해야한다.

 

 

아두이노와 Ethernet Shield를 연결한 모습이다.

 

이제 아두이노를 통하여 이전에 구축했던 Apache2 서버에 연결하겠다.

 

이 코드도 마찬가지로 아두이노에 내장된 예제를 이용하겠다.

 

 

예제 코드 중에서 WebClient WebServer 예제를 사용한다.

 

예제를 열면 아래와 같은 소스를 확인할 수 있다.

 

/*
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);
 
// 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;
 
void setup() {
// 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:
if (Ethernet.begin(mac) == 0) {
Serial.println("Failed to configure Ethernet using DHCP");
// try to congifure using IP address instead of DHCP:
Ethernet.begin(mac, ip);
}
// give the Ethernet shield a second to initialize:
delay(1000);
Serial.println("connecting...");
 
// if you get a connection, report back via serial:
if (client.connect(server, 80)) {
Serial.println("connected");
// 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");
}
}
 
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);
}
}

 

/*
Web Server
A simple web server that shows the value of the analog input pins.
using an Arduino Wiznet Ethernet shield.
Circuit:
* Ethernet shield attached to pins 10, 11, 12, 13
* Analog inputs attached to pins A0 through A5 (optional)
created 18 Dec 2009
by David A. Mellis
modified 9 Apr 2012
by Tom Igoe
modified 02 Sept 2015
by Arturo Guadalupi
*/
 
#include <SPI.h>
#include <Ethernet.h>
 
// Enter a MAC address and IP address for your controller below.
// The IP address will be dependent on your local network:
byte mac[] = {
0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED
};
IPAddress ip(192, 168, 1, 177);
 
// Initialize the Ethernet server library
// with the IP address and port you want to use
// (port 80 is default for HTTP):
EthernetServer server(80);
 
void setup() {
// 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 and the server:
Ethernet.begin(mac, ip);
server.begin();
Serial.print("server is at ");
Serial.println(Ethernet.localIP());
}
 
 
void loop() {
// listen for incoming clients
EthernetClient client = server.available();
if (client) {
Serial.println("new client");
// an http request ends with a blank line
boolean currentLineIsBlank = true;
while (client.connected()) {
if (client.available()) {
char c = client.read();
Serial.write(c);
// if you've gotten to the end of the line (received a newline
// character) and the line is blank, the http request has ended,
// so you can send a reply
if (c == '\n' && currentLineIsBlank) {
// send a standard http response header
client.println("HTTP/1.1 200 OK");
client.println("Content-Type: text/html");
client.println("Connection: close"); // the connection will be closed after completion of the response
client.println("Refresh: 5"); // refresh the page automatically every 5 sec
client.println();
client.println("<!DOCTYPE HTML>");
client.println("<html>");
// output the value of each analog input pin
for (int analogChannel = 0; analogChannel < 6; analogChannel++) {
int sensorReading = analogRead(analogChannel);
client.print("analog input ");
client.print(analogChannel);
client.print(" is ");
client.print(sensorReading);
client.println("<br />");
}
client.println("</html>");
break;
}
if (c == '\n') {
// you're starting a new line
currentLineIsBlank = true;
} else if (c != '\r') {
// you've gotten a character on the current line
currentLineIsBlank = false;
}
}
}
// give the web browser time to receive the data
delay(1);
// close the connection:
client.stop();
Serial.println("client disconnected");
}
}

 

WebServer 코드에서

 

byte mac[];        // PC와 연결된 아두이노의 Mac address

IPAddress ip();    // PC와 연결된 아두이노의 현재 IP 주소

 

위의 정보를 얻을 수 있다.

 

얻은 정보를 WebClient 코드에 수정한 뒤 사용한다.

 

WebClient 코드에 있는

 

IPAddress server();

 

위의 코드의 주석을 풀어 이전에 구축한 서버 PC의 IP주소를 입력한다.

 

그리고 WebClient의 코드를 다음과 같이 수정한다.

 

if (client.connect(server, 80)) {
Serial.println("connected");
// 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");
}
 
/**************** Edit ****************/
 
if (client.connect(server, 80)) {
Serial.println("connected");
// Make a HTTP request:
client.println("GET / HTTP/1.1");
client.println("Host: 192, 168, 1, 177"); //Server's PC IP address
client.println();
} else {
// if you didn't get a connection to the server:
Serial.println("connection failed");
}

 

코드를 수정하고 난 뒤, 업로드를 하면 Sirial 화면으로부터 구축된 서버의 메인 페이지에 대한 정보를 가져오는 것을 확인할 수 있다.

'IT이야기 > 아두이노' 카테고리의 다른 글

DHT-22 온습도 센서 예  (0) 2019.08.22