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

비밀번호

댓글 작성자
 




1  [2]  3  4  5  6  7  8  9  10  11  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13576정성태3/8/20241543닷넷: 2228. .NET Profiler - IMetaDataEmit2::DefineMethodSpec 사용법
13575정성태3/7/20241676닷넷: 2227. 최신 C# 문법을 .NET Framework 프로젝트에 쓸 수 있을까요?
13574정성태3/6/20241557닷넷: 2226. C# - "Docker Desktop for Windows" Container 환경에서의 IPv6 DualMode 소켓
13573정성태3/5/20241563닷넷: 2225. Windbg - dumasync로 분석하는 async/await 호출
13572정성태3/4/20241641닷넷: 2224. C# - WPF의 Dispatcher Queue로 알아보는 await 호출의 hang 현상파일 다운로드1
13571정성태3/1/20241620닷넷: 2223. C# - await 호출과 WPF의 Dispatcher Queue 동작 확인파일 다운로드1
13570정성태2/29/20241633닷넷: 2222. C# - WPF의 Dispatcher Queue 동작 확인파일 다운로드1
13569정성태2/28/20241545닷넷: 2221. C# - LoadContext, LoadFromContext 그리고 GAC파일 다운로드1
13568정성태2/27/20241606닷넷: 2220. C# - .NET Framework 프로세스의 LoaderOptimization 설정을 확인하는 방법파일 다운로드1
13567정성태2/27/20241618오류 유형: 898. .NET Framework 3.5 이하에서 mscoree.tlb 참조 시 System.BadImageFormatException파일 다운로드1
13566정성태2/27/20241631오류 유형: 897. Windows 7 SDK 설치 시 ".NET Development" 옵션이 비활성으로 선택이 안 되는 경우
13565정성태2/23/20241479닷넷: 2219. .NET CLR2 보안 모델에서의 개별 System.Security.Permissions 제어
13564정성태2/22/20241614Windows: 259. Hyper-V Generation 1 유형의 VM을 Generation 2 유형으로 바꾸는 방법
13563정성태2/21/20241645디버깅 기술: 196. windbg - async/await 비동기인 경우 메모리 덤프 분석의 어려움
13562정성태2/21/20241645오류 유형: 896. ASP.NET - .NET Framework 기본 예제에서 System.Web에 대한 System.IO.FileNotFoundException 예외 발생
13561정성태2/20/20241744닷넷: 2218. C# - (예를 들어, Socket) 비동기 I/O에 대한 await 호출 시 CancellationToken을 이용한 취소파일 다운로드1
13560정성태2/19/20241747디버깅 기술: 195. windbg 분석 사례 - Semaphore 잠금으로 인한 Hang 현상 (닷넷)
13559정성태2/19/20242624오류 유형: 895. ASP.NET - System.Security.SecurityException: 'Requested registry access is not allowed.'
13558정성태2/18/20241820닷넷: 2217. C# - 최댓값이 1인 SemaphoreSlim 보다 Mutex 또는 lock(obj)를 선택하는 것이 나은 이유
13557정성태2/18/20241620Windows: 258. Task Scheduler의 Author 속성 값을 변경하는 방법
13556정성태2/17/20241684Windows: 257. Windows - Symbolic (hard/soft) Link 및 Junction 차이점
13555정성태2/15/20241954닷넷: 2216. C# - SemaphoreSlim 사용 시 주의점
13554정성태2/15/20241709VS.NET IDE: 189. Visual Studio - 닷넷 소스코드 디컴파일 찾기가 안 될 때
13553정성태2/14/20241736닷넷: 2215. windbg - thin/fat lock 없이 동작하는 Monitor.Wait + Pulse
13552정성태2/13/20241692닷넷: 2214. windbg - Monitor.Enter의 thin lock과 fat lock
13551정성태2/12/20242017닷넷: 2213. ASP.NET/Core 웹 응용 프로그램 - 2차 스레드의 예외로 인한 비정상 종료
1  [2]  3  4  5  6  7  8  9  10  11  12  13  14  15  ...