본문 바로가기

프로그래밍/아두이노01- 제품개발

아두이노 wifi shield 개발 - 2. 개발환경 구축 및 시작






기존에 주는 빵판이 너무 작아서 더 큰빵판에 아두이노+아두이노 와이파이 쉴드를 결합한 모듈을


케이블 타이로 묶었다.




아두이노 와이파이 쉴드의 경우 개발환경이랄것도없이

그냥 기존에 있는 아두이노 스캐치를 사용하면 그대로 사용이 가능합니다.


다만 코딩 환경에 있어서 와이파이를 쓴다는 점이 달라지기 때문에 와이파이를 사용할때 주의해서 개발해야합니다.


현재 코알라무브먼트팀의 개발환경의 경우 집에서 공유기를 사용한 와이파이 쉴드 링크를 사용하고 있습니다.


와이파이 쉴드를 개발할 경우 공유기설정이나 혹은 집안의 환경 혹은 회사의 환경에 따라 조금씩 코딩이나 환경설정이 달라 질 수있기때문에


반드시 유의 해서 개발해야합니다.


먼저 심플한 샘플 코딩부터 시작하겠습니다.


===========================================================================


#include <SPI.h>

#include <WiFi.h>


char ssid[] = "belkin.E33";      // 공유기 이름

char pass[] = "abc123cde456";   // 공유기 비밀번호

int keyIndex = 0;                 // your network key Index number (needed only for WEP) - 걍 놔두면됨


int status = WL_IDLE_STATUS;

WiFiServer server(81); // 웹서버로 사용할 시에 포트 번호 80 81 82 이런 번호로 쓰면된다.


void setup() {

  Serial.begin(9600);      // 9600으로 놔둠. 왜그런지는 모르겟음. 걍 그렇게햇엇음

  pinMode(9, OUTPUT);      // led를 켜고 끄기 위해서 사용하는 9번 핀모듈. 

//아웃풋으로 지정해놓아서 핀을 디지털신호로 켜고 끌수 있다.

  // check for the presence of the shield:

  if (WiFi.status() == WL_NO_SHIELD) {

  Serial.println("WiFi shield not present"); 

   while(true);        // don't continue

   } 


   // attempt to connect to Wifi network:

  while ( status != WL_CONNECTED) { 

    Serial.print("Attempting to connect to Network named: ");

    Serial.println(ssid);                   // print the network name (SSID);


    // Connect to WPA/WPA2 network. Change this line if using open or WEP network:    

     status = WiFi.begin(ssid, pass);

     // wait 10 seconds for connection:

     delay(10000);

   } 

  server.begin();                           // start the web server on port 80

  printWifiStatus();        // you're connected now, so print out the        status

}



void loop() {



  WiFiClient client = server.available();   // listen for incoming clients


  if (client) {                             // if you get a client,

    Serial.println("new client");           // print a message out the serial port

    String currentLine = "";      // make a String to hold incoming data from the client

    while (client.connected()) {            // loop while the client's connected

     if (client.available()) {             // if there's bytes to read from the client,

     char c = client.read();             // read a byte, then

     Serial.write(c);                    // print it out the serial monitor

     if (c == '\n') {                    // if the byte is a newline character


      // if the current line is blank, you got two newline characters in a row.

      // that's the end of the client HTTP request, so send a response:

      if (currentLine.length() == 0) {  

        // HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK)

        // and a content-type so the client knows what's coming, then a blank line:    

        client.println("HTTP/1.1 200 OK");

        client.println("Content-type:text/html");

        client.println();


        // the content of the HTTP response follows the header:

        client.print("Click <a href=\"/H\">here</a> turn the LED on pin 9 on<br>");

        client.print("Click <a href=\"/L\">here</a> turn the LED on pin 9 off<br>");


        // The HTTP response ends with another blank line:

        client.println();

        // break out of the while loop:

        break;         

       } 

       else {      // if you got a newline, then clear currentLine:

         currentLine = "";

       }

     }     

     else if (c != '\r') {  // if you got anything else but a carriage return character,

      currentLine += c;      // add it to the end of the currentLine

    }


    // Check to see if the client request was "GET /H" or "GET /L":

    if (currentLine.endsWith("GET /H")) {

      digitalWrite(9, HIGH);               // GET /H 과 같은 html 요청이 들어오면 엘이디 신호를 high로 줘서 켠다

    }

    if (currentLine.endsWith("GET /L")) {

      digitalWrite(9, LOW);                // GET /L과 같은 html 요청이 들어오면 엘이디 신호를 low로 줘서 끈다

     }

   }

 }

// close the connection:

client.stop();

Serial.println("client disonnected");

  }

}


