我用Python和Arduino编写了使用串行通信的代码,最初我并没有将它组织成函数或类,所以我现在尝试这样做是为了使它更易于阅读和使用。但是,我在从无限循环切换到可以多次调用的函数时遇到了问题。无限循环完全工作,使电机运行并打印出正确的语句,函数执行打印语句,但不会使电机运行。你知道吗
带有无限循环的通用Python代码:
while True:
ser.write('a'.encode()) #used as an initial byte
...other code... mostly assigning values to the variables below
motorBytes = bytearray([decToByte(left), decToByte(right), decToByte(leftMid), decToByte(rightMid), distPerc]) #puts the motor values into an array as hex
print(motorBytes)
ser.write(motorBytes)
带函数的通用Python代码:
def motor_loop(distObject, forceGraspL, forceGraspR, maxForceL, maxForceR):
ser.write('a'.encode())
...other code... mostly assigning values to the variables below
motorBytes = bytearray([decToByte(left), decToByte(right), decToByte(leftMid), decToByte(rightMid), distPerc]) #puts the motor values into an array as hex
print(motorBytes)
ser.write(motorBytes)
return
motor_loop(1.5, 0, 30, 60, 60) #call the function
这些值是任意的,因为我正在打印通过串行通信发送到两边的值,它们是正确的值。你知道吗
通用Arduino代码:
void loop()
{
while (Serial.available()>0) //checks to see if anything needs to be sent,
{ //denoted by recieveing signal from pySerial
char inByte = Serial.read();
if (inByte == 'a')
{
run_loop();
}
}
}
void run_loop()
{
int num = Serial.readBytes(values, 5);
if (num < 5)
{
return;
}
writeMotor(mtrPinLeft, mtrSpeedLeft, mtrPinRight, mtrSpeedRight, mtrPinLeftMid, mtrSpeedLeftMid, mtrPinRightMid, mtrSpeedRightMid);
(其中writeMotor是将所有电机值写入正确引脚的函数。)
我感觉run\u loop()中arduino位的代码部分:带有返回,以便在函数没有保存所有数据的情况下不运行该函数。有谁能证实这个预感,并对我如何解决这个问题有什么建议吗?我对函数也不是很熟悉,所以我可能会遗漏一些关于如何处理函数的知识。提前谢谢!你知道吗
编辑:ser声明为ser=序列号。序列号(port='COM4')和上面的所有变量(left、right、leftMid等)都在表示其他代码的空格中声明
目前没有回答
相关问题 更多 >
编程相关推荐