Skip to content

Node‐RED GPIO & dht11 in Raspberrypi5

김선영 edited this page Oct 15, 2024 · 15 revisions

🍓 Raspberry Pi 5 DHT11 및 Node-RED 실습 보고서

📚 목차

  1. DHT11 센서 실습 1.1. 실습 환경 1.2. 라이브러리 설치 및 문제 해결 1.3. 하드웨어 연결 1.4. 코드 1.5. 결과화면
  2. Node-RED 실습 2.1. Node-RED 설치 2.2. GPIO LED 실습 2.3. DHT11 센서 데이터 읽기
  3. 참고 자료

1. DHT11 센서 실습

1.1. 실습 환경

먼저 운영체제를 최신 상태로 업그레이드합니다:

sudo apt-get update
sudo apt-get upgrade

1.2. 라이브러리 설치 및 문제 해결

1) Adafruit DHT 라이브러리 설치

git clone https://github.com/adafruit/Adafruit_Python_DHT.git
cd Adafruit_Python_DHT
sudo python setup.py install

2) libgpiod 설치

sudo apt-get install -y libgpiod-dev

📌 주의: libgpiod는 파이썬 패키지가 아닌 시스템 패키지입니다. apt를 사용하여 설치해야 합니다.

🚨 오류 해결: DHT 센서 감지 실패

다음과 같은 오류가 발생할 경우:

raise RuntimeError("DHT sensor not found, check wiring")
RuntimeError: DHT sensor not found, check wiring
Lost access to message queue

libgpiod를 수동으로 설치하여 해결할 수 있습니다:

  1. 필수 패키지 설치

    sudo apt-get update
    sudo apt-get install -y git build-essential autoconf automake libtool pkg-config
  2. libgpiod 소스 코드 다운로드 및 설치

    git clone https://git.kernel.org/pub/scm/libs/libgpiod/libgpiod.git
    cd libgpiod
    ./autogen.sh
    ./configure
    make
    sudo make install
  3. 설치 확인

    gpiodetect

GPIO 접근 권한 설정

sudo usermod -aG gpio pi
sudo reboot

Adafruit CircuitPython DHT 라이브러리 설치

가상환경을 사용하여 라이브러리를 설치합니다:

python3 -m venv ~/dht11_env
source ~/dht11_env/bin/activate
pip3 install adafruit-circuitpython-dht

💡 : 가상환경을 사용하면 시스템 전체에 영향을 주지 않고 프로젝트별로 독립적인 환경을 구성할 수 있습니다.

1.3. 하드웨어 연결

DHT11 연결 다이어그램

  • 온습도 센서 VCC : 1번 핀 (3.3v)
  • 온습도 센서 GND : 6번 핀 (Ground)
  • 온습도 센서 DAT : GPIO 4 (7번핀)

1.4. 코드

import time
import board
import adafruit_dht

dhtDevice = adafruit_dht.DHT11(board.D4)
temperature_c = dhtDevice.temperature        
temperature_f = temperature_c * (9 / 5) + 32    
humidity = dhtDevice.humidity
print(f"Temp: {temperature_f:.1f}°F / {temperature_c:.1f}°C    Humidity: {humidity}%")
time.sleep(2.0)

1.5. 결과화면

DHT11 센서 결과

2. Node-RED 실습

2.1. Node-RED 설치

⚠️ 주의: sudo apt-get을 통한 설치는 GPIO 노드 인식 문제로 추천하지 않습니다.

최신 버전의 Node.js와 Node-RED 설치:

bash <(curl -sL https://raw.githubusercontent.com/node-red/linux-installers/master/deb/update-nodejs-and-nodered)

설치 완료 후 Node-RED 실행:

Node-RED 설치 완료

💡 : ~/.node-red 디렉토리에서 Node-RED 관련 파일을 확인할 수 있습니다.

Node-RED 모듈 폴더 Node-RED 모듈 상세

2.2. GPIO LED 실습

  1. http://127.0.0.1:1880/에 접속하여 Node-RED 플로우 페이지 열기
  2. 다음과 같이 플로우 구성:

GPIO LED 플로우

설정 방법:

  • inject 노드의 payload를 boolean 타입으로 설정
  • 0, 1 입력에 따라 LED on/off 제어

GPIO LED 설정

🎥 GPIO LED 제어 영상

🚨 오류 해결: nrgpio python command not running

다음 오류 발생 시:

14 Oct 02:46:06 - [error] [rpi-gpio out:4f9480a235312ea2] nrgpio python command not running

최신 버전의 Node.js와 Node-RED를 설치하여 해결할 수 있습니다:

bash <(curl -sL https://raw.githubusercontent.com/node-red/linux-installers/master/deb/update-nodejs-and-nodered)

2.3. DHT11 센서 데이터 읽기

⚠️ 주의: Raspberry Pi 5에서는 /dev/gpiomem 호환성 문제로 직접적인 센서 정보 읽기가 어려울 수 있습니다.

대안으로 exec 노드를 사용하여 Python 가상환경에서 센서 데이터를 읽고 JSON으로 파싱합니다:

Node-RED DHT11 데이터

debug 노드 출력:

Node-RED Debug 출력

Python 코드:

import time
import board
import adafruit_dht
import json

def read_sensor():
    try:
        dhtDevice = adafruit_dht.DHT11(board.D4)
        temperature_c = dhtDevice.temperature
        temperature_f = temperature_c * (9 / 5) + 32
        humidity = dhtDevice.humidity
        
        return json.dumps({
            "temperature_c": round(temperature_c, 1),
            "temperature_f": round(temperature_f, 1),
            "humidity": humidity
        })
    except RuntimeError as error:
        return json.dumps({"error": str(error)})
    except Exception as error:
        return json.dumps({"error": f"Unexpected error: {str(error)}"})
    finally:
        dhtDevice.exit()

print(read_sensor())

💡 : 브레드보드 없이 연결 시 내부 풀업 저항을 사용합니다.

3. 참고 자료


🎉 이것으로 Raspberry Pi 5에서 DHT11 센서를 사용한 온습도 측정과 Node-RED를 이용한 GPIO 제어 실습 보고서를 마칩니다. 추가 질문이나 피드백이 있으면 언제든 문의해 주세요!

Clone this wiki locally