본문 바로가기
전자공학/LoRa 통신

아두이노 lora shield(로라 쉴드)로 thingspeak, thingview에 값을 띄워보자, lora shield 시작하기 - (4)

by ohj921189 2020. 8. 8.
반응형

저번 포스팅에서는 송신부, 게이트웨이 측의 결선 및 코드 업로드 시 주의사항에 대해 알려드렸습니다. 이번 포스팅에서는 송신부(노드) 측의 소스 코드 분석을 해보도록 하겠습니다. 

 

#include "DHT.h"
#include <SoftwareSerial.h>
#include "SNIPE.h"

#define DHTPIN 2     // what pin we're connected to

// Uncomment whatever type you're using!
#define DHTTYPE DHT11   // DHT 11 
//#define DHTTYPE DHT22   // DHT 22  (AM2302)
//#define DHTTYPE DHT21   // DHT 21 (AM2301)

#define ADDR  10 //(0x00 ~ 0xFF)
#define TXpin 11
#define RXpin 10
#define ATSerial Serial

// Connect pin 1 (on the left) of the sensor to +5V
// NOTE: If using a board with 3.3V logic like an Arduino Due connect pin 1
// to 3.3V instead of 5V!
// Connect pin 2 of the sensor to whatever your DHTPIN is
// Connect pin 4 (on the right) of the sensor to GROUND
// Connect a 10K resistor from pin 2 (data) to pin 1 (power) of the sensor

// Initialize DHT sensor for normal 16mhz Arduino
DHT dht(DHTPIN, DHTTYPE);
// NOTE: For working with a faster chip, like an Arduino Due or Teensy, you
// might need to increase the threshold for cycle counts considered a 1 or 0.
// You can do this by passing a 3rd parameter for this threshold.  It's a bit
// of fiddling to find the right value, but in general the faster the CPU the
// higher the value.  The default for a 16mhz AVR is a value of 6.  For an
// Arduino Due that runs at 84mhz a value of 30 works.
// Example to initialize DHT sensor for Arduino Due:
//DHT dht(DHTPIN, DHTTYPE, 30);

//16byte hex key
String lora_app_key = "11 22 33 44 55 66 77 88 99 aa bb cc dd ee ff 00";

SoftwareSerial DebugSerial(RXpin,TXpin);
SNIPE SNIPE(ATSerial);
char buffer[20];
int addr;

int echoPin=4;
int trigPin=5;

void setup() {
  ATSerial.begin(115200);
  pinMode(trigPin,OUTPUT);
  pinMode(echoPin,INPUT);
  while(ATSerial.read()>= 0) {}
  while(!ATSerial);

  DebugSerial.begin(115200);

  /* SNIPE LoRa Initialization */
  if (!SNIPE.lora_init()) {
    DebugSerial.println("SNIPE LoRa Initialization Fail!");
    while (1);
  }

  /* SNIPE LoRa Set AppKey */
  if (!SNIPE.lora_setAppKey(lora_app_key)) {
    DebugSerial.println("SNIPE LoRa app key value has not been changed");
  }  

  /* SNIPE LoRa Set Frequency */
  if (!SNIPE.lora_setFreq(LORA_CH_1)) {
    DebugSerial.println("SNIPE LoRa Frequency value has not been changed");
  }

  /* SNIPE LoRa Set Spreading Factor */
  if (!SNIPE.lora_setSf(LORA_SF_7)) {
    DebugSerial.println("SNIPE LoRa Sf value has not been changed");
  }

  /* SNIPE LoRa Set Rx Timeout 
   * If you select LORA_SF_12, 
   * RX Timout use a value greater than 5000  
  */
  if (!SNIPE.lora_setRxtout(5000)) {
    DebugSerial.println("SNIPE LoRa Rx Timout value has not been changed");
  }   
    
  DebugSerial.println("SNIPE LoRa DHT22 Recv");
 
  dht.begin();
}

