我正在尝试使用USB串行端口通过笔记本电脑与arduino通信。我正在使用带有串行包的Python 3.6。我的Python代码的简化版本是:
import serial
import time
with serial.Serial(port="COM3", baudrate=9600) as ser:
time.sleep(2)
while True:
x, y, angle = detectAndDisplay(frame, face_cascade, eyes_cascade)
if x is not None:
ser.write((str(x * 100 // 177) + "/n").encode())
ser.write((str(y * 100 // 133) + "/n").encode())
if cv.waitKey(10) == 27:
break
其中函数detectAndDisplay()返回三个int值。值x,y缩放到0到180之间。我想将值x,y发送到arduino,后者具有以下简化代码:
#include <PID_v1.h>
#include <Servo.h>
Servo Servo_1;
Servo Servo_2;
double Setpoint_1 = 90;
double Input_1;
double Output_1;
double Setpoint_2 = 90;
double Input_2;
double Output_2;
double Kp_1 = 0.022;
double Ki_1 = 0.012;
double Kd_1 = 0;
double Kp_2 = 0.032;
double Ki_2 = 0.022;
double Kd_2 = 0;
PID PID1(&Input_1, &Output_1, &Setpoint_1, Kp_1, Ki_1, Kd_1, DIRECT);
PID PID2(&Input_2, &Output_2, &Setpoint_2, Kp_2, Ki_2, Kd_2, DIRECT);
int serialCount = 0;
int serialInArray[2];
int posX = 90;
int posY = 90;
int errorX;
int errorY;
void setup() {
Serial.begin(9600);
Servo_1.attach(32);
Servo_2.attach(34);
PID1.SetMode(AUTOMATIC);
PID1.SetSampleTime(1);
PID1.SetOutputLimits(-35, 35);
PID2.SetMode(AUTOMATIC);
PID2.SetSampleTime(1);
PID2.SetOutputLimits(-35, 35);
Servo_1.write(90);
Servo_2.write(90);
}
void loop() {
while(Serial.available() == 0);
serialInArray[serialCount] = (Serial.read());
serialCount++;
if (serialCount > 1){
Input_1 = serialInArray[1];
Input_2 = serialInArray[0];
PID1.Compute();
PID2.Compute();
posX = posX + Output_2;
posY = posY + Output_1;
Servo_1.write(posX);
Servo_2.write(posY);
serialCount = 0;
}
}
在这里我将posX和posY的值用作伺服电机的输入。但是,我注意到的是在arduino上接收到输入,因为它会在启动python脚本后立即开始执行操作。但是,一旦接收到输入信号,伺服电动机便开始变为零。此行为与我发送的值无关。我想念什么或做错什么了?