카테고리 없음

마이크로 파이썬 라이브러리 연습 모

trustworthyhand 2025. 7. 25. 12:44

🧰 MicroPython 라이브러리 연습 주제 목록

주제설명사용 라이브러리
① GPIO 출력 제어 LED 켜기/끄기 machine.Pin
② 버튼 입력 읽기 버튼 누름 감지 machine.Pin
③ PWM 제어 서보, BLDC 속도조절 machine.PWM
④ ADC 센서 값 읽기 가변저항, 조도센서 machine.ADC
⑤ Wi-Fi 연결 무선 통신 network
⑥ 소켓 통신 ESP32 ↔ PC socket
⑦ 타이머 사용 반복 실행 machine.Timer
⑧ UART 통신 센서/모듈과 시리얼 연결 machine.UART
 

machine.Pin은 ESP32의 GPIO 핀을 제어하는 가장 기본적이고 중요한 라이브러리

from machine import Pin

출력용 핀 Pin(2, Pin.OUT) GPIO2번을 출력으로 사용
입력용 핀 Pin(14, Pin.IN) GPIO14번을 입력으로 사용
입력 (풀업) Pin(14, Pin.IN, Pin.PULL_UP) 버튼 등에서 GND에 연결 시
입력 (풀다운) Pin(14, Pin.IN, Pin.PULL_DOWN) 버튼이 VCC로 연결될 때 사용

 

출력 핀 연습 (LED 제어)

from machine import Pin
import time

led = Pin(2, Pin.OUT)  # GPIO2 = 내장 LED

# 켜고 끄기
led.value(1)  # HIGH → 켜기
time.sleep(1)
led.value(0)  # LOW  → 끄기

 

입력 핀 연습 (버튼 감지)

button = Pin(14, Pin.IN, Pin.PULL_UP)

while True:
    if button.value() == 0:  # 눌림 (GND에 연결되면 0)
        print("버튼이 눌렸습니다")
    time.sleep(0.1)

 

인터럽트로 버튼 눌림 감지 (irq)

def on_press(pin):
    print("👉 버튼 눌림!")

button = Pin(14, Pin.IN, Pin.PULL_UP)
button.irq(trigger=Pin.IRQ_FALLING, handler=on_press)

Pin.IRQ_FALLING: 1 → 0 (버튼 눌림)

handler: 호출할 함수

 

이 방식은 메인 루프가 없어도 버튼 누르면 자동으로 함수 실행됨

 

'''

button.irq(trigger=Pin.IRQ_FALLING, handler=on_press)
irq() 인터럽트 등록 함수
trigger=Pin.IRQ_FALLING 눌렀을 때 (HIGH → LOW) 작동
handler=on_press 눌리면 실행할 함수 지정

'''


ESP32 server (LED 제어코드 - 소켓연결)

# led_socket_server.py
import socket
from machine import Pin
import network
import time

# --- Wi-Fi 연결 ---
ssid = "wifi"
password = "wifiPW"

sta = network.WLAN(network.STA_IF)
sta.active(True)
sta.connect(ssid, password)

print("📡 Wi-Fi 연결 중...")
while not sta.isconnected():
    time.sleep(1)

print("✅ Wi-Fi 연결됨:", sta.ifconfig()[0])

# --- 핀 설정 ---
led = Pin(2, Pin.OUT)

# --- 소켓 서버 시작 ---
s = socket.socket()
s.bind(('0.0.0.0', 1234))  # ESP32의 1234 포트 열기
s.listen(1)
print("🌐 명령 대기 중...")

conn, addr = s.accept()
print("💻 연결됨:", addr)

while True:
    data = conn.recv(1024)
    cmd = data.decode().strip()

    if cmd == "on":
        led.value(1)
        print("💡 LED ON")
    elif cmd == "off":
        led.value(0)
        print("🔌 LED OFF")

 

 


ESP32 (SERVER) PC (클라이언트)

 


PC 클라이언트- (LED 제어코드 - 소켓연결)

# pc_client.py
import socket

ESP32_IP = "ESP32의 IP주소 입력"
PORT = 1234

s = socket.socket()
s.connect((ESP32_IP, PORT))

while True:
    cmd = input("명령 입력 (on/off): ")
    s.sendall(cmd.encode())