void printWifiStatus() {

  // print the SSID of the network you're attached to:

  Serial.print("SSID: ");

 Serial.println(WiFi.SSID());


 // print your WiFi shield's IP address:

 IPAddress ip = WiFi.localIP();

 Serial.print("IP Address: ");

 Serial.println(ip);


 // print the received signal strength:

 long rssi = WiFi.RSSI();

 Serial.print("signal strength (RSSI):");

 Serial.print(rssi);

 Serial.println(" dBm");

// print where to go in a browser:

Serial.print("To see this page in action, open a browser to http://");

Serial.println(ip);

 }


===========================================================================


위 코드는 아두이노쉴드를 사용하여 9번 핀에 꽂혀있는 led를 동작 제어하도록 하는 


아두이노 웹서버 샘플 코드입니다.


이 코드는 원래 아두이노 공식싸이트 질문게시판(http://forum.arduino.cc/index.php/topic,204497.0.html)


에 올라 왔었던 것인데 웹서버를 구축하는데 있어서 잘 되지 않는다는 글이였습니다.


하지만 코드는 이상이 없고 해당 아두이노 와이파이 쉴드 펌웨어의 문제이기 때문에


반드시 1.0.4 버전 이상으로 올리고 위 코드를 시행시키는걸 추천합니다.



저같은 경우도 1.0.0 와이파이 쉴드 펌웨어에서 실행시켰다가 안되서 고생을 했는데 결국


답은 펌웨어 업그레이드 였습니다. 


아두이노 와이파이 쉴드 펌웨어 관련 글은 이전 1. 개요 글에 있으니 참고하시기 바랍니다.


===========================================================================


위 코드가 제대로 컴파일이 되고나면 해당 아이피(192.168.x.x)가 아두이노의 콘솔창에 나타나면서





제대로 링크가 되었다면 해당 아이피로 접속하면 보일것이고 만약 와이파이에 재대로 물리지 못했다면


에러가 나면서 웹페이지가 보이지 않을 것입니다.



보통 위와같이 error가 나는 경우는 공유기의 이름이 잘못되었거나 비밀번호가 잘못되었을 확률이 높다.



그림. 정상적으로 와이파이 쉴드가 작동되면서 해당 아이피를 치고 그리고 포트번호를


기입하여 실행시킨경우 위와 같은 웹페이지가 나오게된다.




위와 같이 같은 공유기에 물려있는 컴퓨터(노트북)에서 접속하여 버튼을 클릭하게 되면....



위 사신과 같이 엘이디가 켜지게 됩니다.


물론 꺼지는 것도 잘됨

(당연히 위 코드에 적힌것 처럼 led는 9번핀과 gnd에 물려있다.)

(5v전압은 안쓰기 때문에 그냥 빵판에 물려만 놨음.)

(아두이노와 led빵판에 어떻게 꼽는지는 다른 블로그에도 잘나와있으니 거기서 확인하세요.)

(사실 코드안에 답이있음)


===========================================================================


여러가지 공유기 가 있겟지만 우리의 경우 버팔로 공유기를 썻는데


이게 버팔로 공유기는 자신의 공유기 설정하는 포트를 80번을 쓴단다. 그래서 반드시 81 82 같은 유니크한


포트번호를 쓰는것을 권장합니다


나중에라도 포트 포워딩(마치 iot제품처럼 조작가능 토록함)할때 사용될 수 있으므로.


(포트번호는 실제로 작동할때는 그닥 상관이없다 네트워크 내에 똑같은 포트번호가 또 있지않는이상)


===========================================================================


위와 같은 웹페이지에서 이제 각 버튼을 누르게 되면 제대로 작동이 되게됩니다.


웹페이지를 통해 엘이디를 켜고 끌수 있게 된 것입니다.


감사합니다.


다음포스팅은 외부네트워크에 연결하여 아두이노 IoT제품 처럼 작동하도록 하는 


환경을 구축하도록 하겠습니다.