Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
(연관된 글이 2개 있습니다.)

ThingSpeak 사물인터넷 플랫폼에 ESP8266 NodeMCU v1 + 조도 센서 장비 연동

지난 글에서,

C# - CoAP 서버 및 클라이언트 제작 (UDP 소켓 통신)
; https://www.sysnet.pe.kr/2/0/12629

CoAP 프로토콜을 소개해 드렸는데요, 물론 이렇게 해서 서버를 만들어도 되지만 이미 사물 인터넷 데이터를 취급하는 온라인 플랫폼들이 많이 있습니다. 그중의 한 곳이 바로 MathWorks에서 만든 ThingSpeak"인데요,

ThingSpeak for IoT Projects
; https://thingspeak.com/

사용 방법도 매우 간단합니다, 해당 사이트에 (회원 가입 후) 로그인하고 IoT 데이터를 수집할 수 있는 "Channel"을 다음의 화면에서 "New Channel" 버튼을 눌러,

how_to_use_thing_speak_0.png

여러분의 수집 데이터를 위한 필드를 정의한 후,

how_to_use_thing_speak_1.png

(이하 기본값으로 두고) "Save Channel" 버튼으로 생성합니다. 이렇게 생성한 Channel로 여러분의 기기에서 생성한 데이터를 보내면 되는데요, 이를 위해 해당 채널의 설정에서 "Channel ID"와 "API Key"를 복사해 둡니다.

how_to_use_thing_speak_2.png

위의 페이지에서는 안 보이지만, 우측에는 해당 API Key를 가지고 각각의 요청을 어떻게 발생시키는지에 대한 GET 요청을 보여주므로,

Write a Channel Feed
GET https://api.thingspeak.com/update?api_key=...[생략]...&field1=0

Read a Channel Feed
GET https://api.thingspeak.com/channels/1380944/feeds.json?api_key=...[생략]...&results=2

Read a Channel Field
GET https://api.thingspeak.com/channels/1380944/fields/1.json?api_key=...[생략]...&results=2

Read Channel Status Updates
GET https://api.thingspeak.com/channels/1380944/status.json?api_key=...[생략]...

이에 맞게 HTTP 통신으로 쉽게 데이터를 전송/조회할 수 있습니다.




비록 Get HTTP 요청 규약이 있긴 하지만 이것을 NodeMCU v1에서 동작하는 것은 ThingSpeak 라이브러리 덕분에 보다 쉽게 연동할 수 있습니다. 이를 위해 우선 Arduino IDE의 "Library Manager(Ctrl + Shift + I)"에서 "ThingSpeak by MathWorks"를 설치한 후 다음의 예제 코드를 곁들여,

thingspeak-esp-examples/examples/A0_to_ThingSpeak.ino
; https://github.com/nothans/thingspeak-esp-examples/blob/master/examples/A0_to_ThingSpeak.ino

thingspeak-esp-examples/examples/RSSI_to_ThingSpeak.ino
; https://github.com/nothans/thingspeak-esp-examples/blob/master/examples/RSSI_to_ThingSpeak.ino

코딩을 하면 됩니다. 자, 그럼 이제까지 해온 실습을 모두 종합해서, ^^

NodeMCU ESP8266 보드의 A0 핀 사용법 - Cds Cell(GL3526) 조도 센서 연동
; https://www.sysnet.pe.kr/2/0/12630

New NodeMCU v3(ESP8266)의 http 통신
; https://www.sysnet.pe.kr/2/0/11762

ThingSpeak의 Channel ID, API Key, WiFi의 SSID, 암호를 담은 secrets.h 헤더 파일을 생성해 두고,

#define SECRET_SSID "[...ssid...]"
#define SECRET_PASS "[...wifi_password...]"

#define SECRET_CH_ID 000000    // Channel ID
#define SECRET_WRITE_APIKEY "...[write_api_key]..."

다음과 같이 조도 센서의 밝기와 와이파이 신호의 세기 값을 ThinkSpeak 측에 전송하는 코드를 작성할 수 있습니다.

#include "ThingSpeak.h"
#include "secrets.h"

unsigned long myChannelNumber = SECRET_CH_ID;
const char * myWriteAPIKey = SECRET_WRITE_APIKEY;

#include <ESP8266WiFi.h>

int _photoSensorPin = A0;

const char *ssid = SECRET_SSID;
const char *pass = SECRET_PASS;

WiFiClient  client;

void setup() {
  Serial.begin(115200);

  delay(1000);
  ThingSpeak.begin(client);    
}

void loop() {

  if (WiFi.status() != WL_CONNECTED)
  {
    WiFi.begin(ssid, pass);
    Serial.print(".");    
    delay(5000);
  }

  if (WiFi.status() != WL_CONNECTED)
  {
    return;
  }
  
  int cdsValue = analogRead(_photoSensorPin);
  long rssi = WiFi.RSSI();

  ThingSpeak.setField(1, (float)cdsValue);
  ThingSpeak.setField(2, (float)rssi);
  int httpCode = ThingSpeak.writeFields(myChannelNumber, myWriteAPIKey);

  if (httpCode == 200) {
    Serial.println("Channel write successful.");
  }
  else {
    Serial.println("Problem writing to channel. HTTP error code " + String(httpCode));
  }
  
  delay(1000 * 20);
}

실 기기에 업로드 후, 동작을 하면서 약간의 데이터가 쌓이면 ThinkSpeak 웹 페이지에서 다음과 같은 그래프 데이터를 제공하는데,

how_to_use_thing_speak_3.png

