ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [Raspberry][Python] 라즈베리파이 + Ubidots로 온습도 데이터 출력, 시각화 (DHT11)
    프로그래밍/프로젝트 2021. 1. 2. 20:01

    사용한 환경

    (인터넷이 연결된) Raspberry Pi 4 

    DHT11 (온습도 센서)  -> 온습도 센서의 데이터 포트를    라즈베리파이의 GPIO 4번 포트에 장착해야 한다!

     

    배운 점

    IoT플랫폼인 ubidots를 통해 간단하게 라즈베리파이의 온습도 데이터를 실시간으로 웹에서 출력 및 시각화 할 수 있었다

    웹, 휴대폰과의 연동을 통해 많은 센서 데이터를 어디에서나 볼 수 있게 되었다 -> 다양한 작업에 응용 가능

     

    S 부분이 데이터 포트이다! 나머진 + - 에 장착하면 된다!

     

    ubidots 로그인 페이지

     

    따라하기

    import time
    import requests
    import math
    import random
    
    import Adafruit_DHT as dht
    
    TOKEN = "xxxxxxxxx"  # 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
    
    def build_payload(variable_1, variable_2):
        
        hum, temp = dht.read_retry(dht.DHT11, 4)
    
        value_1 = temp
        value_2 = hum
    
        payload = {variable_1: value_1,
                   variable_2: value_2}
        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")
        return True
    
    
    def main():
        payload = build_payload(
            VARIABLE_LABEL_1, VARIABLE_LABEL_2)
    
        print("[INFO] Attemping to send data")
        post_request(payload)
        print("[INFO] finished")
    
    
    if __name__ == '__main__':
        while (True):
            main()
            time.sleep(1)

    해당 코드에 TOKEN 값만 추가하고 라즈베리파이 환경에서 실행하면 자동으로 ubidots에 장치가 추가된다

    가장 중요한 자신의 TOKEN 값을 TOKEN변수에 넣어야 한다

    TOKEN : 아래의 자신의 TOKEN값을 찾는 방법을 참고하세요!

    DEVICE_LABEL : 자신이 원하는 장치명 입력 (아무거나 가능!, 필자는 machine이라고 이름 지었다)

    VARIABLE_LABEL_1 : 자신이 원하는 데이터명 입력 (아무거나 가능!, 필자는 temperature이라고 이름 지었다)

    VARIABLE_LABEL_2 : 자신이 원하는 데이터명 입력 (아무거나 가능!, 필자는 humidity이라고 이름 지었다)

    4부분은 DHT11 센서 데이터 포트가 GPIO 4에 꽂혀 있다는 의미이다.

    자신의 TOKEN값 찾는 방법

    오른쪽 상단 사람모양 클릭 -> API Credentials 클릭

    네모박스안의 Tokens 값을 TOKEN 변수에 넣으면 된다 (문자열 형식으로! ex "xxxxxxx" )

     

    실행결과

    라즈베리파이 Thonny에서 코드를 실행중인 모습
    코드를 실행하면, machine 장치가 추가된 것을 볼 수 있다!
    machine 장치 내에서 습도값, 온도값을 볼 수 있다 (습도 60% / 온도 20도)
    온도, 습도 데이터를 위젯화 한 모습

    감사합니다!

     

    참고자료

    fishpoint.tistory.com/5212

    Ubidots REST API 레퍼런스 문서 : ubidots.com/docs/sw/#operation/List%20Datasource%20Variables

    Connect the Raspberry Pi with Ubidots 문서 : help.ubidots.com/en/articles/513309-connect-the-raspberry-pi-with-ubidots

     

    '프로그래밍 > 프로젝트' 카테고리의 다른 글

    [JAVA] 히어로 야구 시뮬레이터  (0) 2021.05.21
    [Python] 계산기 만들기  (0) 2020.12.27

    댓글

Designed by Tistory.