在Python中通过串行连接设置和发送数据

2024-06-26 13:47:13 发布

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

我有C++编写的代码,我正在翻译成Python。C++代码是:

    WriteBuffer[0] = unsigned char (0xc0 + (Steer & 0x1F));         // change the signal to conform to jrk motor controller
    WriteBuffer[1] = unsigned char (Steer >> 5) & 0x7F;             //      two-word feedback signal

    if(!WriteFile(hSerial[1], &WriteBuffer, 2, &BytesWritten, NULL)){
        //error occurred. Report to user.
        cout<<"error writing T2 \n";
        cout<<BytesWritten;
    } 

我用Python编写的代码不起作用,是这样的:

rightWheel = bytearray(b'\xc000')
rightWheel[0] = rightWheel[0] + (rightWheelSteer & 0x1F)
rightWheel[1] = (rightWheelSteer >> 5) & 0x7F
rightWheel = bytes(rightWheel)
ser2.write(rightWheel)

rightweel的第一个字节似乎包含正确的数据,但第二个字节不包含。我希望rightweel[1]包含一个字节,但它没有。你知道吗

什么样的Python代码可以让我设置一个字节,其中包含一个右移5位的变量,然后用0x7F按位“与”运算?你知道吗


Tags: to代码signal字节errorchangecharcout
1条回答
网友
1楼 · 发布于 2024-06-26 13:47:13

问题出在我的第一行代码中。我有这个:

rightWheel = bytearray(b'\xc000')

但这使得rightweel变成了3个字节,将最右边的两个0作为每个0的一个字节ASCII字符。所以右轮变成了b'\xc0\x30\x30'。你知道吗

修改后的第一行代码正常工作:

righWheel = bytearray(b'\xc0\x00')

相关问题 更多 >