개발자/라즈베리파이4

Raspberry Pi로 Ubidots에 데이터 보내고 받기 2

지구빵집 2020. 11. 4. 21:50
반응형

 

Raspberry Pi로 Ubidots에 데이터 보내고 받기 2 

 

Ubidots에 데이터를 송신하고 최근 데이터 하나를 받는 테스트를 진행했습니다. 이전 포스팅에서 더욱 확장하여 여러 가지 센서 데이터를 보내서 웹에서 확인하는 실습을 진행합니다. 물론 라즈베리파이 기반에서 합니다. 특별히 라즈베리파이 버전과 상관은 없습니다. Ethernet 이든 WiFi 연결도 상관없이 인터넷만 연결하면 됩니다. 이전 포스팅을 따라 하셨다면 여기서 시작하시고 아직 하지 않으셨으면 아래 링크를 따라가 참고하시기 바랍니다.

 

Raspberry Pi로 Ubidots에 데이터 보내고 받기 1 

 

1. 디지털 온습도 센서 달기

 

실습에서 사용하는 온도 습도 센서는 디지털 온습도 센서 -DHT21/AM2301 (Digital Temperature and Humidity Sensor -DHT21/AM2301) 입니다. 자세한 사항은 AM2302 데이터쉬트를 참고하세요.

 

  • 본 제품은 온습도 센서 AM2301입니다.
  • AM2301은 DHT21 센서의 와이어 장착 버전으로 좀 더 큰 플라스틱 몸체를 가지고 있는 센서입니다.
  • 정전식 습도 센서이며, 온도를 측정하기 위해서는 써미스터를 사용하는 센서로 데이터 핀으로 센싱 값을 출력합니다.
  • 센서 데이터는 매 2초 단위로 리프레쉬 됩니다.
센서 특징
Dimension: 59 * 27 * 13mm
3.5-5.5V Input
1-1.5mA measuring current
Humidity from 0-100% RH
-40 - 80 degrees C temperature
range+-3% RH accuracy+-0.5 degrees C
Model: AM2301

 

디지털 온습도 센서 -DHT21/AM2301 (Digital Temperature and Humidity Sensor -DHT21/AM2301)

 

AM2301 온도 습도 센서에 대한 자세한 설명과 센서 정상 동작 여부를 아두이노 우노에서 확인하는 예제를 참고하세요. 일단 라이브러리는 SimpleDHT 라이브러릴 사용하고, SimpleDHT22 dht22; 방식으로 인스턴스를 만들어 사용합니다. 센서는 정상 동작합니다.

 

한 가지 더 주문할 사항은 raspberrypi에서 AM2301 센서에서 온도 습도를 얻는 테스트를 진행하셔야 합니다. 아래 샘플 코드는 파이선 코드인데 바로 돌아가지는 않습니다. 반드시 아래 자료 링크를 따라가셔서 설치와 테스트를 하시기 바랍니다. 

 

RaspberryPi AM2301 온도 습도 센서 python 코드 using the DHT22

 

파이선 코드는 아래와 같습니다. 앞의 예제에서는 DHT pin 4번에 연결했지만 이 예제에서는 24번에 연결했습니다. 물리적인 번호는 18번입니다. 착오 없으시기 바랍니다.

 

#Libraries
import Adafruit_DHT as dht
from time import sleep
#Set DHT22 DATA pin
DHT = 24
while True:
    #Read Temp and Hum from DHT22
    h,t = dht.read_retry(dht.DHT22, DHT)
    #Print Temperature and Humidity on Shell window
    print('Temp={0:0.1f}*C  Humidity={1:0.1f}%'.format(t,h))
    sleep(5) #Wait 5 seconds and read again

 

그럼 이 상태에서 코드를 합칩니다. 합쳐서 잘 동작하는 코드를 설명합니다. 이전의 포스팅과 연결되는 코드이므로 바뀌는 코드만 설명하고 전체 코드를 아래에 올리겠습니다.

 

우선 adafruit_DHT 라이브러리를 import 합니다. 또한 DHT22 센서의 data pin을 정의합니다. 연결 상태에 따라 달라질 수 있습니다.

 

import time
import requests
import math
import random
import datetime

import Adafruit_DHT as dht

#Set DHT22 DATA pin
DHT = 24

 

온도와 습도를 구하는 함수를 정의합니다. 리턴 값이 두 개여야 온도와 습도를 전달합니다.

 

def temphumi():
    #Read Temp and Hum from DHT22
    h,t = dht.read_retry(dht.DHT22, DHT)
    #Print Temperature and Humidity on Shell window
    #print('Temp={0:0.1f}*C  Humidity={1:0.1f}%'.format(t,h))
    return h, t
	#sleep(5) #Wait 5 seconds and read again

 

ubidots 서버로 보낼 데이터를 만드는 곳에서 리턴 받은 값을 value_1과 value_2 에 넣어줍니다. 파이선은 정말 단순하면서도 강력하군요.

 

