라즈파이로 최신 온습도 파일 출력
16571 단어 RaspberryPi파이썬DHT11
소개
라즈파이에서 환경 정보를 얻기 위해 DHT11 온습도 센서를 사용합니다.
취득한 최신의 온습도의 정보를 「2021/07/22 23:00:01 20 82」라고 하는 형태로 파일에 보존하고 있으므로 그 방법을 정리해 둡니다.
센서를 연결하는 방법
DHT11 센서에는 핀이 4개 있는 것과 3개의 것이 있을 것 같습니다.
내가 가지고 있는 것은 3개의 것으로, 왼쪽에서 VCC,GRD,DATA가 되어 있었습니다.
VCC는 4번 포트(5V), GRD는 6번 포트(GRD), DATA는 8번 포트(GPIO14)에 접속했습니다.

온습도 정보 처리
온습도를 파일로 출력하는 처리는 다음과 같습니다. OSOYOO의 샘플 코드를 베이스로 하고 있으므로 세세한 곳은 모릅니다만, 처리를 실행하면 「/var/local/NowTemp.txt」에 최신의 일시와 온습도를 출력합니다.
import RPi.GPIO as GPIO
import time
import os
import datetime
#GPIOの番号
DHTPIN = 14
GPIO.setmode(GPIO.BCM)
MAX_UNCHANGE_COUNT = 100
STATE_INIT_PULL_DOWN = 1
STATE_INIT_PULL_UP = 2
STATE_DATA_FIRST_PULL_DOWN = 3
STATE_DATA_PULL_UP = 4
STATE_DATA_PULL_DOWN = 5
def read_dht11_dat():
GPIO.setup(DHTPIN, GPIO.OUT)
GPIO.output(DHTPIN, GPIO.HIGH)
time.sleep(0.05)
GPIO.output(DHTPIN, GPIO.LOW)
time.sleep(0.02)
GPIO.setup(DHTPIN, GPIO.IN, GPIO.PUD_UP)
unchanged_count = 0
last = -1
data = []
#センサーからデータを取得
while True:
current = GPIO.input(DHTPIN)
data.append(current)
if last != current:
unchanged_count = 0
last = current
else:
unchanged_count += 1
if unchanged_count > MAX_UNCHANGE_COUNT:
break
state = STATE_INIT_PULL_DOWN
lengths = []
current_length = 0
#温度と湿度が混ざった40個のリストを作成
for current in data:
current_length += 1
if state == STATE_INIT_PULL_DOWN:
if current == GPIO.LOW:
state = STATE_INIT_PULL_UP
else:
continue
if state == STATE_INIT_PULL_UP:
if current == GPIO.HIGH:
state = STATE_DATA_FIRST_PULL_DOWN
else:
continue
if state == STATE_DATA_FIRST_PULL_DOWN:
if current == GPIO.LOW:
state = STATE_DATA_PULL_UP
else:
continue
if state == STATE_DATA_PULL_UP:
if current == GPIO.HIGH:
current_length = 0
state = STATE_DATA_PULL_DOWN
else:
continue
if state == STATE_DATA_PULL_DOWN:
if current == GPIO.LOW:
lengths.append(current_length)
state = STATE_DATA_PULL_UP
else:
continue
if len(lengths) != 40:
return False
halfway = (max(lengths) + min(lengths)) / 2
bits = []
the_bytes = []
byte = 0
#中間より多いか少ないかで温度と湿度を判別している
for length in lengths:
#中間より小さければ温度
bit = 0
if length > halfway:
#中間より大きければ湿度
bit = 1
bits.append(bit)
#[湿度,XX,温度,XX,チェックサム]のリストの作成
for i in range(0, len(bits)):
byte = byte << 1
if (bits[i]):
byte = byte | 1
else:
byte = byte | 0
if ((i + 1) % 8 == 0):
the_bytes.append(byte)
byte = 0
#チェックサム比較
checksum = (the_bytes[0] + the_bytes[1] + the_bytes[2] + the_bytes[3]) & 0xFF
if the_bytes[4] != checksum:
return False
return the_bytes[0], the_bytes[2]
def main():
#温湿度情報を取得
while True:
result = read_dht11_dat()
#取得できるまで繰り返し
if result != False:
humidity, temperature = result
break
#日付情報を取得
date = datetime.datetime.now()
#温湿度情報をファイル出力
output = date.strftime('%Y/%m/%d %H:%M:%S ' + str(temperature) + " " + str(humidity))
com = "echo \"" + output + "\" > /var/local/NowTemp.txt"
os.system(com)
def destroy():
GPIO.cleanup()
if __name__ == '__main__':
try:
main()
except KeyboardInterrupt:
destroy()
10분에 한 번 온도 정보 업데이트
항상 최신 온도로 유지하고 싶기 때문에, 10분 주기로 명령 실행하도록/etc/crontab에 기재해, 「systemctl resatar cron」로 cron을 재기동합니다.
그러면 10분 주기로 최신 정보로 갱신해 줍니다.
# Example of job definition:
# .---------------- minute (0 - 59)
# | .------------- hour (0 - 23)
# | | .---------- day of month (1 - 31)
# | | | .------- month (1 - 12) OR jan,feb,mar,apr ...
# | | | | .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat
# | | | | |
# * * * * * user-name command to be executed
*/10 * * * * root python3 /home/pi/leo_test/temp_check2.py
Reference
이 문제에 관하여(라즈파이로 최신 온습도 파일 출력), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다
https://qiita.com/akahira/items/0fefc759a5df58ae3f4f
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념
(Collection and Share based on the CC Protocol.)
DHT11 센서에는 핀이 4개 있는 것과 3개의 것이 있을 것 같습니다.
내가 가지고 있는 것은 3개의 것으로, 왼쪽에서 VCC,GRD,DATA가 되어 있었습니다.
VCC는 4번 포트(5V), GRD는 6번 포트(GRD), DATA는 8번 포트(GPIO14)에 접속했습니다.

