首页 > 解决方案 > 如何从 python 向 Arduino 发送值?

问题描述

我正在尝试发送从 python 脚本获取的角度值,并将这些值发送到 arduino 以旋转伺服电机。我在 youtube 上使用了有关 mediapipe 手部跟踪的教程。我得到的食指角度值从 0 度到 180 度。但是我如何将这些值发送到伺服电机并旋转它?下面是我的代码:


import cv2
import numpy as np
import HandTrackingModule as htm
import math

import Utilities
from Utilities import connectToRobot

portNo = "COM5"
wCam, hCam = 640, 480

cap = cv2.VideoCapture(1)
cap.set(3, wCam)
cap.set(4, hCam)
Utilities.connectToRobot(portNo)

detector = htm.handDetector(detectionCon=0.75)

while True:
    success, img = cap.read()

    img = detector.findHands(img)
    lmList = detector.findPosition(img, draw=False)
    if len(lmList) != 0:
        #print(lmList[8], lmList[0])

        x1, y1 = lmList[8][1], lmList[8][2]
        x2, y2 = lmList[0][1], lmList[0][2]

        cv2.circle(img, (x1, y1), 10, (255, 0, 255), cv2.FILLED)
        cv2.circle(img, (x2, y2), 10, (255, 0, 255), cv2.FILLED)
        cv2.line(img, (x1, y1), (x2, y2), (255, 0, 255), 3)

        length = math.hypot(x2 - x1, y2 - y1)
        #print(length)

        # Index finger range 330 - 140
        # servo motor angle range 180 - 0

        angle = np.interp(length, [140, 300], [0, 180])
        print(int(angle))

    cv2.imshow("Image", img)

    key = cv2.waitKey(1)
    if key & 0xff == ord('q'):
        break


对不起,我的英语不好。谢谢你的建议。

这些是角度。您会看到最大角度为 180 度,最小角度为 0 度。我没有取 0 度,因为这只是print(int(angle))为了让您了解我想要做什么的输出。在此处输入图像描述这是我的手顺便说一句。这张照片显示了代码的作用。我画了紫色线来计算角度。

65
78
77
80
92
67
79
74
91
98
126
144
144
175
180
180
180

标签: pythonarduino

解决方案


推荐阅读