6. #include <ESP8266WiFi.h>
#include <WiFiUdp.h>
char ssid[] = "ChiwonC-iPhone6"; // your network SSID (name)
char pass[] = ""; // your network password
unsigned int localPort = 2390; // local port to listen for UDP packets
IPAddress timeServerIP; // time.nist.gov NTP server address
const char* ntpServerName = "time.nist.gov";
const int NTP_PACKET_SIZE = 48; // NTP time stamp is in the first 48 bytes of the message
byte packetBuffer[ NTP_PACKET_SIZE]; //buffer to hold incoming and outgoing packets
// A UDP instance to let us send and receive packets over UDP
WiFiUDP udp;
void setup()
{
Serial.begin(115200);
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, pass);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
Serial.println("Starting UDP");
udp.begin(localPort);
Serial.print("Local port: ");
Serial.println(udp.localPort());
}
void loop()
{
WiFi.hostByName(ntpServerName, timeServerIP);
sendNTPpacket(timeServerIP);
delay(5000);
int cb = udp.parsePacket();
if (!cb) {
Serial.println("no packet yet");
}
else {
Serial.print("packet received, length=");
Serial.println(cb);
udp.read(packetBuffer, NTP_PACKET_SIZE); // read the packet into the buffer
//the timestamp starts at byte 40 of the received packet and is four bytes,
// or two words, long. First, esxtract the two words:
unsigned long highWord = word(packetBuffer[40], packetBuffer[41]);
unsigned long lowWord = word(packetBuffer[42], packetBuffer[43]);
// combine the four bytes (two words) into a long integer
// this is NTP time (seconds since Jan 1 1900):
unsigned long secsSince1900 = highWord << 16 | lowWord;
Serial.print("Seconds since Jan 1 1900 = " );
Serial.println(secsSince1900);
// now convert NTP time into everyday time:
Serial.print("Unix time = ");
// Unix time starts on Jan 1 1970. In seconds, that's 2208988800:
const unsigned long seventyYears = 2208988800UL;
// subtract seventy years:
unsigned long epoch = secsSince1900 - seventyYears;
// print Unix time:
Serial.println(epoch);
// print the hour, minute and second:
Serial.print("The UTC time is "); // UTC is the time at Greenwich Meridian (GMT)
Serial.print((epoch % 86400L) / 3600); // print the hour (86400 equals secs per day)
Serial.print(':');
if ( ((epoch % 3600) / 60) < 10 ) {
// In the first 10 minutes of each hour, we'll want a leading '0'
Serial.print('0');
}
Serial.print((epoch % 3600) / 60); // print the minute (3600 equals secs per minute)
Serial.print(':');
if ( (epoch % 60) < 10 ) {
// In the first 10 seconds of each minute, we'll want a leading '0'
Serial.print('0');
}
Serial.println(epoch % 60); // print the second
}
delay(10*1000);
}
unsigned long sendNTPpacket(IPAddress& address)
{
Serial.println("sending NTP packet...");
memset(packetBuffer, 0, NTP_PACKET_SIZE);
packetBuffer[0] = 0b11100011; // LI, Version, Mode
packetBuffer[1] = 0; // Stratum, or type of clock
packetBuffer[2] = 6; // Polling Interval
packetBuffer[3] = 0xEC; // Peer Clock Precision
// 8 bytes of zero for Root Delay & Root Dispersion
packetBuffer[12] = 49;
packetBuffer[13] = 0x4E;
packetBuffer[14] = 49;
packetBuffer[15] = 52;
udp.beginPacket(address, 123); //NTP requests are to port 123
udp.write(packetBuffer, NTP_PACKET_SIZE);
udp.endPacket();
}
https://github.com/iamchiwon/iot_with_arduino/tree/master/WiFi_Ntp_Client
7. #include <ESP8266WiFi.h>
#include <WiFiClient.h>
char ssid[] = “iptime";
char pass[] = "";
const char http_site[] = "www.naver.com";
const int http_port = 80;
WiFiClient client;
void setup()
{
Serial.begin(115200);
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, pass);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
void loop()
{
if ( !getPage() ) {
Serial.println("GET request failed");
}
while ( client.available() ) {
char c = client.read();
Serial.print(c);
}
if ( !client.connected() ) {
Serial.println();
client.stop();
if ( WiFi.status() != WL_DISCONNECTED ) {
WiFi.disconnect();
}
// Do nothing
Serial.println("Finished Thing GET test");
while(true){
delay(1000);
}
}
}
bool getPage() {
// Attempt to make a connection to the remote server
if ( !client.connect(http_site, http_port) ) {
return false;
}
// Make an HTTP GET request
client.println("GET /index.html HTTP/1.1");
client.print("Host: ");
client.println(http_site);
client.println("Connection: close");
client.println();
return true;
}
https://github.com/iamchiwon/iot_with_arduino/tree/master/GetWebPage
아두이노와 인터넷을 연결하는 방법
아두이노 + PC + LAN
아두이노 + 이더넷 쉴드 + LAN
아두이노 이더넷 + LAN
아두이노 + WiFi 쉴드 + WiFi
아두이노 Yún
WeMos D1
Arduino Uno-like wifi board based on ESP-8266EX.
a Micro USB connection
Compatible with Arduino
WeMos D1 보드 사용하기
http://www.wemos.cc/
드라이버 설치CH340 driver : http://www.wemos.cc/downloads/http://goo.gl/Q6kL0F
보드 설치http://arduino.esp8266.com/stable/package_esp8266com_index.jsonhttp://goo.gl/sct0aD- 환경설정 > 보드매니저 등록- 보드 추가 : ESP8266 Package
보드 설정Upload Using : SerialCPU Frequency : 80 MHzUpload Speed : 115200
ESP8266 규격을 통한 WiFi 연결
라이브러리 ESP8266WiFi 사용
SSID, PASSWORD 가 미리 소스에 기입됨
WiFi.begin() 메소드로 연결 수행
WiFi 라이브러리 Referencehttps://www.arduino.cc/en/Reference/WiFi
WiFi 를 통한 서버 통신 예제 (UDP)
UDP 소켓통신으로 Time Server 연동하기Timer 서버에 접속해서 UTC 시간 얻어오기
Time Server : time.nist.gov
Protocol : NTP (Network Time Protocol)http://www.ntp.org/
WiFi 라이브러리의 WiFiUDP 클래스 사용https://www.arduino.cc/en/Reference/WiFi
WiFi 를 통한 서버 통신 예제 (TCP)
소켓통신을 기본으로 함
대표적인 TCP 통신 : HTTP / 80 포트
웹 페이지를 가져오기 위해서는 소켓통신으로 HTTP 프로토콜을 구현해줘야 함
RequestGET /index.html HTTP/1.1Host: www.naver.com\r\nConnection: close\r\\r\n
WiFi 를 통한 서버 통신 예제 (HTTP)
HttpClient 라이브러리 사용
HTTP 프로토콜 구현
Response 헤더 파싱
REST API 호출 및 정보 조회 시 사용
미세농도 표시기Open API 를 활용하여 미세먼지 정보를 얻어LCD화면에 표시하기
정보 수집서울 열린 데이터 센터 광장 / 서울시 권역별 실시간 대기현황 현황http://data.seoul.go.kr/openinf/openapiview.jsp?infId=OA-2219
Open APIJSON : http://openapi.seoul.go.kr:8088/sample/json/RealtimeCityAir/1/5/XML : http://openapi.seoul.go.kr:8088/sample/xml/RealtimeCityAir/1/5/
Json ParserArduinoJsonhttps://github.com/bblanchon/ArduinoJson/wiki
Data ParsingJsonObject& root = jsonBuffer.parseObject(response);JsonArray& rows = root["RealtimeCityAir"]["row"].asArray();JsonObject& row = rows.get(0);float pm10 = row["PM10"]; //미세먼지
모바일 연동 방법(1) Arduino – Mobile 직접연동 : 아두이노 프로그래밍, 로컬서버 프로그래밍, 모바일 프로그래밍(2) Arduino – Server – Mobile 연동 : 아두이노 프로그래밍, 클라우드 서버 프로그래밍, 모바일 프로그래밍(3) 플랫폼 연동 : 아두이노 프로그래밍
Blynk 플랫폼- 무료 회원 가입- 프로젝트 공유 가능- 클라우드 서버 제공- 모바일(Android, iOS) 어플리케이션 제공- 오픈소스 (MIT License)
Blynk 홈페이지- http://www.blynk.cc/
어플 설치- 모바일 스토어에서 Blynk 검색- 어플리케이션 다운로드
회원가입- Create New Account- 이메일/비밀번호 입력 (이메일로 전달되는 App Key 를 전달받아야 함)
프로젝트 생성Create New Project 를 선택해서 프로젝트 생성
프로젝트 세팅프로젝트 이름 : First Project (아무거나 입력)하드웨어 모델 : WeMos D1토큰 : 이메일 버튼으로 전송Create Project 버튼으로 생성 완료
위젯 배치바닥을 클릭해서 Widget Box 보기Button 선택길게 눌러서 위치 이동 가능
버튼 설정OUTPUT : D8MODE : PUSH
실행하기우측상단 PLAY 버튼 선택(“WeMos D1 is offline”)
Blynk 라이브러리 사용BlynkSimpleEsp8266 선택
Blynk기본 코드 삽입(Blynk.begin 에서 SSID, PASS 함게 파라미터로 전달)
펌웨어 업로드