Weather Station 실습 자료
Python으로 피지컬컴퓨팅 수업 전략, 교구 제작
Python으로 피지컬컴퓨팅 수업 전략, 교구 제작
import machine
pin2 = machine.Pin(2, machine.Pin.OUT)
pin2.value(1)
# 라이브러리 가져오기
from machine import Pin #핀 설정
from time import sleep #일시 정지
# 핀 설정
led = Pin(2, Pin.OUT) #내장LED를 출력용으로
# 방법1
while True: #무한 반복
led.value(1) # 1: ON, HIGH,3.3V
sleep(1) #1초 재우기
led.value(0) # 0:OFF, LOW, 0V
sleep(1) #1초 재우기
#방법2
# while True:
# led.value(not led.value()) #led 토글(반전)
# sleep(1) #1초 재우기
# 라이브러리 가져오기
from machine import Pin #핀 설정
from time import sleep #일시 정지
# 핀 설정
grn = Pin(25, Pin.OUT) #초록LED
yel = Pin(26, Pin.OUT) #노랑LED
red = Pin(27, Pin.OUT) #빨강LED
#한꺼번에 점멸 1초 간격으로
while True:
red.value(1) #빨강 켜기
yel.value(1) #노랑 켜기
grn.value(1) #초록 켜기
sleep(1) #1초 대기
red.value(0) #빨강 끄기
yel.value(0) #노랑 끄기
grn.value(0) #초록 끄기
sleep(1) #1초 대기
# 라이브러리 가져오기
from machine import Pin #핀 설정
from time import sleep #일시 정지
# 핀 설정
grn = Pin(25, Pin.OUT) #초록LED
yel = Pin(26, Pin.OUT) #노랑LED
red = Pin(27, Pin.OUT) #빨강LED
#하나씩 켜고 끄기 0.5초 간격으로
while True:
red.value(1) #빨강 켜기
sleep(0.5) #0.5초 대기
red.value(0) #빨강 끄기
yel.value(1) #노랑 켜기
sleep(0.5) #0.5초 대기
yel.value(0) #노랑 끄기
grn.value(1) #초록 켜기
sleep(0.5) #0.5초 대기
grn.value(0) #초록 끄기
# 라이브러리 가져오기
from machine import Pin #핀 설정
from time import sleep #일시 정지
# 핀 설정
grn = Pin(25, Pin.OUT) #초록LED
yel = Pin(26, Pin.OUT) #노랑LED
red = Pin(27, Pin.OUT) #빨강LED
#하나씩 켜고 끄기 0.5초 간격으로
while True:
red.value(1) #빨강 켜기
sleep(0.5) #0.5초 대기
yel.value(1) #노랑 켜기
sleep(0.5) #0.5초 대기
grn.value(1) #초록 켜기
sleep(0.5) #0.5초 대기
red.value(0) #빨강 끄기
yel.value(0) #노랑 끄기
grn.value(0) #초록 끄기
sleep(0.5) #0.5초 대기
# 라이브러리 가져오기
from machine import Pin #핀 설정
from time import sleep #일시 정지
# 핀 설정
grn = Pin(25, Pin.OUT) #초록LED
yel = Pin(26, Pin.OUT) #노랑LED
red = Pin(27, Pin.OUT) #빨강LED
buz = Pin(33, Pin.OUT) #부저
#3색 신호등 동작 구현
while True:
red.value(1) #빨강 켜기
sleep(0.5) #0.5초 대기
red.value(0) #빨강 끄기
yel.value(1) #노랑 켜기
sleep(0.5) #0.5초 대기
yel.value(0) #노랑 끄기
grn.value(1) #초록 켜기
buz.value(1) #부저 켜기
sleep(0.5) #0.5초 대기
grn.value(0) #초록 끄기
buz.value(0) #부저 끄기
# 라이브러리 가져오기
from machine import Pin #핀 설정
from time import sleep #일시 정지
# 핀 설정
grn = Pin(25, Pin.OUT) #초록LED
yel = Pin(26, Pin.OUT) #노랑LED
red = Pin(27, Pin.OUT) #빨강LED
btn1 = Pin(39, Pin.IN) #버튼1(누르면0, 놓으면1)
# 버튼1의 값을 쉘과 플로터로 보기
while True:
print('btn1:', btn1.value())
sleep(0.1) # 출력 속도
# 라이브러리 가져오기
from machine import Pin #핀 설정
from time import sleep #일시 정지
# 핀 설정
grn = Pin(25, Pin.OUT) #초록LED
yel = Pin(26, Pin.OUT) #노랑LED
red = Pin(27, Pin.OUT) #빨강LED
btn1 = Pin(39, Pin.IN) #버튼1(누르면0, 놓으면1)
# 버튼으로 제어하기(방법1)
while True:
if(btn1.value() == 0): #버튼1 누르면,
red.value(1) #빨강 켜기
else: #버튼1 놓으면,
red.value(0) #빨강 끄기
# 버튼으로 제어하기(방법2)
# while True:
# red.value(not btn1.value()) # 빨강LED 토글(반전)
# 라이브러리 가져오기
from machine import Pin #핀 설정
from time import sleep #일시 정지
# 핀 설정
grn = Pin(25, Pin.OUT) #초록LED
yel = Pin(26, Pin.OUT) #노랑LED
red = Pin(27, Pin.OUT) #빨강LED
buz = Pin(33, Pin.OUT) #부저
btn1 = Pin(39, Pin.IN) #버튼1(누르면0, 놓으면1)
btn2 = Pin(34, Pin.IN) #버튼2(누르면0, 놓으면1)
btn3 = Pin(35, Pin.IN) #버튼3(누르면0, 놓으면1)
# 버튼으로 신호등 제어
while True:
red.value(not btn1.value()) #버튼1 상태를 빨강LED에 반영
yel.value(not btn2.value()) #버튼2 상태를 노랑LED에 반영
grn.value(not btn3.value()) #버튼3 상태를 초록LED에 반영
#눌린 버튼의 수를 저장
pressed_btn_cnt = btn1.value() + btn2.value() + btn3.value()
#눌린 버튼의 수가 2개 미만이면 부저 끄기
buz.value(pressed_btn_cnt < 2)
# 라이브러리 가져오기
from machine import Pin #핀 설정
# 핀 설정
btn1 = Pin(39, Pin.IN) #버튼1(누르면0, 놓으면1)
cnt = 0 #누른 횟수
# 버튼을 누른 횟수 세기
while True:
if btn1.value() == 0: #버튼1을 누르면,
cnt += 1 #cnt 1증가
print('누른 횟수:', cnt) #버튼 누른 횟수 출력
# 라이브러리 가져오기
from machine import Pin #핀 설정
# 핀 설정
btn1 = Pin(39, Pin.IN) #버튼1(누르면0, 놓으면1)
cnt = 0 #누른 횟수
pre_state = 1 #이전 상태(누르지 않은)
cur_state = 1 #현재 상태(누르지 않은)
#[방법1] 버튼을 누른 횟수 세기 - 반복 측정 오류 개선
while True:
cur_state = btn1.value() #버튼1의 현재 상태 저장
if pre_state == 1 and cur_state == 0: #버튼을 누르면,
cnt += 1 #cnt 1증가
print('누른 횟수:', cnt) #버튼 누른 횟수 출력
pre_state = cur_state #이전 상태 업데이트
elif pre_state == 0 and cur_state == 1: #버튼을 놓으면,
pre_state = cur_state #이전 상태 업데이트
#[방법2] 버튼을 누른 횟수 세기 - 반복 측정 오류 개선
# while True:
# cur_state = btn1.value() #버튼1의 현재 상태 저장
# if pre_state != cur_state: #버튼 상태가 변했다면,
# pre_state = cur_state #이전 상태 업데이트
# if cur_state == 0: #버튼을 눌렀다면,
# cnt += 1 #cnt 1증가
# print('누른 횟수:', cnt) #버튼 누른 횟수 출력
# 라이브러리 가져오기
from machine import Pin #핀 설정
from time import sleep #일시 정지
# 핀 설정
btn1 = Pin(39, Pin.IN) #버튼1(누르면0, 놓으면1)
cnt = 0 #누른 횟수
pre_state = 1 #이전 상태(누르지 않은)
cur_state = 1 #현재 상태(누르지 않은)
#[방법1] 버튼을 누른 횟수 세기 - 반복 측정 오류 개선
while True:
cur_state = btn1.value() #버튼1의 현재 상태 저장
if pre_state == 1 and cur_state == 0: #버튼을 누르면,
cnt += 1 #cnt 1증가
print('누른 횟수:', cnt) #버튼 누른 횟수 출력
pre_state = cur_state #이전 상태 업데이트
sleep(0.04) #0.04초(40ms) 대기, debouncing 용
elif pre_state == 0 and cur_state == 1: #버튼을 놓으면,
pre_state = cur_state #이전 상태 업데이트
#[방법2] 버튼을 누른 횟수 세기 - 반복 측정 오류 개선
# while True:
# cur_state = btn1.value() #버튼1의 현재 상태 저장
# if pre_state != cur_state: #버튼 상태가 변했다면,
# pre_state = cur_state #이전 상태 업데이트
# if cur_state == 0: #버튼을 눌렀다면,
# cnt += 1 #cnt 1증가
# print('누른 횟수:', cnt) #버튼 누른 횟수 출력
# [1] htu21d 라이브러리 내부 살펴보기
import htu21d # htu21 온습도센서 모듈
print(dir(htu21d)) # htu21d 라이브러리 내부 출력
# # 라이브러리 가져오기
# from htu21d import HTU21D #htu21d 온습도센서 클래스
# from time import sleep #일시 정지
#
#
# # 핀설정: i2C통신(scl,sda)
# htu = HTU21D(scl=22, sda=21) #scl:클럭, sda:데이터
#
# # [2] 1초 간격으로 온도, 습도 읽어서 출력하기
# while True:
# temp = htu.temperature #온도 읽기
# humi = htu.humidity #습도 읽기
# print(f'Temp: {temp:4.2f}\u2103', end=' , ') #온도 출력
# print(f'Humi: {humi:4.2f}%') #습도 출력
# sleep(1) #1초 간격
# wifi 연결==================================================
import wifi
ssid = 'woonam'
key = 'woonamhs'
wifi.connect(ssid, key)
#라이브러리 가져오기
from time import localtime,time
print(time()) #기기의 현재 시각 출력
t = localtime(time()) #기기의 현재 시각을 튜플로 저장
print(t, type(t))
print(f'{t[0]}.{t[1]}.{t[2]}.', end=' ') #년월일 출력
print(f'{t[3]:02d}:{t[4]:02d}:{t[5]:02d}') #시분초 출력
#라이브러리 가져오기
from time import localtime,time,sleep #시간 제어 모듈
UTC_OFFSET = 9 * 60 * 60 # 한국 시각(UTC+9) 반영
while True:
t = localtime(time() + UTC_OFFSET) #KST(한국표준시): UTC + 9
print(time())
print(f'{t[0]}.{t[1]}.{t[2]}.', end=' ') #년월일 출력
print(f'{t[3]:02d}:{t[4]:02d}:{t[5]:02d}') #시분초 출력
sleep(1) #1초마다 출력
#라이브러리 가져오기
from time import localtime,time,sleep #시간 제어 모듈
import ntptime #ntp 모듈
import wifi #wifi 모듈
# wifi 연결
ssid = 'woonam' #아이디
key = 'woonamhs' #비밀번호
wifi.connect(ssid, key) #wifi 연결하기
# NTP 시각 가져오기(인터넷 연결 상태에서 실행할 것)
ntptime.settime() # NTP서버의 시간 반영하기
# wifi 연결 해제
wifi.disconnect()
# 한국표준시 변환
UTC_OFFSET = 9 * 60 * 60 # 한국표준시는 UTC + 9hr, 초단위로 환산
# 1초마다 한국 시각 출력하기
while True:
t = localtime(time() + UTC_OFFSET) #KST(한국표준시)
print(f'{t[0]}.{t[1]}.{t[2]}.', end=' ') #년월일 출력
print(f'{t[3]:02d}:{t[4]:02d}:{t[5]:02d}') #시분초 출력
sleep(1) #1초마다 출력
#라이브러리 가져오기
from time import localtime,time,sleep #시간 제어 모듈
import ntptime #ntp 모듈
import wifi #wifi 모듈
def setTime():
# wifi 연결
ssid = 'woonam' #아이디
key = 'woonamhs' #비밀번호
wifi.connect(ssid, key) #wifi 연결하기
# NTP 시각 가져오기
try:
print("Local time before synchronization:%s" %str(localtime()))
#인터넷 연결 상태에서 실행할 것
ntptime.settime() # NTP서버에서 시간 가져와서 반영하기
print("Local time after synchronization:%s" %str(localtime()))
except:
print("Error syncing time")
# wifi 연결 해제
wifi.disconnect()
# 시각을 맞추었으면 setTime() 반복하지 말 것
setTime() #NTP 시각으로 맞추기
# 1초마다 현재 시각 출력하기
UTC_OFFSET = 9 * 60 * 60 # 한국표준시(UTC+9) 반영
while True:
t = localtime(time() + UTC_OFFSET) #KST(한국표준시): UTC + 9
print(f'{t[0]}.{t[1]}.{t[2]}.', end=' ') #년월일 출력
print(f'{t[3]:02d}:{t[4]:02d}:{t[5]:02d}') #시분초 출력
sleep(1) #1초마다 출력
#[1] display() 모듈 내부 살펴보기
from tft_lcd import display,color565
print(dir(display))
#[2] 화면 크기 확인하기 - 네 모서리에 픽셀 표시
display.draw_pixel(0, 0, color565(255,255,255)) #하양
display.draw_pixel(319, 0, color565(255,0,0)) #빨강
display.draw_pixel(0, 239, color565(0,255,0)) #초록
display.draw_pixel(319, 239, color565(0,0,255)) #파랑
# 폰트 라이브러리 추가
from tft_lcd import display,color565,espresso,d2coding
# 직선과 도형
#draw_line(x1, y1, x2, y2, color)
display.draw_line(0, 0, 319, 239, color565(255,255,255))
#draw_rectangle(x, y, w, h, color)
display.draw_rectangle(10, 10, 100, 100, color565(0,255,0))
#draw_circle(x0, y0, r, color)
display.draw_circle(160, 120, 50, color565(255,0,0))
#draw_polygon(sides, x0, y0, r, color, rotate=0)
display.draw_polygon(6, 160, 120, 50, color565(255,255,0), rotate=0)
# 문자 출력
display.draw_text(0,20,'ABCDEFGHIJKLMOPQRSTUVWXYZ', espresso, color565(255,255,255))
display.draw_text(0,190,'0123456789. & %', d2coding, color565(255,0,255))
# 폰트 라이브러리 추가
from tft_lcd import display,color565,espresso,d2coding
# LCD 화면 기본 표시
# 프로젝트명
display.draw_text(20, 10, 'Weather Station ver1.0', espresso, color565(255, 0, 255))
# 온도
display.draw_text(20, 68, 'Temp ', espresso, color565(0, 255, 255))
# 습도
display.draw_text(20, 120, 'Humi ', espresso, color565(0, 255, 255))
# 저작자이름
display.draw_text(10, 210, 'programmed by khs@wahs', espresso, color565(0, 255, 0))
#=====================================
# Weather Station 구현하기
# 2022.11.22. 포근함 by김학생 GNU
#=====================================
# H/W: esp32 MCU(Micro Control Unit)
# S/W: MicroPython
# IDE: Thonny
#라이브러리 가져오기
from machine import Pin
from time import sleep
# 온습도센서 모델: HTU21D===========================
from htu21d import HTU21D #htu21d 온습도센서 모듈
# print(dir(htu21d))
# 핀설정: i2C통신(scl,sda)
htu = HTU21D(scl=22, sda=21)
def getTempHumi():
global temp, humi
temp = htu.temperature #온도 읽기
humi = htu.humidity #습도 읽기
# wifi 연결=========================================
import wifi
ssid = 'woonam'
key = 'woonamhs'
wifi.connect(ssid, key)
# 인터넷 시각 맞추기 =============================
import ntptime
from time import localtime,time
# NTP 시각 가져오기
ntptime.settime() # NTP서버에서 시간 가져와서 반영
UTC_OFFSET = 9 * 60 * 60 # 한국표준시(UTC+9) 변환
# NTP 시각 가져오지 않기(이미 맞추었으면)
# UTC_OFFSET = 0 #이미 맞추었으면
# wifi 연결 해제
wifi.disconnect()
#현재 시각 가져오기
def getTime():
global t
t = localtime(time() + UTC_OFFSET)
#LCD 화면(TFT, 2.8", 320x240)==========================
from tft_lcd import display,color565,espresso,d2coding
#기본 화면 구성============
# 프로젝트명
display.draw_text(20, 10, 'Weather Station ver1.0', espresso, color565(255, 0, 255))
# 온도
display.draw_text(20, 68, 'Temp ', espresso, color565(0, 255, 255))
# 습도
display.draw_text(20, 120, 'Humi ', espresso, color565(0, 255, 255))
# 저작자
display.draw_text(10, 210, 'programmed by khs@wahs', espresso, color565(0, 255, 0))
while True:
# 온습도 값 읽기
getTempHumi()
# 현재 시각 읽기
getTime()
# LCD 화면 표시 ==================================================================
# 온도
display.draw_text(90, 58, f'{temp:4.2f} & ', d2coding, color565(255, 255, 0))
# 습도
display.draw_text(90, 110, f'{humi:4.2f} % ', d2coding, color565(255, 255, 0))
# 현재 시각
display.draw_text(10, 176, f'{t[0]}.{t[1]}.{t[2]}. ', espresso, color565(128, 128, 255))
display.draw_text(120, 160, f'{t[3]:02d}:{t[4]:02d}:{t[5]:02d}', d2coding, color565(255, 255, 255))
# 화면 표시 주기
sleep(1)
#=====================================
# Weather Station 구현하기
# 2022.11.22. 포근함 by김학생 GNU
#=====================================
# H/W: esp32 MCU(Micro Control Unit)
# S/W: MicroPython
# IDE: Thonny
#라이브러리 가져오기
from machine import Pin
from time import localtime,time,sleep
from htu21d import HTU21D #htu21d 온습도센서 모듈
from tft_lcd import display,color565,espresso,d2coding #LCD 화면(TFT, 2.8", 320x240)
# 핀설정: i2C통신(scl,sda)
htu = HTU21D(scl=22, sda=21)
#기본 화면 구성=====================================================================
# 프로젝트명
display.draw_text(20, 10, 'Weather Station ver1.0', espresso, color565(255, 0, 255))
# 온도
display.draw_text(20, 68, 'Temp ', espresso, color565(0, 255, 255))
# 습도
display.draw_text(20, 120, 'Humi ', espresso, color565(0, 255, 255))
# 저작자
display.draw_text(10, 210, 'programmed by khs@wahs', espresso, color565(0, 255, 0))
print('starting weather station...')
# 무한 반복
while True:
try:
temp = htu.temperature #온도 읽기
humi = htu.humidity #습도 읽기
t = localtime(time()) #현재 시각 읽기
except Exception as e:
print('Reading error', e) #오류 발생 시
else:
# LCD 화면 업데이트 ==================================================================
# 온도
display.draw_text(90, 58, f'{temp:4.2f} & ', d2coding, color565(255, 255, 0))
# 습도
display.draw_text(90, 110, f'{humi:4.2f} % ', d2coding, color565(255, 255, 0))
# 현재 시각
display.draw_text(10, 176, f'{t[0]}.{t[1]}.{t[2]}. ', espresso, color565(128, 128, 255))
display.draw_text(120, 160, f'{t[3]:02d}:{t[4]:02d}:{t[5]:02d}', d2coding, color565(255, 255, 255))
finally:
sleep(1) #업데이트 주기