0

I have code written in C++ that I am translating to Python. The C++ code is:

    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;
    } 

The code I have written in Python, which does not work, is this:

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

The first byte of rightWheel seems to contain the correct data, but the second byte does not. I want rightWheel[1] to contain a single byte, but it does not.

What Python code will let me set up a single byte containing a variable shifted right five bits and then bitwise-anded with 0x7F?

3
  • Can you provide example input and output? Your code looks correct and produces sensible results for me. Commented Jun 30, 2016 at 13:52
  • Thank you very much for checking the code. When I went to create example input and output, I found a problem with my test code that was producing the problem. So my code is indeed correct. Commented Jul 9, 2016 at 0:27
  • Oops, there still was a problem, as noted in my answer below. Commented Jul 9, 2016 at 3:15

1 Answer 1

1

The problem was in my first line of code. I had this:

rightWheel = bytearray(b'\xc000')

But that was making rightWheel into 3 bytes, taking the rightmost two 0s as one-byte ASCII characters for 0 each. So rightWheel became b'\xc0\x30\x30'.

This modified first line of code works correctly:

righWheel = bytearray(b'\xc0\x00')
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.