Weather Station on Esp32
Python 피지컬컴퓨팅 수업 전략, 교구 제작
Python 피지컬컴퓨팅 수업 전략, 교구 제작
1) Thonny 보기 > 파일
2) "이 컴퓨터" 창에서 설치 파일이 있는 폴더 선택
라이브러리(lib)는 폴더째로 올리는 게 편하다.
3) lib 폴더 우클릭 > /에 업로드
폰트(fonts)는 필요한 것만 골라서 올린다.
4) "MicroPython 장치" 창에서 fonts 폴더 생성 > fonts폴더 더블 클릭
5) "이 컴퓨터" 창에서 필요한 폰트 선택(우클릭)하여 /fonts에 업로드
font와 lib를 설치한 모습
#=====================================
# Weather Station 구현하기
# 2024.05.27. 포근함 by김학생 GNU
#=====================================
# H/W: esp32 MCU(Micro Control Unit)
# S/W: MicroPython
# IDE: Thonny
#라이브러리 가져오기
from machine import Pin
from time import sleep
from machine import Pin #핀 설정
# 종료 버튼 설정
btn1 = Pin(39, Pin.IN) #버튼1(누르면0, 놓으면1)
# 온습도센서 모델: 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 = 'ASUS_2G'
key = '!qazxsw2'
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))
# 종료 조건
doStop = True
# 웨더스테이션 메인루프
while doStop:
# 온습도 값 읽기
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)
# 종료 확인
doStop = btn1.value()
# 화면 지우기
display.clear()
display.fill_circle(270,120,30,color565(200,200,200))#아래
display.fill_circle(270,80,20,color565(200,200,200))#위
display.draw_circle(270,80,20,color565(255,0,0))#위테두리
#====================================
# GPIO(입출력 장치) 제어
# 2022.11.3. 좋음 by김학생 GNU
#====================================
# 회로 연결
# D2:내장LED, D33:부저, D25:G, D26:Y, D27:R, 39(VN):BTN1, D34:BTN2, D35:BTN3
###다음시간 온습도센서(HTU21D): D21:SDA, D22:SCL
# 쉘에서 help()
# 코드 복사하기
# import machine
# led = machine.Pin(2, machine.Pin.OUT) #2번 핀을 출력용으로 설정하고 led로 이름부여
# led.value(1) #led 값을 1(HIGH)로
# STOP으로 종료
#모듈이름 생략하기
# from machine import Pin
#
# led = Pin(2, Pin.OUT) #핀설정
# led.value(1) #led 켜기
# 1초마다 내장LED 점멸(on/off) ====================================
# 모듈 가져오기
from machine import Pin
from time import sleep
# 핀 설정
led = Pin(2, Pin.OUT) #2번 핀을 출력용으로 설정
# 메인코드
while True:
led.value(1) #led 켜기
sleep(1) #1초 잠자기
led.value(0) #led 끄기
sleep(1) #1초 잠자기
# =====================================================
# 다른 표현
# while True:
# led.value(not led.value()) #led 켜기
# print(led.value()) #led값 출력
# sleep(1) #1초 잠자기
# 신호등 제어하기 =====================
# 핀 설정
grn = Pin(25, Pin.OUT) #초록LED
yel = Pin(26, Pin.OUT) #노랑LED
red = Pin(27, Pin.OUT) #빨강LED
buz = Pin(33, Pin.OUT) #부저
# 한꺼번에 점멸
# while True:
# red.value(1)
# yel.value(1)
# grn.value(1)
# sleep(1)
# red.value(0)
# yel.value(0)
# grn.value(0)
# sleep(1)
# 순서대로 켜고 한꺼번에 끄기
# while True:
# red.value(1)
# sleep(1)
# yel.value(1)
# sleep(1)
# grn.value(1)
# sleep(1)
# red.value(0)
# yel.value(0)
# grn.value(0)
# sleep(1)
# [과제] 신호등 구현
# 빨강1.5초 >> 노랑 0.5초>> 초록1초
# 초록불에서는 부저도 울릴 것
# while True:
# red.value(1)
# sleep(1.5)
# red.value(0)
# yel.value(1)
# sleep(0.5)
# yel.value(0)
# grn.value(1)
# buz.value(1)
# sleep(1)
# grn.value(0)
# buz.value(0)
# 버튼 제어하기 =====================
# 핀 설정
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:
# print('btn1:', btn1.value())
# # print('btn1:', btn1.value(),'btn2:', btn2.value(),'btn3:', btn3.value())
# sleep(0.1)
# 버튼으로 제어하기
# while True:
# if(btn1.value() == 0): #버튼1 누르면
# red.value(1) #빨강 켜기
# else:
# red.value(0) #빨강 끄기
# while True:
# red.value(not btn1.value()) # 다른 방법
# [과제2] 버튼으로 LED 제어하기
# 버튼1- 빨강, 버튼2-노랑, 버튼3-초록
# 버튼을 두개 이상 누르면 부저 울리기
while True:
red.value(not btn1.value())
yel.value(not btn2.value())
grn.value(not btn3.value())
buz.value((btn1.value()+btn2.value()+btn3.value()) < 2)
#=================================
# Weather Station 구현하기
# 2022.11.22. 포근함 by김학생 GNU
#=================================
# H/W: esp32 MCU(Micro Control Unit)
# S/W: MicroPython
# IDE(개발툴): Thonny
# 1. 전원을 켠다 >> 보드의 빨강 LED ON
# 2. Thonny - 보드 연결>>쉘 창에 안내 메시지
#입력장치: 버튼,온습도센서
#출력장치: LED,부저,LCD화면
from machine import Pin
from time import sleep
#핀설정- 내장LED는 2번 핀
# led = Pin(2, Pin.OUT)
#제어하기
# while True: #무한 반복
# led.value(1) # 1: ON, HIGH,3.3V
# sleep(1) #1초 재우기
# led.value(0) # 0:OFF, LOW, 0V
# sleep(1) #1초 재우기
# 온습도 센서로 세상읽기 ==========
# 온습도센서 모델: HTU21D
# 모듈 가져오기
from htu21d import HTU21D #htu21d 온습도센서 모듈
# print(dir(htu21d))
# 핀설정: i2C통신(scl,sda)
htu = HTU21D(scl=22, sda=21)
# 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초 간격
def getTempHumi():
global temp, humi
temp = htu.temperature #온도 읽기
humi = htu.humidity #습도 읽기
# while True:
# getTempHumi()
# print(f'Temp: {temp:4.2f}\u2103', end=' , ') #온도 출력
# print(f'Humi: {humi:4.2f}%') #습도 출력
# sleep(1)
# wifi 연결==================================================
import wifi
ssid = 'woonam'
key = 'woonamhs'
wifi.connect(ssid, key)
# 인터넷 시각 맞추기 =======================================
# NTP(Network Time Protocol) 인터넷으로 시간 맞추기
import ntptime
from time import localtime,time
# print(dir(ntptime))
# NTP 시각 가져오기 =========================
# ntptime.settime() # NTP서버에서 시간 가져와서 반영하기
# UTC_OFFSET = 9 * 60 * 60 # 한국 시각(UTC+9) 반영
# NTP 시각 가져오지 않기(이미 맞추었으면)
UTC_OFFSET = 0 #이미 맞추었으면
# wifi 연결 해제
wifi.disconnect()
# while True:
# t = localtime(time() + UTC_OFFSET)
# print(f'{t[0]}.{t[1]}.{t[2]}.', end=' ')
# print(f'{t[3]:02d}:{t[4]:02d}:{t[5]:02d}')
# sleep(1)
def getTime():
global t
t = localtime(time() + UTC_OFFSET)
# while True:
# getTime()
# print(f'{t[0]}.{t[1]}.{t[2]}.', end=' ')
# print(f'{t[3]:02d}:{t[4]:02d}:{t[5]:02d}')
# sleep(1)
#LCD 화면(TFT, 2.8", 320x240)================================
from tft_lcd import display,color565,espresso,d2coding
# print(dir(display))
# 위치 확인
# LCD 가로(w) 320 x 세로(h) 240픽셀
# 0.0 --- 319.0
# 0.239 --- 319.239
# espresso_dolce 폰트: 24x45 , 가로 13자
# lib/ili9341.py 열어보면 있음
# 픽셀로 화면 크기 확인하기
# 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))
# 직선과 도형
# display.draw_line(0, 0, 319, 239, color565(255,255,255)) #draw_line(x1, y1, x2, y2, color)
# display.draw_rectangle(10, 10, 100, 100, color565(0,255,0)) #draw_rectangle(x, y, w, h, color)
# display.draw_circle(160, 120, 50, color565(255,0,0)) #draw_circle(x0, y0, r, color)
# display.draw_polygon(6, 160, 120, 50, color565(255,255,0), rotate=0) #draw_polygon(sides, x0, y0, r, color, rotate=0)
# 문자 출력
# display.draw_text(0,0,'ABCDEFGHIJKLMOPQRSTUVWXYZ', espresso, color565(255,255,255))
#x-coordinate: 325 above maximum of 319.
# display.draw_text(0,30,'0123456789. & %', d2coding, color565(255,0,255))
# 프로젝트명
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))
# display.draw_text(20, 210, 'Woonam High School', espresso, color565(0, 255, 0))
# y-coordinate: 240 above maximum of 239.
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)
# while True:
# try:
# # 온습도 값 읽기
# humi = htu.humidity
# temp = htu.temperature
#
# # 현재 시각 읽기
# t = time.localtime(time.time() + UTC_OFFSET)
#
# except Exception as e:
# print('Error to Reading', e)
# pass
#
# 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)
동시
점멸
하나씩
점멸
하나씩
쌓기
신호등
구현
2023.11.10. 현재 Thonny 버전3.x에서는 더욱 간단하게 작업 가능
BOOT를 누른 상태에서 USB 연결
도구>옵션>인터프리터
※ 교구의 Esp32용 MicroPython 사용법 및 펌웨어를 찾아가는 과정입니다.
웹에서 'micropython' 검색
마이크로파이썬 공식 홈페이지 클릭 ▶ https://micropython.org/
<사용법>
[DOCS]탭 선택 ▶ https://docs.micropython.org/
Quick reference for the ESP32 클릭 ▶ https://docs.micropython.org/en/latest/esp32/quickref.html
<펌웨어 다운로드>
Installing MicroPython 클릭 ▶ https://docs.micropython.org/en/latest/esp32/quickref.html#installing-micropython
Getting started with MicroPython on the ESP32 클릭 ▶ https://docs.micropython.org/en/latest/esp32/tutorial/intro.html#esp32-intro
1.3. Getting the firmware 아래 MicroPython downloads page 클릭 ▶ https://micropython.org/download/#esp32
Port: esp32 클릭 ▶ https://micropython.org/download/?port=esp32
아래 그림 ESP32 Espressif 클릭 ▶https://micropython.org/download/?mcu=esp32
Thonny 실행
교구 연결
UART 드라이버가 CH340인 보드는 별도의 드라이버가 필요할 수 있습니다.
thonny 에서 교구 포트가 보이지 않으면 아래 사이트를 참고하여 CH34x 드라이버를 설치하세요.
http://bplab.kr/coding_download/?q=YToxOntzOjEyOiJrZXl3b3JkX3R5cGUiO3M6MzoiYWxsIjt9&bmode=view&idx=6659702&t=board
도구>옵션>인터프리터 > Install or update MicroPython 클릭
4. 펌웨어 파일 위치 선택한 후 [설치] 클릭
이전 버전의 Thonny 에서는 파일로 설치
Thonny 4.1.4 이후 버전에서는 온라인에서 다운로드하여 설치
5. Micropython 설치가 완료되었을 때 쉘 창
★ 다음과 같은 에러 발생 시 보드의 [boot]버튼을 누른 상태에서 [설치] 클릭
Writing at 0x0001000... 메시지가 뜨기 시작하면 버튼을 놓아도 됩니다.
C:\Users\ksyun\AppData\Local\Programs\Thonny\python.exe -u -m esptool --port COM10 erase_flash
esptool.py v4.4
Serial port COM10
Connecting......................................
A fatal error occurred: Failed to connect to Espressif device: Wrong boot mode detected (0x13)! The chip needs to be in download mode.
For troubleshooting steps visit: https://docs.espressif.com/projects/esptool/en/latest/troubleshooting.html
Erase command returned with error code 2
회로도 v1
회로도 v2
PCB 앞면 v1
PCB 뒷면 v1
PCB 앞면 v2
운암고20221007
창의융합교육원20230208