반응형

예전 포스팅에서 ESP8266의 펌웨어를 업데이트 해봤고(http://deneb21.tistory.com/269) AT 커맨드를 이용하여 공유기에 연결해 보았다.(http://deneb21.tistory.com/272) 이번엔 웹페이지를 통해서 아두이노에 달린 LED를 컨트롤 해 보자


웹페이지의 버튼을 클릭하면 아두이노에 연결된 특정 LED가 켜지고 꺼지는 것을 구현해 보는 것이다.


연결은 다음과 같이 해 주었다. 그리고 위의 두 개의 글에서도 말을 했지만 ESP8266은 3.3V에서 동작하는데 아두이노 디지털핀의 출력은 5V이다. 저항 등을 연결하여 다운시켜야 고장이 없지만 저항이 없어서 직접 연결하였다. 이는 ESP8266 모듈의 고장이나 아두이노의 고장의 원인이 될 수가 있다고 한다. 하지만 나의 경우는 운이 좋아서 그런건지 몇 시간을 테스트 해도 이상이 없다;; 물론 LED도 저항과 함께 연결해야 한다.



■ Fritzing 파일: 

ESP8266_WEB_LED.fzz


아두이노측 소스


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#include <SoftwareSerial.h>
#define DEBUG true
 
SoftwareSerial esp8266(2,3); // make RX Arduino line is pin 2, make TX Arduino line is pin 3.
                                        // This means that you need to connect the TX line from the esp to the Arduino's pin 2
                                        // and the RX line from the esp to the Arduino's pin 3
 
void setup() {
  Serial.begin(9600);
  esp8266.begin(9600); // your esp's baud rate might be different
  
  pinMode(11, OUTPUT);
  digitalWrite(11, LOW);
  
  pinMode(12, OUTPUT);
  digitalWrite(12, LOW);
  
  pinMode(13, OUTPUT);
  digitalWrite(13, LOW);
   
  sendData("AT+RST\r\n",2000,DEBUG); // reset module
  sendData("AT+CIOBAUD?\r\n",2000,DEBUG); // check baudrate (redundant)
  sendData("AT+CWMODE=3\r\n",1000,DEBUG); // configure as access point (working mode: AP+STA)
  sendData("AT+CWLAP\r\n",3000,DEBUG); // list available access points
  sendData("AT+CWJAP=\"AP NAME\",\"AP PASSWORD\"\r\n",5000,DEBUG); // join the access point
  sendData("AT+CIFSR\r\n",1000,DEBUG); // get ip address
  sendData("AT+CIPMUX=1\r\n",1000,DEBUG); // configure for multiple connections
  sendData("AT+CIPSERVER=1,80\r\n",1000,DEBUG); // turn on server on port 80
}
 
void loop() {
  if(esp8266.available()) { // check if the esp is sending a message
    if(esp8266.find("+IPD,")) {
      delay(1000); // wait for the serial buffer to fill up (read all the serial data)
      // get the connection id so that we can then disconnect
      int connectionId = esp8266.read()-48// subtract 48 because the read() function returns 
                                           // the ASCII decimal value and 0 (the first decimal number) starts at 48
      esp8266.find("pin="); // advance cursor to "pin="
      int pinNumber = (esp8266.read()-48)*10// get first number i.e. if the pin 13 then the 1st number is 1, then multiply to get 10
      pinNumber += (esp8266.read()-48); // get second number, i.e. if the pin number is 13 then the 2nd number is 3, then add to the first number
      digitalWrite(pinNumber, !digitalRead(pinNumber)); // toggle pin    
     
      // make close command
      String closeCommand = "AT+CIPCLOSE="
      closeCommand+=connectionId; // append connection id
      closeCommand+="\r\n";
      sendData(closeCommand,1000,DEBUG); // close connection
    }
  }
}
 
/*
* Name: sendData
* Description: Function used to send data to ESP8266.
* Params: command - the data/command to send; timeout - the time to wait for a response; debug - print to Serial window?(true = yes, false = no)
* Returns: The response from the esp8266 (if there is a reponse)
*/
String sendData(String command, const int timeout, boolean debug) {
    String response = "";
    esp8266.print(command); // send the read character to the esp8266
    long int time = millis();
    
    while( (time+timeout) > millis()) {
      while(esp8266.available()) {
        // The esp has data so display its output to the serial window 
        char c = esp8266.read(); // read the next character.
        response+=c;
      }
    }
    
    if(debug) {
      Serial.print(response);
    }
    return response;
}
cs


위에서 25행에 AP NAME, AP PASSWORD 부분에는 자신이 연결하려고 하는 공유기의 AP이름과 패스워드를 적어 주어야 한다.


나의 경우 전력부족으로 추정되는 에러로 위의 프로그램이 업로드가 되지 않는 현상이 있었다. 이런 경우 ESP8266의 전원케이블을 뽑고 프로그램을 업로드 하니 업로드가 잘 된다. 역시 ESP8266이 전력을 많이 먹는것 같다.


웹페이지 소스


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<html>
 <head>
  <title>ESP8266 LED Control</title>
 </head>
 <body>
 
 <!-- in the <button> tags below the ID attribute is the value sent to the arduino -->
 <h>ESP8266 LED Control</h></br></br>
 <button id="11" class="led">LED PIN 11</button<!-- button for pin 11 -->
 <button id="12" class="led">LED PIN 12</button<!-- button for pin 12 -->
 <button id="13" class="led">LED PIN 13</button<!-- button for pin 13 -->
  
 <script src="jquery.min.js"></script>
 <script type="text/javascript">
  $(document).ready(function(){
   $(".led").click(function(){
    var p = $(this).attr('id'); // get id value (i.e. pin13, pin12, or pin11)
    // send HTTP GET request to the IP address with the parameter "pin" and value "p", then execute the function
    $.get("http://192.168.1.102:80/", {pin:p}); // execute get request
   });
  });
 </script>
 </body>
</html>
cs


웹페이지 소스도 19행의 '192.168.1.102' 부분을 자신의 ESP8266 IP주소로 바꿔주어야 한다. 그리고 아래의 jquery.min.js 파일을 위의 html 파일과 같은 폴더에 넣어준다.

jquery.min.js


그리고 로컬 컴퓨터에서 테스트 하는 것은 그냥 html 파일을 브라우저로 불러와서 테스트해도 되지만 원격에서 테스트 하고자 하는 경우 당연한 얘기겠지만 자신의 PC에 웹서버를 설치하고 html 파일을 웹서버에 올려야 한다. 그리고 공유기 환경이라면 포트포워딩 등을 통해서 외부에서 접근 가능하도록 해야 한다. 나의 경우는 간단한 웹서버로 Mongoose 웹서버를 즐겨쓴다.


결과

각 버튼을 클릭하면 약간의 텀이 있지만 해당되는 LED가 잘 켜지고 잘 꺼진다. 더 응용하면 릴레이나 모터의 제어도 가능할 것 같다.




참고 사이트: 

http://allaboutee.com/2015/01/02/esp8266-arduino-led-control-from-webpage/

http://blog.naver.com/damtaja/220311479276

반응형

+ Recent posts