def build_payload(variable_1, variable_2, variable_3):
    # Creates two random values for sending data
    #value_1 = random.randint(-10, 50)
    #value_2 = random.randint(0, 85)
    value_1, value_2 = temphumi() 

    # Creates a random gps coordinates
    lat = random.randrange(34, 36, 1) + \
        random.randrange(1, 1000, 1) / 1000.0
    lng = random.randrange(-83, -87, -1) + \
        random.randrange(1, 1000, 1) / 1000.0
    payload = {variable_1: value_1,
               variable_2: value_2,
               variable_3: {"value": 1, "context": {"lat": lat, "lng": lng}}}

    return pa

 

잘 동작하는 전체 코드를 올립니다. 부여받은 토큰을 넣습니다. 

 

import time
import requests
import math
import random
import datetime

import Adafruit_DHT as dht

#Set DHT22 DATA pin
DHT = 24

TOKEN = "BBFF-***********"  # Put your TOKEN here
DEVICE_LABEL = "machine"  # Put your device label here 
VARIABLE_LABEL_1 = "temperature"  # Put your first variable label here
VARIABLE_LABEL_2 = "humidity"  # Put your second variable label here
VARIABLE_LABEL_3 = "position"  # Put your second variable label here


def temphumi():
    #Read Temp and Hum from DHT22
    h,t = dht.read_retry(dht.DHT22, DHT)
    #Print Temperature and Humidity on Shell window
    #print("Temp={0:0.1f}*C  Humidity={1:0.1f}%".format(t,h))
    return h, t
	#sleep(5) #Wait 5 seconds and read again

def build_payload(variable_1, variable_2, variable_3):
    # Creates two random values for sending data
    #value_1 = random.randint(-10, 50)
    #value_2 = random.randint(0, 85)
    value_1, value_2 = temphumi() 

    # Creates a random gps coordinates
    lat = random.randrange(34, 36, 1) + \
        random.randrange(1, 1000, 1) / 1000.0
    lng = random.randrange(-83, -87, -1) + \
        random.randrange(1, 1000, 1) / 1000.0
    payload = {variable_1: value_1,
               variable_2: value_2,
               variable_3: {"value": 1, "context": {"lat": lat, "lng": lng}}}

    return payload


def post_request(payload):
    # Creates the headers for the HTTP requests
    url = "http://industrial.api.ubidots.com"
    url = "{}/api/v1.6/devices/{}".format(url, DEVICE_LABEL)
    headers = {"X-Auth-Token": TOKEN, "Content-Type": "application/json"}

    # Makes the HTTP requests
    status = 400
    attempts = 0
    while status >= 400 and attempts <= 5:
        req = requests.post(url=url, headers=headers, json=payload)
        status = req.status_code
        attempts += 1
        time.sleep(1)

    # Processes results
    if status >= 400:
        print("[ERROR] Could not send data after 5 attempts, please check \
            your token credentials and internet connection")
        return False

    print("[INFO] request made properly, your device is updated")
    now= datetime.datetime.now()
    print(now)
    return True


def main():
    payload = build_payload(
        VARIABLE_LABEL_1, VARIABLE_LABEL_2, VARIABLE_LABEL_3)

    print("[INFO] Attemping to send data")
    post_request(payload)


if __name__ == '__main__':
    while (True):
        main()
        time.sleep(60)
			
		

 

여기까지 입니다. 사이트 가서 확인하니 데이터가 잘 들어 옵니다. 우선 출력코드는 아래와 같습니다.

 

pi@raspberrypi:~/ubidots $ python ubi_test_post.py
Temp=29.5*C  Humidity=26.2%
[INFO] Attemping to send data
[INFO] request made properly, your device is updated
2020-11-06 18:07:45.269437
Temp=29.3*C  Humidity=26.7%
[INFO] Attemping to send data
[INFO] request made properly, your device is updated
2020-11-06 18:09:00.095766
Temp=28.9*C  Humidity=26.1%
[INFO] Attemping to send data
[INFO] request made properly, your device is updated
2020-11-06 18:10:02.258796
Temp=29.7*C  Humidity=26.2%
[INFO] Attemping to send data
[INFO] request made properly, your device is updated
2020-11-06 18:11:09.379709
Temp=29.7*C  Humidity=26.2%
[INFO] Attemping to send data
[INFO] request made properly, your device is updated
2020-11-06 18:12:11.463281

 

ubidots 사이트의 디바이스에서 본 데이터 입니다. 정확하게 1분 마다 측정한 온도와 습도 값이 입력됩니다.

 

다음은 조도 센서로 사무실 안의 밝기를 어둡다, 밝다 정도를 측정하여 전송하는 코드를 추가하겠습니다. 읽어주셔서 감사합니다. 

 

ubidots 화면

 

라즈베리파이에 am2301 센서 연결

 

 

반응형