결국 "사물인터넷 플랫폼"이란 것은 "ThinkSpeak"처럼 IoT 기기의 데이터를 축적해 다룰 수 있는 온라인 플랫폼인 것입니다.

(첨부 파일은 이 글의 아두이노 프로젝트를 포함합니다.)




물론, 공짜가 아닙니다. ^^ 상용으로 사용하실 생각이라면 다음의 라이선스를 확인하는 것이 좋을 듯합니다.

ThingSpeak™ Licensing FAQ
; https://thingspeak.com/pages/license_faq

참고로, Free 사용은 1년에 3백만 메시지 이상을 보낼 수 없습니다. 그렇다면 하루에 8,200개 정도, 시간당 342개 정도, 분당 5개 정도의 데이터만 보낼 수 있습니다. 따라서 12초 정도에 한 번만 메시지를 보내면 1년 치 사용량이 만료되는 것입니다.

또한, Free 사용은 총 4개의 채널만 생성할 수 있습니다. 그렇다면 채널 한 개가 늘어날 때마다 각각 12, 24, 36, 48초에 한 번씩만 메시지를 보내야 합니다.

또 한 가지 제약은, Free 사용에서는 전송 주기를 15초 이상으로 설정해야 합니다. 가령, 그렇지 않고 5초 delay로 전송을 하는 경우 -401 오류 코드가 발생합니다. (예제 코드에서 delay 20초를 준 것이 괜히 있는 것이 아닙니다. ^^)




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]

[연관 글]






[최초 등록일: ]
[최종 수정일: 5/7/2021]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 




... 46  47  48  49  50  51  52  53  54  55  56  57  [58]  59  60  ...
NoWriterDateCnt.TitleFile(s)
12192정성태3/14/202012330개발 환경 구성: 484. docker - Sybase Anywhere 16 컨테이너 실행
12191정성태3/14/202012696개발 환경 구성: 483. docker - OracleXE 컨테이너 실행 [1]
12190정성태3/14/20208789오류 유형: 606. Docker Desktop 업그레이드 시 "The process cannot access the file 'C:\Program Files\Docker\Docker\resources\dockerd.exe' because it is being used by another process."
12189정성태3/13/202013690개발 환경 구성: 482. Facebook OAuth 처리 시 상태 정보 전달 방법과 "유효한 OAuth 리디렉션 URI" 설정 규칙
12188정성태3/13/202016232Windows: 169. 부팅 시점에 실행되는 chkdsk 결과를 확인하는 방법
12187정성태3/12/20208591오류 유형: 605. NtpClient was unable to set a manual peer to use as a time source because of duplicate error on '...'.
12186정성태3/12/20209725오류 유형: 604. The SysVol Permissions for one or more GPOs on this domain controller and not in sync with the permissions for the GPOs on the Baseline domain controller.
12185정성태3/11/202010444오류 유형: 603. The browser service was unable to retrieve a list of servers from the browser master...
12184정성태3/11/202011814오류 유형: 602. Automatic certificate enrollment for local system failed (0x800706ba) The RPC server is unavailable. [3]
12183정성태3/11/202010186오류 유형: 601. Warning: DsGetDcName returned information for \\[...], when we were trying to reach [...].
12182정성태3/11/202011363.NET Framework: 901. C# Windows Forms - Vista/7 이후의 Progress Bar 업데이트가 느린 문제파일 다운로드1
12181정성태3/11/202012134기타: 76. 재현 가능한 최소한의 예제 프로젝트란? - 두 번째 예제파일 다운로드1
12180정성태3/10/20208755오류 유형: 600. "Docker Desktop for Windows" - EXPOSE 포트가 LISTENING 되지 않는 문제
12179정성태3/10/202020201개발 환경 구성: 481. docker - PostgreSQL 컨테이너 실행
12178정성태3/10/202011721개발 환경 구성: 480. Linux 운영체제의 docker를 위한 tcp 바인딩 추가 [1]
12177정성태3/9/202011290개발 환경 구성: 479. docker - MySQL 컨테이너 실행
12176정성태3/9/202010723개발 환경 구성: 478. 파일의 (sha256 등의) 해시 값(checksum) 확인하는 방법
12175정성태3/8/202010826개발 환경 구성: 477. "Docker Desktop for Windows"의 "Linux Container" 모드를 위한 tcp 바인딩 추가
12174정성태3/7/202010390개발 환경 구성: 476. DockerDesktopVM의 파일 시스템 접근 [3]
12173정성태3/7/202011394개발 환경 구성: 475. docker - SQL Server 2019 컨테이너 실행 [1]
12172정성태3/7/202016246개발 환경 구성: 474. docker - container에서 root 권한 명령어 실행(sudo)
12171정성태3/6/202011331VS.NET IDE: 143. Visual Studio - ASP.NET Core Web Application의 "Enable Docker Support" 옵션으로 달라지는 점 [1]
12170정성태3/6/20209864오류 유형: 599. "Docker Desktop is switching..." 메시지와 DockerDesktopVM CPU 소비 현상
12169정성태3/5/202011871개발 환경 구성: 473. Windows nanoserver에 대한 docker pull의 태그 사용 [1]
12168정성태3/5/202012606개발 환경 구성: 472. 윈도우 환경에서의 dockerd.exe("Docker Engine" 서비스)가 Linux의 것과 다른 점
12167정성태3/5/202011832개발 환경 구성: 471. C# - 닷넷 응용 프로그램에서 DB2 Express-C 데이터베이스 사용 (3) - ibmcom/db2express-c 컨테이너 사용
... 46  47  48  49  50  51  52  53  54  55  56  57  [58]  59  60  ...