ESP8266 펌웨어, 웹 클라이언트 기능 예
ESP8266 Arduino IDE를 이용하여 ESP8266 펌웨어 개발 환경설정은 이 링크를 눌러 확인하세요
http://shawnhymel.com/695/quick-tip-http-get-with-the-esp8266-thing/
WiFi 네트워크에 연결하여 웹서버에 5초 간격으로 요청을 전달하고 응답을 수신하여 시리얼 모니터에 출력하는 예
/* * This sketch sends data via HTTP GET requests to data.sparkfun.com service. * * You need to get streamId and privateKey at data.sparkfun.com and paste them * below. Or just customize this script to talk to other HTTP servers. * */ #include <ESP8266WiFi.h> const char *ssid = "201-1203-office-net"; const char *password = "my_office_pwd"; const char* host = "google.com"; void setup() { Serial.begin(115200); delay(10); // We start by connecting to a WiFi network Serial.println(); Serial.println(); Serial.print("Connecting to "); Serial.println(ssid); WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println(""); Serial.println("WiFi connected"); Serial.print("IP address: "); Serial.println(WiFi.localIP()); } int value = 0; void loop() { delay(5000); ++value; Serial.print("connecting to "); Serial.println(host); // Use WiFiClient class to create TCP connections WiFiClient client; const int httpPort = 80; if (!client.connect(host, httpPort)) { Serial.println("connection failed"); return; } // We now create a URI for the request String url = "/"; // url += streamId; // url += "?private_key="; // url += privateKey; // url += "&value="; // url += value; Serial.print("Requesting URL: "); Serial.println(url); // This will send the request to the server client.print(String("GET ") + url + " HTTP/1.1\r\n" + "Host: " + host + "\r\n" + "Connection: close\r\n\r\n"); int timeout = millis() + 5000; while (client.available() == 0) { if (timeout - millis() < 0) { Serial.println(">>> Client Timeout !"); client.stop(); return; } } // Read all the lines of the reply from server and print them to Serial while(client.available()) { String line = client.readStringUntil('\r'); Serial.print(line); } Serial.println(); Serial.println("closing connection"); }
위의 코드를 실행하면 아두이노의 시리얼 모니터에 다음과 같은 메시지가 출력된다
위의 코드에서 시리얼 통신의 속도를 115200 으로 설정했으므로 아두이노 IDE의 시리얼 모니터 화면 하단에서 통신속도를 코드와 동일하게 115200으로 설정해야만 아래와 같은 출력을 확인할 수 있다
Connecting to 201-1203-home-net
..........
WiFi connected
IP address: 192.168.0.12
connecting to google.com
Requesting URL: /
HTTP/1.1 302 Found
Cache-Control: private
Content-Type: text/html; charset=UTF-8
Location: http://www.google.co.kr/?gfe_rd=cr&ei=LwmCV8r0FY3f8Afo5qqAAQ
Content-Length: 261
Date: Sun, 10 Jul 2016 08:37:03 GMT
Connection: close
<HTML><HEAD><meta http-equiv="content-type" content="text/html;charset=utf-8">
<TITLE>302 Moved</TITLE></HEAD><BODY>
<H1>302 Moved</H1>
The document has moved
<A HREF="http://www.google.co.kr/?gfe_rd=cr&ei=LwmCV8r0FY3f8Afo5qqAAQ">here</A>.
</BODY></HTML>
closing connection