簡體   English   中英

在Python中通過串行連接設置和發送數據

[英]Setting up and sending data over a serial connection in 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)

rightWheel的第一個字節似乎包含正確的數據,但第二個字節沒有。 我希望rightWheel [1]包含一個字節,但不是。

什么樣的Python代碼可以讓我設置一個包含向右移位5位然后用0x7F按位與的變量的單個字節?

問題出在我的第一行代碼中。 我有這個:

rightWheel = bytearray(b'\xc000')

但這就是將rightWheel分成3個字節,將最右邊的兩個0當作一個字節的ASCII字符,每個0。 所以rightWheel變成了b'\\ xc0 \\ x30 \\ x30'。

修改后的第一行代碼可以正常工作:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM