개발자/Arduino

Arduino Nano 33 IoT 개발 가이드 3 - WiFi Network 실습

지구빵집 2020. 5. 13. 16:04
반응형

 

 

Nano 33 IoT 개발 가이드 3 - WiFi Network 실습

 

이 장에서는 Arduino Nano 33 IoT 온보드 WiFi를 사용하는 방법에 대해 설명한다. WiFi 핫스팟을 스캔하는 첫 번째 데모는 주변 환경에서 WiFi를 스캔하는 예제다. 아두이노 사이트에서 제공하는 공식 라이브러리인  WiFiNINA 라이브러리를 사용한다. WiFi.scanNetworks() 를 사용해서 SSID의 리스트를 구하는 예제다. 라이브러리에 대한 설명은 위 링크를 따라간다.

 

전체 강의자료와 소스코드는 아래를 참고하십시요. 소스코드의 출처는 위의 책 마지막 페이지에 소개되어 있습니다.

 

Arduino Nano 33 IoT 개발 가이드 1 - 개발환경

Arduino Nano 33 IoT 개발 가이드 2 - 기본적인 예제 살펴보기

Arduino Nano 33 IoT 개발 가이드 3 - WiFi Network 실습

Arduino Nano 33 IoT 개발 가이드 4 - 내부 RTC와 Sleep Mode

Arduino Nano 33 IoT 개발 가이드 5 - Arduino Cloud

Arduino Nano 33 IoT 개발 가이드 6 - Accelerator and Gyroscope

Arduino Nano 33 IoT 개발 가이드 7 - Bluetooth Low Energy (BLE)

실습에 필요한 전체 소스코드 다운

 

우선 WiFiNINA library 를 포함하기 위해 아래 이미지와 같이 메뉴 -> 스케치 Sketch -> 라이브러리 포함하기 Include Library -> 라이브러리 관리하기 Manage Libraries 를 클릭한다.

 

메뉴 -> 스케치 Sketch -> 라이브러리 포함하기 Include Library -> 라이브러리 관리하기 Manage Libraries 

아래 이미지를 참조하여 라이브러리 관리에서 WIFININA 를 검색하여 설치한다.

 

WIFININA 라이브러리 설치 화면

 

아래의 wifiscan.ino 코드는 라이브러리 함수인 WiFi.scanNetworks ()를 사용하여 SSID 목록을 보여준다.

 

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

int led = 13;

void setup() 
{
	Serial.begin(9600);
    pinMode(led, OUTPUT);
	// check for the WiFi module:
    if (WiFi.status() == WL_NO_MODULE) 
    {
    	Serial.println("Communication with WiFi module failed!");
        // don't continue
        while (true);
    }
}

void loop() 
{
	digitalWrite(led, HIGH);
	scanWiFi();
	digitalWrite(led, LOW);
	delay(15000);
}
void scanWiFi() 
{
	Serial.print("Scanning...");
	byte ssid = WiFi.scanNetworks();
	Serial.print("found ");
	Serial.println(ssid);
	for (int i = 0; i<ssid; i++) 
	{
		Serial.print(">> ");
		Serial.print(WiFi.SSID(i));
		Serial.print("\tRSSI: ");
		Serial.print(WiFi.RSSI(i));
		Serial.print(" dBm");
		Serial.print("\tEncryption: ");
		Serial.println(WiFi.encryptionType(i));
	}
	Serial.println("");
	Serial.println("");
}

 

컴파일하고 업로드 한다. 위 프로그램을 실행한 출력은 아래와 같다.

 

WiFi 스캔 결과

두 번째 데모는 WiFi에 연결하여 외부 웹사이트에 연결하는 데모다. 샘플 프로그램 WiFiWebClient 를 사용한다. 소스크드의 위치는 menu에서  파일 -> 예제 -> WiFiNINA -> WiFiWebClient 로 선택한다.

 

프로그램의 시작 부분에 ssid 와 pass 를 srduino_secrets.h 라는 헤더파일에서 읽어 온다. 따라서 불러 온 파일을 다른 폴더에 저장을 한다. 그러면 그 폴더 아래에 방금 말한 헤더파일이 생성되어 있는데 없으면 만들어 주고, 헤더파일을 편집하여 자신의 네트워크에 접속할 수 있는 SSID와 PASS 를 넣어주고 업로딩 한다. 

 

/*
  Web client

 This sketch connects to a website (http://www.google.com)
 using the WiFi module.

 This example is written for a network using WPA encryption. For
 WEP or WPA, change the Wifi.begin() call accordingly.

 This example is written for a network using WPA encryption. For
 WEP or WPA, change the Wifi.begin() call accordingly.

 Circuit:
 * Board with NINA module (Arduino MKR WiFi 1010, MKR VIDOR 4000 and UNO WiFi Rev.2)

 created 13 July 2010
 by dlf (Metodo2 srl)
 modified 31 May 2012
 by Tom Igoe
 */


#include <SPI.h>
#include <WiFiNINA.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;
// if you don't want to use DNS (and reduce your sketch size)
// use the numeric IP instead of the name for the server:
//IPAddress server(74,125,232,128);  // numeric IP for Google (no DNS)
char server[] = "www.google.com";    // name address for Google (using DNS)

// Initialize the Ethernet client library
// with the IP address and port of the server
// that you want to connect to (port 80 is default for HTTP):
WiFiClient client;

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 WiFi module:
  if (WiFi.status() == WL_NO_MODULE) {
    Serial.println("Communication with WiFi module failed!");
    // don't continue
    while (true);
  }

  String fv = WiFi.firmwareVersion();
  if (fv < WIFI_FIRMWARE_LATEST_VERSION) {
    Serial.println("Please upgrade the firmware");
  }

  // attempt to connect to Wifi network:
  while (status != WL_CONNECTED) {
    Serial.print("Attempting to connect to SSID: ");
    Serial.println(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);
  }
  Serial.println("Connected to wifi");
  printWifiStatus();

  Serial.println("\nStarting connection to server...");
  // if you get a connection, report back via serial:
  if (client.connect(server, 80)) {
    Serial.println("connected to server");
    // Make a HTTP request:
    client.println("GET /search?q=arduino HTTP/1.1");
    client.println("Host: www.google.com");
    client.println("Connection: close");
    client.println();
  }
}

void loop() {
  // if there are incoming bytes available
  // from the server, read them and print them:
  while (client.available()) {
    char c = client.read();
    Serial.write(c);
  }

  // if the server's disconnected, stop the client:
  if (!client.connected()) {
    Serial.println();
    Serial.println("disconnecting from server.");
    client.stop();

    // do nothing forevermore:
    while (true);
  }
}


void printWifiStatus() {
  // print the SSID of the network you're attached to:
  Serial.print("SSID: ");
  Serial.println(WiFi.SSID());

  // print your board'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");
}

 

컴파일 업로딩한 후 결과를 확인한다. 아래에 접속 서버 주소가 구글로 되어 있어 많은 양의 데이터가 나온다.

 

구글 사이트에 접속한 결과 화면

 

다음으로 간단한 IoT 애플리케이션 프로그램을 실습한다.

 

Building a Simple IoT Application In this demo we build a simple IoT application. We use three LEDs. We define HTTP request as follows:

http:///gpio1/1 turns on LED 1

http:///gpio1/0 turns off LED 1

http:///gpio2/1 turns on LED 2

http:///gpio2/0 turns off LED 2

http:///gpio3/1 turns on LED 3

http:///gpio3/0 turns off LED 3 Let's start.

 

Led 와 핀 연결은

LED 1 is connected to digital pin 6
LED 2 is connected to digital pin 4
LED 3 is connected to digital pin 3

 

아래 iotdemo.ino 코드를 입력한다. 프로그램을 업로드 한다. 시리얼 모니터를 연다. 아두이노 씨리얼 모니터에 IoT 보드의 IP 주소가 나온다. 이 주소를 위에 정의한 HTTP 리퀘스트를 보낸다. 즉, 씨리얼 모니터의 데이터 입력 부분에 "http://<확보한 IP주소/gpio3/1" 이렇게 입력하여 보내면 LED 점등을 확인할 수 있다. 

 

#include <SPI.h>
#include <WiFiNINA.h>
int led1 = 6;
int led2 = 4;
int led3 = 3;
const char* ssid = "ssid";
const char* password = "ssid_key";
int status = WL_IDLE_STATUS;
WiFiServer server(80);

void setup() {
Serial.begin(9600);
delay(10);
// prepare GPIO5
pinMode(led1, OUTPUT);
pinMode(led2, OUTPUT);
pinMode(led3, OUTPUT);
digitalWrite(led1, 0);
digitalWrite(led2, 0);
digitalWrite(led3, 0);
// Connect to WiFi network
while (status != WL_CONNECTED) {
Serial.print("Attempting to connect to SSID: ");
Serial.println(ssid);
status = WiFi.begin(ssid, password);
// wait 10 seconds for connection:
delay(10000);
}
Serial.println("");
Serial.println("WiFi connected");
// Start the server
server.begin();
Serial.println("Server started");
// Print the IP address
char ips[24];
IPAddress ip = WiFi.localIP();
sprintf(ips, "%d.%d.%d.%d", ip[0], ip[1], ip[2], ip[3]);
Serial.println(ips);
}

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');
Serial.println(req);
client.flush();

// Match the request
int val1 = 0;
int val2 = 0;
int val3 = 0;
int ledreq = 0;
if (req.indexOf("/gpio1/0") != -1) {
val1 = 0;
ledreq = 1;
}
else if (req.indexOf("/gpio1/1") != -1) {
val1 = 1;
ledreq = 1;
}
else if (req.indexOf("/gpio2/0") != -1) {
val2 = 0;
ledreq = 2;
}
else if (req.indexOf("/gpio2/1") != -1) {
val2 = 1;
req = 2;
}
else if (req.indexOf("/gpio3/0") != -1) {
val3 = 0;
ledreq = 3;
}
else if (req.indexOf("/gpio3/1") != -1) {
val3 = 1;
ledreq = 3;
}
else {
Serial.println("invalid request");
client.stop();
return;
}

// Set GPIO2 according to the request
digitalWrite(led1, val1);
digitalWrite(led2, val2);
digitalWrite(led3, val3);
client.flush();
// Prepare the response
String s = "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n<!DOCTYPE HTML>\r\n<html>\r\n";

if(ledreq==1) {
s += "LED1 is ";
s += (val1)? "ON": "OFF";
}else if(ledreq==2) {
s += "LED2 is ";
s += (val2)? "ON": "OFF";
}else if(ledreq==3) {
s += "LED3 is ";
s += (val3)? "ON": "OFF";
}
s += "</html>\n";
// Send the response to the client
client.print(s);
delay(1);
client.stop();
Serial.println("Client disonnected");
}


 

위 프로그램의 실습 화면이다. 

 

실행 후 IoT 보드의 IP 주소가 보인다.

 

HTTP request를 보내면 LED 가 점등한다.

 

오늘 20200506은 여기까지. 술마시러 나감. ^^

 

참고자료

 

WiFiNINA library 참고

 

 

꼭 실습 이미지만 넣는 게 좀 이상해서 다른 이미지를 넣음.

 

학교 밥인데 메뉴도 두 가지, 가격은 5,000원

 

 

 

 

 

 

 

반응형