행복한 하루

아두이노 나노(Arduino Nano) 33 IoT로 작은 웹서버 만들기 본문

Embedded/Arduino

아두이노 나노(Arduino Nano) 33 IoT로 작은 웹서버 만들기

변화의 물결 2021. 6. 13. 19:11

 

 

안녕하세요.

 

  이전 글에서 많은 센서들을 테스트해보았습니다. 이제 실생활에 적용할 수 있는 것을 들을 찾아보려고 합니다. 그러기 위해서 우선 IoT 장비가 PC나 스마트폰과 통신되는 것이 가장 우선순위가 되어야 한다고 생각했습니다.

 그래서 가지고 있는 아두이노 33 IoT 모듈에 웹서버를 올려놓으면 필요할 때마다 볼 수 있고 DDNS 혹은 포트 포워딩 등 해두면 외부에서도 볼 수 있겠다 생각하였습니다. (블루투스가 되지만 다른 장치를 사용할 때만 페어링 하고 해야 해서 웹서버로 결정하였습니다.)

 

  1차는 웹서버를 테스트하고 2차, 3차에 온도 습도 등 센서 장착해서 수치 확인하고 이후에 케이스에 소형 솔라셀을 붙여서 외부 전력 공급 없이 작동하도록 하는 것으로 실제로 베란다에 두고 작동시켜보려고 합니다.

 

1. 아두이노 나노 33 IoT의 통신 모듈 정보

   - 아두이노 기본 스펙은 인터넷에서 많이 볼 수 있을 것으로 생각되어 생각되어 생략(첨부파일 참조)하고 통신 칩에 대해서 확인해보겠습니다. 아마 장착되어 있는 통신 모듈은 NINA-W10 series 일 것입니다.

 

  - NINA-W10 series are stand-alone multiradio MCU modules integrate a powerful microcontroller (MCU) and a radio for wireless communication. With the open CPU architecture, customers can develop advanced applications running on the dual core 32-bit MCU. The radio provides support for Wi-Fi 802.11b/g/n in the 2.4 GHz ISM band and Bluetooth v4.2 (Bluetooth BR/EDR and Bluetooth Low Energy (LE) communications.

 

 - Radio Performance

 

2. 웹서버 소스 확인

 1) 소스 코드 확인

  - 감사하게도 이미 여러 개발자 분이 소스를 공개해서 사용할 수 있도록 공개해주고 있습니다. 

  - 아두이노 새 파일을 눌러 아래의 소스를 붙여 넣기 혹은 소스를 다운하여 실행해볼 수 있습니다.

  - 수정해야 할 부분은 가정 혹은 회사에 설치된 공유기의 SSID와 PW 내용을 수정해야 합니다. 이 부분은 “arduino_secrets.h” 해더 파일처럼 #define 문으로 해서 문자열로 저장합니다.

 

- 소스 코드

 

/*
  WiFi Web Server
  A simple web server:
  
  created 13 July 2010
  by dlf (Metodo2 srl)
  modified 31 May 2012
  by Tom Igoe
  modified Jan 2020
  by Gary Sims
*/

#include <SPI.h>
#include <WiFiNINA.h>
//#include <WiFi101.h>

#include "arduino_secrets.h"
///////please enter your sensitive data in the Secret tab/arduino_secrets.h
char ssid[] = SECRET_SSID;        // your network SSID (name)
char pass[] = SECRET_PASS;    // your network password (use for WPA, or use as key for WEP)
int keyIndex = 0;                 // your network key Index number (needed only for WEP)

int status = WL_IDLE_STATUS;

WiFiServer server(80);

