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

비밀번호

댓글 작성자
 




... 76  77  78  79  80  [81]  82  83  84  85  86  87  88  89  90  ...
NoWriterDateCnt.TitleFile(s)
11908정성태5/22/201919837.NET Framework: 836. C# - Python range 함수 구현파일 다운로드1
11907정성태5/22/201916579오류 유형: 541. msbuild - MSB4024 The imported project file "...targets" could not be loaded
11906정성태5/21/201916798.NET Framework: 835. .NET Core/C# - 리눅스 syslog에 로그 남기는 방법
11905정성태5/21/201917367.NET Framework: 834. C# - 폴더 경로 문자열에서 "..", "." 표기를 고려한 최종 문자열을 얻는 방법 - 두 번째 이야기
11904정성태5/21/201925733.NET Framework: 833. C# - Open Hardware Monitor를 이용한 CPU 온도 정보 [1]파일 다운로드1
11903정성태5/21/201919562오류 유형: 540. .NET Core - System.PlatformNotSupportedException: The named version of this synchronization primitive is not supported on this platform.
11902정성태5/21/201917741오류 유형: 539. mstest 실행 시 "The directory name is invalid." 오류 발생
11901정성태5/21/201919626오류 유형: 538. msbuild 오류 - Could not find a part of the path '%LOCALAPPDATA%\Temp\2\.NETFramework,Version=v4.0.AssemblyAttributes.cs'
11900정성태5/18/201918566오류 유형: 537. "sfc /scannow" 실행 중 시스템이 부팅되는 현상
11899정성태5/17/201919420Linux: 9. Linux에서 윈도우의 OutputDebugString 대신 사용할 수 있는 syslog [1]
11898정성태5/16/201921221VC++: 130. C++ string의 c_str과 data 함수의 차이점 [3]
11897정성태5/16/201928198오류 유형: 536. Visual Studio - "Developer Pack"을 설치했는데도 "대상 프레임워크" 목록에 나오지 않는 경우 [2]
11896정성태5/15/201923100개발 환경 구성: 440. C#, C++ - double의 Infinity, NaN 표현 방식파일 다운로드1
11895정성태5/12/201920970.NET Framework: 832. ML.NET Model Builder - 회귀(Regression), 다중 분류(Multi-class classification) 예제파일 다운로드1
11894정성태5/10/201922690VS.NET IDE: 135. Visual Studio - ML.NET Model Builder 소개 [5]
11893정성태5/10/201919611오류 유형: 535. C# 6.0 이상의 문법을 컴파일 시 오류가 발생한다면?
11892정성태5/10/201919443웹: 38. HTTP Cookie의 expires 시간 형식(RFC7231)
11891정성태5/9/201922515.NET Framework: 831. (번역글) .NET Internals Cookbook Part 12 - Memory structure, attributes, handles
11890정성태5/8/201917617개발 환경 구성: 439. "Visual Studio Enterprise is required to execute the test." 메시지와 관련된 코드 기록
11889정성태5/8/201918330개발 환경 구성: 438. mstest, QTAgent의 로그 파일 설정 방법
11888정성태5/8/201935683.NET Framework: 830. C# - 비동기 호출을 취소하는 CancellationToken의 간단한 예제 코드 [1]파일 다운로드1
11887정성태5/8/201921268.NET Framework: 829. C# - yield 문을 사용할 수 있는 메서드의 조건
11886정성태5/7/201919127오류 유형: 534. mstest.exe 실행 시 "Visual Studio Enterprise is required to execute the test." 오류 [2]
11885정성태5/7/201916013오류 유형: 533. mstest.exe 실행 시 "File extension specified '.loadtest' is not a valid test extension." 오류 발생
11884정성태5/5/201920843.NET Framework: 828. C# DLL에서 Win32 C/C++처럼 dllexport 함수를 제공하는 방법 - 두 번째 이야기
11883정성태5/3/201926038.NET Framework: 827. C# - 인터넷 시간 서버로부터 받은 시간을 윈도우에 적용하는 방법파일 다운로드1
... 76  77  78  79  80  [81]  82  83  84  85  86  87  88  89  90  ...