Python PC到Arduino串行通信

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

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

我对Python和Arduino都很陌生。如果你需要更多的信息,告诉我。在

我想做的是: 我想用arduino控制几个伺服系统。我想改变伺服的角度在一个图形用户界面在个人电脑(后来的RPi)和发送他们通过串行通信到阿尔杜诺

我的Arduino代码如下:

#include <Servo.h> 

int angle;
int pinServo1 = 5;
Servo servo1;       
int min = 0.547;    
int max = 2.47;     

void setup()
{
   Serial.begin(9600);
   pinMode(pinServo1,OUTPUT);   
   servo1.attach(pinServo1,min,max);        
}

void loop()
{
   if(Serial.available() > 0)
      {
        Serial.read();
        angle = Serial.parseInt();
        servo1.write(angle);
      }
}

到目前为止没有错误。在

问题似乎出在我的Python代码上:

^{pr2}$

我得到了这个错误:

Enter new angle:
90
Traceback (most recent call last):
  File "C:/Users/yoogibubu/Desktop/STUDIUM/BACHELORARBEIT/GUI/send.py", line 10, in <module>
    arduino.write(angle)
  File "C:\Program Files (x86)\PYTHON\lib\site-packages\serial\serialwin32.py", line 283, in write
data = to_bytes(data)
  File "C:\Program Files (x86)\PYTHON\lib\site-packages\serial\serialutil.py", line 76, in to_bytes
    b.append(item)  # this one handles int and str for our emulation and ints for Python 3.x
TypeError: an integer is required
>>>    

如果我试图将输入解析为整数,我会得到另一个错误:

TypeError: 'int' object is not iterable

有人能告诉我怎么了吗?提前谢谢你!在


Tags: 代码inpy错误lineserialarduinofile
2条回答

您应该能够直接编写这个loop()

void loop()
{
   if(Serial.available() > 0)
      {
        angle = Serial.read();
        servo1.write(angle);
      }
}

但问题在于servo1.attach()。你的伺服minmax在美国应该是最小和最大脉冲宽度的int值(而不是毫秒)。这用于映射读取结果。在

你可能想要这样的东西:

^{pr2}$

在串行写入应为字节数组数据类型参数。要发送字符串,必须首先将它们转换为字节数组,尤其是在Python3.x中,因为字符串是使用Unicode存储的,这使得事情比简单的字符数组更加复杂。在

尝试以下操作:

arduino.write(angle.encode())

相关问题 更多 >

    热门问题