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)
12396정성태11/3/20208414VS.NET IDE: 152. Visual Studio - "Tools" / "External Tools..."에 등록된 외부 명령어에 대한 단축키 설정 방법
12395정성태11/3/20209732오류 유형: 677. SSMS로 DB 접근 시 The server principal "..." is not able to access the database "..." under the current security context.
12394정성태11/3/20208155오류 유형: 676. cacls - The Recycle Bin on ... is corrupted. Do you want to empty the Recycle Bin for this drive?
12393정성태11/3/20208652오류 유형: 675. Visual Studio - 닷넷 응용 프로그램 디버깅 시 Disassembly 창에서 BP 설정할 때 "Error while processing breakpoint." 오류
12392정성태11/2/202012758.NET Framework: 959. C# 9.0 - (9) 레코드(Records) [4]파일 다운로드1
12390정성태11/1/202011031디버깅 기술: 173. windbg - System.Configuration.ConfigurationErrorsException 예외 분석 방법
12389정성태11/1/202010767.NET Framework: 958. C# 9.0 - (8) 정적 익명 함수 (static anonymous functions)파일 다운로드1
12388정성태10/29/202010223오류 유형: 674. 어느 순간부터 닷넷 응용 프로그램 실행 시 System.Configuration.ConfigurationErrorsException 예외가 발생한다면?
12387정성태10/28/202011009.NET Framework: 957. C# - static 필드의 정보가 GC Heap에 저장될까요? [3]파일 다운로드1
12386정성태10/28/202011252Linux: 34. 사용자 정보를 함께 출력하는 리눅스의 ps 명령어 사용 방법
12385정성태10/28/20209069오류 유형: 673. openssl - req: No value provided for Subject Attribute CN, skipped
12384정성태10/27/202010270오류 유형: 672. AllowPartiallyTrustedCallers 특성이 적용된 어셈블리의 struct 멤버 메서드를 재정의하면 System.Security.VerificationException 예외 발생
12383정성태10/27/202011160.NET Framework: 956. C# 9.0 - (7) 패턴 일치 개선 사항(Pattern matching enhancements) [3]파일 다운로드1
12382정성태10/26/20208888오류 유형: 671. dotnet build - The local source '...' doesn't exist
12381정성태10/26/202010546VC++: 137. C++ stl map의 사용자 정의 타입을 key로 사용하는 방법 [1]파일 다운로드1
12380정성태10/26/20207971오류 유형: 670. Visual Studio - Squash_FailureCommitsReset
12379정성태10/21/202010971.NET Framework: 955. .NET 메서드의 Signature 바이트 코드 분석 [1]파일 다운로드2
12378정성태10/15/202010387.NET Framework: 954. C# - x86/x64 환경에 따라 달라지는 P/Invoke 함수의 export 이름파일 다운로드1
12377정성태10/15/202011683디버깅 기술: 172. windbg - 파일 열기 시점에 bp를 걸어 파일명 알아내는 방법(Managed/Unmanaged)
12376정성태10/15/20208400오류 유형: 669. windbg - sos의 name2ee 명령어 실행 시 "Failed to request module list." 오류
12375정성태10/15/20209782Windows: 177. 윈도우 탐색기에서 띄우는 cmd.exe 창의 디렉터리 구분 문자가 'Yen(&#0165;)' 기호로 나오는 경우 [1]
12374정성태10/14/202014394.NET Framework: 953. C# 9.0 - (6) 함수 포인터(Function pointers) [1]파일 다운로드2
12373정성태10/14/20209686.NET Framework: 952. OpCodes.Box와 관련해 IL 형식으로 직접 코딩 시 유의할 점
12372정성태10/13/202011498.NET Framework: 951. C# 9.0 - (5) 로컬 함수에 특성 지정 가능(Attributes on local functions)파일 다운로드1
12371정성태10/13/202010282개발 환경 구성: 519. Visual Studio의 Ctrl+Shift+U (Edit.MakeUppercase) 단축키가 동작하지 않는 경우
12370정성태10/13/202011181Linux: 33. Linux - nmcli를 이용한 고정 IP 설정
... 46  47  48  49  [50]  51  52  53  54  55  56  57  58  59  60  ...