이전 자료
출처
소스코드
//① 번에는 헤더 파일 포함, 네트워크 접속 정보 외 각종 선언들이 들어가고
#include <ESP8266WiFi.h>
const char* ssid = "glory";//와이파이 이름 //캐릭터 포인터 변수
const char* password = "ㅇㅇㅇㅇ";//와이파이 비밀번호
// Create an instance of the server
// specify the port to listen on as an argument
WiFiServer server(80); //WiFiServer라는 클래스에 80포트를 열고 객체를 생성한다. 이름은 server
//와이파이가 아두이노에게 ip를 할당해준다.
//②번은 setup() 함수로 WiFi 연결을 설정합니다.
void setup() {
//모니터링과 디버깅을 위해 Serial 통신을 설정
Serial.begin(9600);//9600 속도 시리얼 모니터 속도를 꼭 확인할 것
delay(10); //0.01초에 Term을 준다.
// Connect to WiFi network
Serial.println(); //한글과 컴퓨터에서 Enter 같은역할이다. 출력할때 줄 바꾸기
Serial.println();
Serial.print("Connecting to "); //연결중이다라는 말을 출력해줄려고 하는 것이다.
Serial.println(ssid);
// WiFi 연결 시도
WiFi.begin(ssid, password);
// 연결될 때 까지 계속 실행
while (WiFi.status() != WL_CONNECTED) { //WiFi.status() 랑 WL_CONNECTED랑 같지 않으면 접속이 안됨.
delay(500);
Serial.print(".");//연결할 때 까지 ..... 하는 걸 만들려고 하는 것이다.
}
Serial.println("");
Serial.println("WiFi connected");//연결이 다 끝나면 Wifi가 Connected됬다 라고 메시지를 뿌려준다.
// 만약에 잘 안된다면 보드 왼쪽 위에 버튼을 눌러서 진행하면 된다.
// Start the server
server.begin(); // 80 서버를 열어서 대기
Serial.println("Server started");//성공적으로 서버가 열리면 문구 출력
// Print the IP address
Serial.println(WiFi.localIP());// ip를 출력하는 코드
}
//③번은 loop() 함수이고, Client 접속이 들어올 때마다 웹페이지를 전송합니다.
void loop() {
// Check if a client has connected
WiFiClient client = server.available(); // 클라이언트 접속이 들어오는지 체크
if (!client) {//접속이 안될때 이 문구를 작성해야한다.
return;
}
// Wait until the client sends some data
Serial.println("new client");
//while(!client.available()){
// delay(1);
//}
// Read the first line of the request
String req = client.readStringUntil('\r'); //클라이언트가 어떤 요청을 했는지 읽기위해서 나오는 구문이다.
//예를 들어서 http://192.168.0.42:80 이런 요청이 들어왔다고 가정하자.
//뒤에 :80 은 생략이 가능해서 http://192.168.0.42 이렇게 해도 된다. 주소창을 입력하고 Enter를 하는데 \r은 줄바꿈을 의미한다.
Serial.println(req);
client.flush();//요청을 초기화 한다고 생각하면 된다.
// Prepare the response 웹사이트로 출력하는 응답 소스 코드
String s="<html>";
s=s+"<meta name='viewport' content='width=device-width, initial-scale=1.0'/>";
//s=s+"<meta http-equiv='refresh' content='5'/>";
s=s+"<meta http-equiv='Content-Type' content='text/html;charset=utf-8' />";
s=s+"<head></head><body>안녕하세요!</body></html>";
// Send the response to the client
client.print(s);
delay(1);
Serial.println("Client disonnected"); //응답을 하게 되면 요청을 끝내는 방식이다.
// The client will actually be disconnected
// when the function returns and 'client' object is detroyed
}
Arduino
복사
•
여기서부터는 아두이노 스케치에서 컴파일 하는 방식은 스킵하겠다. (앞에 설명에서 언급했기 때문)
•
그리고 안녕하세요 라는 글자가 적힌 웹 서버를 구축을 하려면 인터넷 주소창에 다음처럼 입력을 해야한다.
•
시리얼 모니터에 있는 IP 주소를 확인하고 인터넷 브라우저 주소창에 작성을 하면 5글자가 나오게 된다.
•
만약에 접속하면 아래의 문구가 나오게 된다.