0

I'm new here and I'm a beginner in python programming. I need to convert C# code to python but I stuck when I wanted to read serial data as byte array. I used extend() and bytearray() functions but nothing is working.

Bellow is the C# code which I want to convert to Python 3.x

do
{

    int _byteToRead = P._serialPort.BytesToRead;
    byte[] inBuffer = new byte[_byteToRead];
    P._serialPort.Read(inBuffer, 0, _byteToRead); //Reads a number of characters from the System.IO.Ports.SerialPort input buffer and writes them into an array of characters at a given offset.
    byte MatchStart = 242; // HEX: F2
    byte MatchEnd = 248; // HEX: F8

    try
    {
        for (int j = 0; j < inBuffer.Length; j++)
        {
            if (inBuffer[j] == MatchStart)

I don't know how to convert the first 3 lines.

I tried:

bytedata=ser.read(10000) # I need to 
b=bytearray()
b.extend(map(ord, bytedata))

or:

bytedata+=ser.read(ser.inWaiting())
z=bytearray(bytedata)

Thanks.

Matthieu Brucher
  • 21,634
  • 7
  • 38
  • 62
vlad
  • 11
  • 1
  • can't help with the question, but recommend changing the title to be clearer that you're asking for help doing it in Python. I clicked it because I filtered to c#-tagged questions and have done this in c#... but that's no use to you... Something like "How can I translate this c# serial port code to python?" would perhaps be better? – GPW Jan 14 '19 at 11:57
  • Ignore the return value of `SerialPort.Read` at your peril. Although you are requesting a read of `_byteToRead` bytes, there is no guarantee that this number of bytes will be read. The only way to **know** how many bytes were read is by means of the return value. – spender Jan 14 '19 at 11:59
  • 1
    ...i.e. the code you are trying to translate is not so good – spender Jan 14 '19 at 12:02
  • Take a look at this [SO Question](https://stackoverflow.com/questions/45411924/python3-two-way-serial-communication-reading-in-data), answers have been provided for reading and writing in serial port – karthickj25 Jan 14 '19 at 12:08

0 Answers0