카테고리 없음

아두이노 Cactus Micro ESP8266WiFi 클라이언트 Thingspeak 웹서버 코딩 예제: II

coding art 2017. 1. 13. 18:58
728x90


본 프로그래밍 예제는 반드시 앞서의 예제와 연결된 내용임을 참조하기 바란다. 













Cactus Micro 모듈 프로그래밍에 반드시 필요한 라이브러리는 Github로부터 다운 받도록 한다.

인터넷 url 주소는 다음과 같다.
https://github.com/tuanpmt/espduino
espduino 디렉토리가 Cactus Micro 보드 프로그램에 필요한 라이브러리이다.
반드시 아두이노 라이브러리 디렉토리 나 아니면 자신이 잘아는 경로에 다운 받아서 압축을 풀면 espduino-master 디렉토리가 생성된다.
아두이노 편집기 스케치 탭에서 라이브러리 포함하기 탭에서 .ZIP 라이브러리 추가 명령을 클릭한 후 espduino-master 디렉토리 경로를 정확하게 설정한다.





라이브러리 내부를 보면 크게 mqtt와 rest가 들어 있다.
본 프로그램에서는 특별한 센서 사용 없이 구하기 쉬우며 배선이 간단한 가변 저항만을 사용한 rest를 사용하는 프로그램을 제시한다.


Examples 디렉토리에 예제 프로그램이 들어 있는데 아래에 제시된 프로그램은 가변저항 아날로그 입력 값을 ThingSpeak에 전송할 수 있도록 수정된 프로그램이다.







Cactus_ thingspeak_resistor_03

#include <espduino.h>   // 라이브러리
#include <rest.h>        //라이브러리


#define PIN_ENABLE_ESP 13         // Cactus 의 13번 핀 상태 지정
#define SSID  "ABCDEFGHIJKLMN"  // 자신의 스마트폰 핫 스팟 ID
#define PASS  "00000000"   // 비밀번호 없으며 그대로 있으면 입력

int InputAnalog = 0;     //아날로그 핀 초기화

// replace with your channel's thingspeak API key
String apiKey = "API_Key"; //ThingSpeak에서 부여 받은 Write API Key 값

ESP esp(&Serial1, &Serial, PIN_ENABLE_ESP);

REST rest(&esp);

boolean wifiConnected = false;

void wifiCb(void* response)
{
  uint32_t status;
  RESPONSE res(response);

  if(res.getArgc() == 1) {
    res.popArgs((uint8_t*)&status, 4);
    if(status == STATION_GOT_IP) {
      Serial.println("WIFI CONNECTED");
    
      wifiConnected = true;
    } else {
      wifiConnected = false;
    }   
  }
}

void setup() {
  Serial1.begin(19200); // NodeMCU와는 전송속도가 다름
  Serial.begin(19200);
  esp.enable();
  delay(500);
  esp.reset();
  delay(500);
  while(!esp.ready());

  Serial.println("ARDUINO: setup rest client");
  if(!rest.begin("api.thingspeak.com")) {
    Serial.println("ARDUINO: failed to setup rest client");
    while(1);
  }

  /*setup wifi*/
  Serial.println("ARDUINO: setup wifi");
  esp.wifiCb.attach(&wifiCb);

  esp.wifiConnect(SSID, PASS);
  Serial.println("ARDUINO: system started");
}

void loop() {
  char response[266];
  esp.process();
  if(wifiConnected) {

 // read the value from InputAnalog.
  int val = 0;
      val= analogRead(InputAnalog);  
 // convert to float temp: temp value is in 0-1023 range
 float temp = val;

      char buff[64];
      char strTemp[6];
      dtostrf(temp, 4, 1, strTemp);//실수 temp를 처리하는 C 루틴

      sprintf(buff, "/update?api_key=API-Key&field1=%s",  strTemp);//API Key 입력

      rest.get((const char*)buff);
      Serial.println(strTemp);
//      Serial.println("ARDUINO: send get");

      if(rest.getResponse(response, 266) == HTTP_STATUS_OK){
//        Serial.println("ARDUINO: GET successful");
        Serial.println(response);//시리얼창에서 몇번째 데이터를 수신했는지 정수 값 출력
     
      delay(16000);// ThingSpeak에서 요구되는 최소한의 샘플링 간격 15초 이상
  
    }
    else {
      Serial.print("error,\r\n");
    }
    
  }
   
}.


스마트 폰 핫스팟을 켜고 동시에 아두이노 편집기에서 보드는 LilyPad Arduino USB로 지정후 COM 포트가 인식이 되면 업로딩한다.





프로그램이 수행되면 시리얼 모니터 창에서 핫스팟에서 할당된 IP를 출력하고 가변 저항에 걸린 전압 값을 출력한다.









ThingSpeak에서 데이터 개수 30을 지정하고 가변 저항을 인위적으로 돌려보아 출력한 결과이다.


NodeMCU Web Server 예제를 참고로 Cactus 모듈도 Web Server 예제로 전환하기 위해서는 서로 사용하는 라이브러리가 다르므로 프로그래밍이 다소 어려울 수 있다. 하지만 불가능하지는 않다고 보이며 관심 있는 분들의 프로그래밍을 권장하는 바이다.

반대로 NodeMCU 모듈에서 ThingSpeak에 데이터를 송신하여 그래프를 작성할 수 있도록 웹서버 프로그램을 수정할 계획이다.