void setup() {
  //Initialize serial and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  // check for the presence of the shield:
  if (WiFi.status() == WL_NO_SHIELD) {
    Serial.println("WiFi shield not present");
    // don't continue:
    while (true);
  }

  // attempt to connect to WiFi network:
  while (status != WL_CONNECTED) {
    Serial.print("Attempting to connect to WiFi network.");
    // 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();
  // you're connected now, so print out the status:
  printWiFiStatus();
}


void loop() {
  // listen for incoming clients
  WiFiClient client = server.available();
  if (client) {
    Serial.println("new client");
    // an http request ends with a blank line
    bool currentLineIsBlank = true;
    while (client.connected()) {
      if (client.available()) {
        char c = client.read();
        Serial.write(c);
        // if you've gotten to the end of the line (received a newline
        // character) and the line is blank, the http request has ended,
        // so you can send a reply
        if (c == '\n' && currentLineIsBlank) {
          // send a standard http response header
          client.println("HTTP/1.1 200 OK");
          client.println("Content-Type: text/html");
          client.println("Connection: close");  // the connection will be closed after completion of the response
          client.println();
          client.println("<!DOCTYPE HTML>");
          client.println("<html>");
          client.println("<p>Welcome to the world's smallest web server.");
          client.println("<p>Thanks for visiting.");
          // print the received signal strength:
          long rssi = WiFi.RSSI();
          client.print("<p><em>Signal strength (RSSI):");
          client.print(rssi);
          client.println(" dBm</em>");
          client.println("</html>");
          break;
        }
        if (c == '\n') {
          // you're starting a new line
          currentLineIsBlank = true;
        }
        else if (c != '\r') {
          // you've gotten a character on the current line
          currentLineIsBlank = false;
        }
      }
    }
    // give the web browser time to receive the data
    delay(1);

    // close the connection:
    client.stop();
    Serial.println("client disconnected");
  }
}


void printWiFiStatus() {
 
  // 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");
}

 

  

 2) 오류 나는 부분

  - 위의 소스로 에러가 발생하지 않을 수 있지만,  컴파일하면서 발생했던 내용을 공유드립니다.

WiFi101.h 혹은 WiFiNINA.h 파일이 없다고 나온다면 라이브러리를 추가 설치해줍니다.

 

WiFi101.h 파일 없을 경우
WIFININA.h 파일 없을 경우

  - “툴”에 “라이브러리 매니저”로 들어가서 “wifinina” 로 검색합니다. WIFININA 최신 버전을 설치합니다. (WIFININA.h 에러 경우)

 

3. 실행결과

  - 소스를 다운로드한 후 시리얼 데이터로 보면 공유기와 접속하는 시간이 조금 걸리지만 웹서버 주소가 나오고 신호 강도(RSSI)가 나타납니다.

 

   - 웹 브라우저로 IP 주소로 접속하면 샘플로 만들어진 웹서버로 접속할 수 있게 됩니다.

 

  - 시리얼 데이터는 접속한 클라이언트의 정보를 출력하고 접속이 끊어지게 됩니다.

 

  - 이 소스를 기반으로 제어 결과 등을 출력하고 모니터링하는 것으로 사용해도 될 것으로 보입니다. 그러나 아두이노 33 IoT의 Flash가 256KB이고, SRAM이 32KB인 메모리를 감안하여 프로그래밍하여야 할 것입니다.

 

<참  고>

  - 시리얼 포트를 연결하지 않으면 웹서버가 작동하지 않는 현상이 발생하는데, 그것은 참고사이트에서 나온 것처럼 시리얼 포트를 검색하는 로직이 들어서 있어서 그렇습니다. 그래서 실제 동작하려고 할 때는 아래 부분을 주석 처리합니다.

 

//while (!Serial) {

//    ; // wait for serial port to connect. Needed for native USB port only

//}

 

  실제 배치할 때는 위의 내용을 주석으로 처리하고 배터리로 동작시키면 문제없이 작동하는 것을 확인할 수 있습니다.

 

  - 첨부파일에 아두이노 소스와 아두이노 스펙과 NINA-W10 데이터 시트를 추가하였습니다.

 

감사합니다.

 

 

 

<참고 사이트>

1. 나노 WEB SERVER

https://fishpoint.tistory.com/5046

2. WiFiNINA Web Server example problem using Nano 33 IOT board

https://forum.arduino.cc/t/wifinina-web-server-example-problem-using-nano-33-iot-board/623784

3. The World's Smallest Web Server (Arduino MKR1000 with WiFi)

https://github.com/garyexplains/examples/tree/master/MKR1000  

 

ArduinoWebServerSource_Datasheet.zip
1.90MB

 

 

Comments