<aside> 📌
[과제명][학교][이름] 바꿔주세요, 과제태그를 선생님 설명 듣고 넣어
주세요.
</aside>
1 : 내부 led켜기 2: 내부 led 끄기 3: 내부 led 깜빡이기 4: 서보모터 1 움직이기 5: 서보모터 2 움직이기 6: 서보모터 1,2 동시에 움직이기 7 :서보모터 1,2 모두 동작 그만 8: 서보모터 1,2 초기 각도로 돌아가기 (90도)
from machine import Pin, PWM
import sys
from time import sleep
# 내장 LED 설정 (Raspberry Pi Pico는 "LED"가 내장 LED 핀 이름임)
led = Pin("LED", Pin.OUT)
# 서보모터 핀 설정
servo1 = PWM(Pin(15))
servo2 = PWM(Pin(17))
servo1.freq(50)
servo2.freq(50)
# 현재 각도 상태 변수
angle1 = 90
angle2 = 90
# 각도 → 듀티사이클 변환 함수
def angle_to_duty(angle):
return int(1638 + (angle / 180.0) * (8192 - 1638))
# 각도 적용 함수
def update_servos():
servo1.duty_u16(angle_to_duty(angle1))
servo2.duty_u16(angle_to_duty(angle2))
# 초기 위치
update_servos()
print("시리얼 통신으로 명령을 입력하세요.")
print("1: LED ON, 2: LED OFF, 3: LED Blink")
print("4: Servo1 제어, 5: Servo2 제어, 6: Servo1+2 동시 제어")
print("7: Servo 정지, 8: Servo 초기화 (90도)")
try:
while True:
command = sys.stdin.readline().strip()
if command == "1":
led.value(1)
print("LED ON")
elif command == "2":
led.value(0)
print("LED OFF")
elif command == "3":
print("LED Blink 시작")
for _ in range(5):
led.toggle()
sleep(0.3)
led.value(0)
print("LED Blink 완료")
elif command == "4":
angle1 = min(180, angle1 + 10)
update_servos()
print("Servo1 각도:", angle1)
elif command == "5":
angle2 = max(0, angle2 - 10)
update_servos()
print("Servo2 각도:", angle2)
elif command == "6":
angle1 = min(180, angle1 + 10)
angle2 = max(0, angle2 - 10)
update_servos()
print("Servo1:", angle1, "/ Servo2:", angle2)
elif command == "7":
servo1.deinit()
servo2.deinit()
print("서보모터 정지")
elif command == "8":
angle1 = 90
angle2 = 90
servo1.init()
servo2.init()
servo1.freq(50)
servo2.freq(50)
update_servos()
print("서보모터 초기 위치 (90도)")
else:
print("알 수 없는 명령입니다. 1~8 사이 숫자를 입력하세요.")
except Exception as e:
print("오류 발생:", e)
finally:
servo1.deinit()
servo2.deinit()
print("프로그램 종료 및 서보모터 해제")
실습 1. 내부 led 코드 제어 코드
from machine import Pin
import sys
# 내장 LED는 일반적으로 GP25에 연결되어 있음
led = Pin("LED", Pin.OUT)
print("UART LED Controller Ready")
print("Type 'on' to turn on the LED, 'off' to turn it off")
while True:
try:
# 한 줄 입력 받기 (터미널에서)
command = sys.stdin.readline().strip().lower()
if command == "on":
led.value(1)
print("LED ON")
elif command == "off":
led.value(0)
print("LED OFF")
else:
print("Unknown command. Type 'on' or 'off'.")
except Exception as e:
print("Error:", e)
from machine import Pin
import sys
# 내장 LED는 일반적으로 GP25에 연결되어 있음
led = Pin("LED", Pin.OUT)
print("UART LED Controller Ready")
print("Type 'on' to turn on the LED, 'off' to turn it off")
while True:
try:
# 한 줄 입력 받기 (터미널에서)
command = sys.stdin.readline().strip().lower()
if command == "on":
led.value(1)
print("LED ON")
elif command == "off":
led.value(0)
print("LED OFF")
else:
print("Unknown command. Type 'on' or 'off'.")
except Exception as e:
print("Error:", e)
import cv2
import mediapipe as mp
import time
# MediaPipe 손 인식 초기화
mp_hands = mp.solutions.hands
mp_drawing = mp.solutions.drawing_utils
hands = mp_hands.Hands(max_num_hands=1, min_detection_confidence=0.7)
# 버튼 클래스
class Button:
def __init__(self, pos, text):
self.pos = pos # (x, y)
self.size = (100, 100)
self.text = text
self.clicked = False
self.last_click_time = 0
def draw(self, img):
color = (0, 255, 0) if self.clicked else (200, 200, 200)
x, y = self.pos
w, h = self.size
cv2.rectangle(img, (x, y), (x + w, y + h), color, -1)
cv2.rectangle(img, (x, y), (x + w, y + h), (0, 0, 0), 2)
cv2.putText(img, self.text, (x + 30, y + 60),
cv2.FONT_HERSHEY_SIMPLEX, 2, (0, 0, 0), 3)
def check_click(self, finger_pos):
x, y = self.pos
w, h = self.size
fx, fy = finger_pos
if x < fx < x + w and y < fy < y + h:
current_time = time.time()
if current_time - self.last_click_time > 1: # 1초 간격
self.clicked = True
self.last_click_time = current_time
print(f"버튼 '{self.text}' 클릭됨")
else:
self.clicked = False
# 버튼 생성 (3x3 그리드)
buttons = []
for i in range(3):
for j in range(3):
num = str(3 * i + j + 1)
buttons.append(Button((100 + j * 120, 100 + i * 120), num))
# 웹캠 열기
cap = cv2.VideoCapture(0)
print("검지 손가락으로 숫자 버튼을 눌러보세요 (ESC로 종료)")
while True:
ret, frame = cap.read()
if not ret:
break
frame = cv2.flip(frame, 1) # 좌우 반전
img_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
results = hands.process(img_rgb)
# 손 검출되면 랜드마크 추출
finger_pos = None
if results.multi_hand_landmarks:
for hand_landmarks in results.multi_hand_landmarks:
# 검지 손가락 끝: landmark 8
h, w, _ = frame.shape
x = int(hand_landmarks.landmark[8].x * w)
y = int(hand_landmarks.landmark[8].y * h)
finger_pos = (x, y)
mp_drawing.draw_landmarks(frame, hand_landmarks, mp_hands.HAND_CONNECTIONS)
# 검지 위치 시각화
cv2.circle(frame, finger_pos, 10, (255, 0, 255), -1)
# 버튼 그리기 및 클릭 감지
for btn in buttons:
btn.draw(frame)
if finger_pos:
btn.check_click(finger_pos)
cv2.imshow("Hand Button Click", frame)
if cv2.waitKey(1) & 0xFF == 27:
break
cap.release()
cv2.destroyAllWindows()