从Python向Arduino发送一个单一的信号来获取一系列值

2024-09-29 21:33:23 发布

您现在位置:Python中文网/ 问答频道 /正文

Python代码:

ser = serial.Serial("COM1", 19200, timeout=5)
time.sleep(2)
while True:
    # ... img processing
    faces = face_cascade.detectMultiScale(gray, 1.3, 5)

    detected = False


    for (x, y, w, h) in faces:
        # ... faces processing
        detect_face=x


        print 'face distance: ', detect_face
        if 80 < detect_face < 100:
            if detected:
               pass
            else:
               print '1'
               detected = True
        else:
            if detected:
               print '2'
               detected = False
            else:
               pass

detect_face值:

^{pr2}$

Arduino代码:

void loop() {
  if (Serial.available() > 0) { 
    incomingBit = Serial.read();
    switch (incomingBit) {
      case '1':
          Servo1.write(0); 
          delay(1000); 

          Servo1.write(90); 
          delay(1000); 

          Servo1.write(180); 
          delay(1000); 
          //exit(0);
       break;

       case '2' :
         Servo1.write(0);
       break;

现在我要做的是每次发送一个'single'信号'1',每次80 < detect_face < 100。例如,当detect_face104,95,80,80,98,100,...ser.write('1')发送信号4次,结果连接到Arduino的伺服在一个循环中移动4次。我想要的是detect_face104,95,80,80,98,100只向arduino发送一次信号,而不是4次。如何在Python端做到这一点?甚至在阿杜伊诺那边?在


Tags: 代码trueif信号serialelseserwrite
1条回答
网友
1楼 · 发布于 2024-09-29 21:33:23

下面是一个很容易使用的片段:

for detect_face in [79,80,81, 90, 99,100,101]:
    print(detect_face)
    if 80 < detect_face < 100:
        print(' 1')
    else:
        print(' 2')

它印出来了

^{pr2}$

所以这种情况看起来像你想要的那样有效。在

如果我理解正确,您的问题是如何防止这种情况连续运行几次,这样[90,90,90,110,110,110,90,90,90]不会导致

90
 1
90
 1
90
 1
110
 2
110
 2
110
 2
90
 1
90
 1
90
 1

但在这一点上:

90
 1
90
90
110
 2
110
110
90
 1
90
90

所以代码还必须检测状态的变化,而不仅仅是阈值。保持和比较状态使其成为边缘检测器(状态变化):

detected = False

for detect_face in [90,90,90,110,110,110,90,90,90]:
    print(detect_face)
    if 80 < detect_face < 100:
        if detected:
            pass
        else:
            print(' 1')
            detected = True
    else:
        if detected:
            print(' 2')
            detected = False
        else:
            pass

(见上面的输出)

注意条件的对称性。在电子学中,这是一个flip-flop。在

这相当于保留最后一个结果并将其与当前结果进行比较;如果它们不同,则为一个边(事件)。在

阈值可以通过滞后来扩展。在

相关问题 更多 >

    热门问题