import cv2
from cvzone.HandTrackingModule import HandDetector
import serial
import time

# Connect to Arduino
arduino = serial.Serial('COM3', 9600)  # Replace with your correct port (e.g. 'COM4' or '/dev/ttyUSB0')
time.sleep(2)  # Wait for connection

# Set up camera and hand detector
cap = cv2.VideoCapture(0)
detector = HandDetector(detectionCon=0.8, maxHands=2)

while True:
    success, img = cap.read()
    hands, img = detector.findHands(img)

    fingers = [0]*10  # Default: all off

    for i in range(len(hands)):
        hand = hands[i]
        up = detector.fingersUp(hand)
        for j in range(5):
            fingers[i*5 + j] = up[j]  # First 5 for hand 1, next 5 for hand 2

    # Send to Arduino
    data = ''.join(map(str, fingers))  # e.g., '1100001100'
    arduino.write(data.encode())
    print("Sent to Arduino:", data)

    # Show video
    cv2.imshow("Hand Detection", img)
    if cv2.waitKey(1) == ord('q'):
        break

cap.release()
cv2.destroyAllWindows()
arduino.close()