void loop() {

  digitalWrite(trigPin,LOW);
  digitalWrite(echoPin,LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin,HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin,LOW);
  unsigned long duration=pulseIn(echoPin,HIGH);
  float distance=((float)(340*duration)/10000)/2;
  int i_distance,i_t,i_h;
  i_distance = int(distance);
  DebugSerial.println(i_distance);

  // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
  float h = dht.readHumidity();
  // Read temperature as Celsius
  float t = dht.readTemperature();
  // Read temperature as Fahrenheit
  float f = dht.readTemperature(true);

  // Check if any reads failed and exit early (to try again).
      if (isnan(h) || isnan(t) || isnan(f)) {
        DebugSerial.println("Failed to read from DHT sensor!");
        return;
      }

  // Compute heat index
  // Must send in temp in Fahrenheit!
  float hi = dht.computeHeatIndex(f, h);
  
  i_t = int(t);
  i_h = int(h);
  DebugSerial.print("Humidity: "); 
  DebugSerial.println(i_h);
  DebugSerial.print("Temperature: ");
  DebugSerial.println(i_t);

  String value = (String)i_distance + ":" + (String)i_h + ":" + (String)i_t;
  DebugSerial.println(value);
  SNIPE.lora_send(value);
  
  delay(1000);
}

소스를 업로드하기 전에 DHT.h, SNIPE.h 헤더 파일을 다운로드하시길 바랍니다. SNIPE 헤더 파일은 이전 포스팅에 올려두었으니 참고해 주시고 DHT 헤더 파일은 따로 검색하셔서 다운로드하시길 바랍니다. 예제 코드를 바탕으로 하여 필요한 부분은 추가하는 식으로 코드를 작성하였습니다. 예제에 있는 부분은 매뉴얼 로라와 놀자 아두이노 편(소프트웨어 편)에 자세히 설명이 되어 있으므로 제가 따로 추가한 부분에 대해서만 설명드리도록 하겠습니다.

 

 

 

제가 참고한 것은 SNIPE-master 라이브러리의 DHT_Recv2 예제입니다. DHT_Recv2 예제를 보게 되면 윗부분에 DHTTYPE을 설정하는 부분이 있는데 기본 값으로 DHT22로 설정이 되어있습니다. 저는 DHT11을 사용하였기 때문에 DHT22 부분을 주석 처리하고 DHT11로 수정하였습니다.

 

로라 쉴드의 app key를 설정하는 부분, SNIPE LoRa Initialization, SNIPE LoRa Set AppKey,  SNIPE LoRa Set Frequency, SNIPE LoRa Set Spreading Factor, SNIPE LoRa Set Rx Timeout은 로라 쉴드를 사용하기 위해 필요한 기초적인 코드라고 판단되어 변형하지 않고 setup 부분에 그대로 두었습니다. 

 

setup 부분에 추가한 것은 초음파 센서를 사용하기 위해 필요한 핀 설정 부분으로 echo 핀을 4번, trig 핀을 5번으로 설정하였습니다.

 

void loop 쪽을 보면 처음에 digitalWrite(trigPin, LOW);부터 float distance=((float)(340*duration)/10000)/2; 까지는 일반적으로 초음파 거리 측정 센서를 사용할 때 쓰이는 코드입니다.

int i_distance, i_t, i_h; i_distance = int(distance);
거리 값이 소수점까지 포함된 형태로 저장되는데 소수점까지 필요가 없어서 정수형으로 형 변환을 하였습니다.

그 뒤로 float h = dht.readHumidity();부터 float hi = dht.computeHeatIndex(f, h); 까지는 온습도센서를 사용하기 위해 필요한 코드 부분입니다.

i_t = int(t); i_h = int(h);
온습도센서도 마찬가지로 정수형인 int로 형 변환을 해주었습니다.

DebugSerial.print 함수는 Serial.print와 같은 기능을 하는 함수입니다.

 

String value = (String) i_distance + ":" + (String) i_h + ":" + (String) i_t;
데이터를 보내는 lora_send 함수가 String 형식으로만 데이터 전송이 가능하기 때문에 앞의 정수형의 값을 String 형식으로 변환해 주어야 합니다. 한 번에 여러 개의 값을 보내기 위해 +를 이용하여 값을 묶어주었습니다. 000 : 000 : 000 형식으로 value에 저장이 됩니다.


SNIPE.lora_send(value);
이 함수를 사용하여 값을 다른 보드로 전송합니다.

 

반응형

댓글