메인
home
소프트웨어
home

[피코-미디어파이프-시리얼통신][덕원여고][이은]

실시간 확인

1. 시리얼 통신으로 피코 제어

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 from time import sleep import _thread # 내장 LED 설정 led = Pin("LED", Pin.OUT) # 서보모터 설정 servo1 = PWM(Pin(15)) servo2 = PWM(Pin(17)) servo1.freq(50) servo2.freq(50) # 듀티 설정 min_duty = 1638 max_duty = 8100 mid_duty = (min_duty + max_duty) // 2 step = 200 # 현재 각도 저장용 duty1 = mid_duty duty2 = mid_duty servo1.duty_u16(duty1) servo2.duty_u16(duty2) # 깜빡이기 제어 변수 blinking = False # 서보모터 동작 쓰레드 중단 변수 moving = False # LED 깜빡이기 함수 (쓰레드용) def blink_led(): global blinking while blinking: led.toggle() sleep(0.5) led.value(0) # 서보모터 동시에 움직이기 (쓰레드용) def move_servos(): global moving, duty1, duty2 while moving: duty1 = min_duty if duty1 > mid_duty else max_duty duty2 = max_duty if duty2 < mid_duty else min_duty servo1.duty_u16(duty1) servo2.duty_u16(duty2) sleep(0.5) # 메뉴 출력 def print_menu(): print("\n===== 시리얼 통신 메뉴 =====") print("1 : 내부 LED 켜기") print("2 : 내부 LED 끄기") print("3 : 내부 LED 깜빡이기") print("4 : 서보모터 1 움직이기 (90~180도)") print("5 : 서보모터 2 움직이기 (90~0도)") print("6 : 서보모터 1,2 동시에 움직이기") print("7 : 서보모터 1,2 모두 동작 그만") print("8 : 서보모터 1,2 초기 각도로 돌아가기 (90도)") print("===========================\n") print_menu() while True: try: command = input("번호 입력 (1~8): ").strip() if command == "1": blinking = False led.value(1) print("LED 켜짐") elif command == "2": blinking = False led.value(0) print("LED 꺼짐") elif command == "3": if not blinking: blinking = True _thread.start_new_thread(blink_led, ()) print("LED 깜빡이기 시작") else: blinking = False print("LED 깜빡이기 중지") elif command == "4": duty1 = min(duty1 + step, max_duty) servo1.duty_u16(duty1) print("서보모터1 이동: duty =", duty1) elif command == "5": duty2 = max(duty2 - step, min_duty) servo2.duty_u16(duty2) print("서보모터2 이동: duty =", duty2) elif command == "6": if not moving: moving = True _thread.start_new_thread(move_servos, ()) print("서보모터1,2 동시에 움직이기 시작") elif command == "7": moving = False print("서보모터1,2 동작 중지") elif command == "8": duty1 = mid_duty duty2 = mid_duty servo1.duty_u16(duty1) servo2.duty_u16(duty2) print("서보모터1,2 초기 각도(90도)로 이동") else: print("알 수 없는 명령입니다. 1~8 중 입력하세요.") except Exception as e: print("에러 발생:", e)
Python
복사
실습 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)
Python
복사

2. 미디어파이프로 피코 제어

import cv2 import mediapipe as mp # 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, min_tracking_confidence=0.7) # 웹캠 시작 cap = cv2.VideoCapture(0) clicked_button = None while cap.isOpened(): ret, frame = cap.read() if not ret: print("프레임 수신 실패") break frame = cv2.flip(frame, 1) # 좌우 반전 h, w, _ = frame.shape rgb_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) # 손 추적 results = hands.process(rgb_frame) # 검지 손가락 위치 초기화 index_finger_tip = None # 버튼 크기 및 위치 계산 (3x3 그리드) rows, cols = 3, 3 button_w = int(w / (cols + 1)) button_h = int(h / (rows + 1)) buttons = [] for i in range(9): col = i % cols row = i // cols x = int((col + 1) * w / (cols + 1) - button_w / 2) y = int((row + 1) * h / (rows + 1) - button_h / 2) buttons.append({'number': str(i + 1), 'x': x, 'y': y, 'w': button_w, 'h': button_h}) # 손 좌표 추출 및 클릭 판정 if results.multi_hand_landmarks: for hand_landmarks in results.multi_hand_landmarks: mp_drawing.draw_landmarks(frame, hand_landmarks, mp_hands.HAND_CONNECTIONS) index_tip = hand_landmarks.landmark[8] finger_x = int(index_tip.x * w) finger_y = int(index_tip.y * h) for button in buttons: if (button['x'] < finger_x < button['x'] + button['w'] and button['y'] < finger_y < button['y'] + button['h']): clicked_button = button['number'] # 버튼 그리기 for button in buttons: color = (200, 200, 200) if button['number'] == clicked_button: color = (0, 255, 0) cv2.rectangle(frame, (button['x'], button['y']), (button['x'] + button['w'], button['y'] + button['h']), color, -1) cv2.putText(frame, button['number'], (button['x'] + int(button['w'] / 3), button['y'] + int(button['h'] * 2 / 3)), cv2.FONT_HERSHEY_SIMPLEX, 1.5, (0, 0, 0), 3) # 결과 출력 cv2.imshow("Balanced Buttons with Hand Tracking", frame) if cv2.waitKey(1) & 0xFF == 27: # ESC 키로 종료 break # 종료 cap.release() cv2.destroyAllWindows() hands.close()
Python
복사
[과제명][학교][이름] 바꿔주세요, 과제태그를 선생님 설명 듣고 넣어주세요.