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)
12421정성태11/19/20208818.NET Framework: 972. DNNE가 출력한 NE DLL을 직접 생성하는 방법파일 다운로드1
12420정성태11/19/20207998오류 유형: 684. Visual C++ - MSIL .netmodule or module compiled with /GL found; restarting link with /LTCG; add /LTCG to the link command line to improve linker performance
12419정성태11/19/20209277VC++: 139. Visual C++ - .NET Core의 nethost.lib와 정적 링크파일 다운로드1
12418정성태11/19/202011312오류 유형: 683. Visual C++ - error LNK2038: mismatch detected for 'RuntimeLibrary': value 'MT_StaticRelease' doesn't match value 'MDd_DynamicDebug'파일 다운로드1
12417정성태11/19/20208723오류 유형: 682. Visual C++ - warning LNK4099: PDB '...pdb' was not found with '...lib(pch.obj)' or at '...pdb'; linking object as if no debug info
12416정성태11/19/20209998오류 유형: 681. Visual C++ - error LNK2001: unresolved external symbol _CrtDbgReport
12415정성태11/18/202010112.NET Framework: 971. UnmanagedCallersOnly 특성과 DNNE 사용파일 다운로드1
12414정성태11/18/202011145VC++: 138. x64 빌드에서 extern "C"가 아닌 경우 ___cdecl name mangling 적용 [4]파일 다운로드1
12413정성태11/17/202010820.NET Framework: 970. .NET 5 / .NET Core - UnmanagedCallersOnly 특성을 사용한 함수 내보내기파일 다운로드1
12412정성태11/16/202013069.NET Framework: 969. .NET Framework 및 .NET 5 - UnmanagedCallersOnly 특성 사용파일 다운로드1
12411정성태11/12/202010098오류 유형: 680. C# 9.0 - Error CS8889 The target runtime doesn't support extensible or runtime-environment default calling conventions.
12410정성태11/12/20209972디버깅 기술: 174. windbg - System.TypeLoadException 예외 분석 사례
12409정성태11/12/202011338.NET Framework: 968. C# 9.0의 Function pointer를 이용한 함수 주소 구하는 방법파일 다운로드1
12408정성태11/9/202022918도서: 시작하세요! C# 9.0 프로그래밍 [8]
12407정성태11/9/202011660.NET Framework: 967. "clr!JIT_DbgIsJustMyCode" 호출이 뭘까요?
12406정성태11/8/202013220.NET Framework: 966. C# 9.0 - (15) 최상위 문(Top-level statements) [5]파일 다운로드1
12405정성태11/8/202010628.NET Framework: 965. C# 9.0 - (14) 부분 메서드에 대한 새로운 기능(New features for partial methods)파일 다운로드1
12404정성태11/7/202011174.NET Framework: 964. C# 9.0 - (13) 모듈 이니셜라이저(Module initializers)파일 다운로드1
12403정성태11/7/202011209.NET Framework: 963. C# 9.0 - (12) foreach 루프에 대한 GetEnumerator 확장 메서드 지원(Extension GetEnumerator)파일 다운로드1
12402정성태11/7/202011811.NET Framework: 962. C# 9.0 - (11) 공변 반환 형식(Covariant return types) [1]파일 다운로드1
12401정성태11/5/202010745VS.NET IDE: 153. 닷넷 응용 프로그램에서의 "My Code" 범위와 "Enable Just My Code"의 역할 [1]
12400정성태11/5/20207696오류 유형: 679. Visual Studio - "Source Not Found" 창에 "Decompile source code" 링크가 없는 경우
12399정성태11/5/202011434.NET Framework: 961. C# 9.0 - (10) 대상으로 형식화된 조건식(Target-typed conditional expressions)파일 다운로드1
12398정성태11/4/20209945오류 유형: 678. Windows Server 2008 R2 환경에서 Powershell을 psexec로 원격 실행할 때 hang이 발생하는 문제
12397정성태11/4/202010117.NET Framework: 960. C# - 조건 연산자(?:)를 사용하는 경우 달라지는 메서드 선택 사례파일 다운로드1
12396정성태11/3/20208414VS.NET IDE: 152. Visual Studio - "Tools" / "External Tools..."에 등록된 외부 명령어에 대한 단축키 설정 방법
... 46  47  48  [49]  50  51  52  53  54  55  56  57  58  59  60  ...