온습도 정보 처리
온습도를 파일로 출력하는 처리는 다음과 같습니다. OSOYOO의 샘플 코드를 베이스로 하고 있으므로 세세한 곳은 모릅니다만, 처리를 실행하면 「/var/local/NowTemp.txt」에 최신의 일시와 온습도를 출력합니다.
import RPi.GPIO as GPIO
import time
import os
import datetime
#GPIOの番号
DHTPIN = 14
GPIO.setmode(GPIO.BCM)
MAX_UNCHANGE_COUNT = 100
STATE_INIT_PULL_DOWN = 1
STATE_INIT_PULL_UP = 2
STATE_DATA_FIRST_PULL_DOWN = 3
STATE_DATA_PULL_UP = 4
STATE_DATA_PULL_DOWN = 5
def read_dht11_dat():
GPIO.setup(DHTPIN, GPIO.OUT)
GPIO.output(DHTPIN, GPIO.HIGH)
time.sleep(0.05)
GPIO.output(DHTPIN, GPIO.LOW)
time.sleep(0.02)
GPIO.setup(DHTPIN, GPIO.IN, GPIO.PUD_UP)
unchanged_count = 0
last = -1
data = []
#センサーからデータを取得
while True:
current = GPIO.input(DHTPIN)
data.append(current)
if last != current:
unchanged_count = 0
last = current
else:
unchanged_count += 1
if unchanged_count > MAX_UNCHANGE_COUNT:
break
state = STATE_INIT_PULL_DOWN
lengths = []
current_length = 0
#温度と湿度が混ざった40個のリストを作成
for current in data:
current_length += 1
if state == STATE_INIT_PULL_DOWN:
if current == GPIO.LOW:
state = STATE_INIT_PULL_UP
else:
continue
if state == STATE_INIT_PULL_UP:
if current == GPIO.HIGH:
state = STATE_DATA_FIRST_PULL_DOWN
else:
continue
if state == STATE_DATA_FIRST_PULL_DOWN:
if current == GPIO.LOW:
state = STATE_DATA_PULL_UP
else:
continue
if state == STATE_DATA_PULL_UP:
if current == GPIO.HIGH:
current_length = 0
state = STATE_DATA_PULL_DOWN
else:
continue
if state == STATE_DATA_PULL_DOWN:
if current == GPIO.LOW:
lengths.append(current_length)
state = STATE_DATA_PULL_UP
else:
continue
if len(lengths) != 40:
return False
halfway = (max(lengths) + min(lengths)) / 2
bits = []
the_bytes = []
byte = 0
#中間より多いか少ないかで温度と湿度を判別している
for length in lengths:
#中間より小さければ温度
bit = 0
if length > halfway:
#中間より大きければ湿度
bit = 1
bits.append(bit)
#[湿度,XX,温度,XX,チェックサム]のリストの作成
for i in range(0, len(bits)):
byte = byte << 1
if (bits[i]):
byte = byte | 1
else:
byte = byte | 0
if ((i + 1) % 8 == 0):
the_bytes.append(byte)
byte = 0
#チェックサム比較
checksum = (the_bytes[0] + the_bytes[1] + the_bytes[2] + the_bytes[3]) & 0xFF
if the_bytes[4] != checksum:
return False
return the_bytes[0], the_bytes[2]
def main():
#温湿度情報を取得
while True:
result = read_dht11_dat()
#取得できるまで繰り返し
if result != False:
humidity, temperature = result
break
#日付情報を取得
date = datetime.datetime.now()
#温湿度情報をファイル出力
output = date.strftime('%Y/%m/%d %H:%M:%S ' + str(temperature) + " " + str(humidity))
com = "echo \"" + output + "\" > /var/local/NowTemp.txt"
os.system(com)
def destroy():
GPIO.cleanup()
if __name__ == '__main__':
try:
main()
except KeyboardInterrupt:
destroy()
10분에 한 번 온도 정보 업데이트
항상 최신 온도로 유지하고 싶기 때문에, 10분 주기로 명령 실행하도록/etc/crontab에 기재해, 「systemctl resatar cron」로 cron을 재기동합니다.
그러면 10분 주기로 최신 정보로 갱신해 줍니다.
# Example of job definition:
# .---------------- minute (0 - 59)
# | .------------- hour (0 - 23)
# | | .---------- day of month (1 - 31)
# | | | .------- month (1 - 12) OR jan,feb,mar,apr ...
# | | | | .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat
# | | | | |
# * * * * * user-name command to be executed
*/10 * * * * root python3 /home/pi/leo_test/temp_check2.py
Reference
이 문제에 관하여(라즈파이로 최신 온습도 파일 출력), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다
https://qiita.com/akahira/items/0fefc759a5df58ae3f4f
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념
(Collection and Share based on the CC Protocol.)
import RPi.GPIO as GPIO
import time
import os
import datetime
#GPIOの番号
DHTPIN = 14
GPIO.setmode(GPIO.BCM)
MAX_UNCHANGE_COUNT = 100
STATE_INIT_PULL_DOWN = 1
STATE_INIT_PULL_UP = 2
STATE_DATA_FIRST_PULL_DOWN = 3
STATE_DATA_PULL_UP = 4
STATE_DATA_PULL_DOWN = 5
def read_dht11_dat():
GPIO.setup(DHTPIN, GPIO.OUT)
GPIO.output(DHTPIN, GPIO.HIGH)
time.sleep(0.05)
GPIO.output(DHTPIN, GPIO.LOW)
time.sleep(0.02)
GPIO.setup(DHTPIN, GPIO.IN, GPIO.PUD_UP)
unchanged_count = 0
last = -1
data = []
#センサーからデータを取得
while True:
current = GPIO.input(DHTPIN)
data.append(current)
if last != current:
unchanged_count = 0
last = current
else:
unchanged_count += 1
if unchanged_count > MAX_UNCHANGE_COUNT:
break
state = STATE_INIT_PULL_DOWN
lengths = []
current_length = 0
#温度と湿度が混ざった40個のリストを作成
for current in data:
current_length += 1
if state == STATE_INIT_PULL_DOWN:
if current == GPIO.LOW:
state = STATE_INIT_PULL_UP
else:
continue
if state == STATE_INIT_PULL_UP:
if current == GPIO.HIGH:
state = STATE_DATA_FIRST_PULL_DOWN
else:
continue
if state == STATE_DATA_FIRST_PULL_DOWN:
if current == GPIO.LOW:
state = STATE_DATA_PULL_UP
else:
continue
if state == STATE_DATA_PULL_UP:
if current == GPIO.HIGH:
current_length = 0
state = STATE_DATA_PULL_DOWN
else:
continue
if state == STATE_DATA_PULL_DOWN:
if current == GPIO.LOW:
lengths.append(current_length)
state = STATE_DATA_PULL_UP
else:
continue
if len(lengths) != 40:
return False
halfway = (max(lengths) + min(lengths)) / 2
bits = []
the_bytes = []
byte = 0
#中間より多いか少ないかで温度と湿度を判別している
for length in lengths:
#中間より小さければ温度
bit = 0
if length > halfway:
#中間より大きければ湿度
bit = 1
bits.append(bit)
#[湿度,XX,温度,XX,チェックサム]のリストの作成
for i in range(0, len(bits)):
byte = byte << 1
if (bits[i]):
byte = byte | 1
else:
byte = byte | 0
if ((i + 1) % 8 == 0):
the_bytes.append(byte)
byte = 0
#チェックサム比較
checksum = (the_bytes[0] + the_bytes[1] + the_bytes[2] + the_bytes[3]) & 0xFF
if the_bytes[4] != checksum:
return False
return the_bytes[0], the_bytes[2]
def main():
#温湿度情報を取得
while True:
result = read_dht11_dat()
#取得できるまで繰り返し
if result != False:
humidity, temperature = result
break
#日付情報を取得
date = datetime.datetime.now()
#温湿度情報をファイル出力
output = date.strftime('%Y/%m/%d %H:%M:%S ' + str(temperature) + " " + str(humidity))
com = "echo \"" + output + "\" > /var/local/NowTemp.txt"
os.system(com)
def destroy():
GPIO.cleanup()
if __name__ == '__main__':
try:
main()
except KeyboardInterrupt:
destroy()
항상 최신 온도로 유지하고 싶기 때문에, 10분 주기로 명령 실행하도록/etc/crontab에 기재해, 「systemctl resatar cron」로 cron을 재기동합니다.
그러면 10분 주기로 최신 정보로 갱신해 줍니다.
# Example of job definition:
# .---------------- minute (0 - 59)
# | .------------- hour (0 - 23)
# | | .---------- day of month (1 - 31)
# | | | .------- month (1 - 12) OR jan,feb,mar,apr ...
# | | | | .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat
# | | | | |
# * * * * * user-name command to be executed
*/10 * * * * root python3 /home/pi/leo_test/temp_check2.py
Reference
이 문제에 관하여(라즈파이로 최신 온습도 파일 출력), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://qiita.com/akahira/items/0fefc759a5df58ae3f4f텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념
(Collection and Share based on the CC Protocol.)