0

Ive taken up an old project a former colleague used to work on.

The question boils down to reading from a serial port. In short: Through a GUI, I'm able to communicate to a camera, controlling zoom functions. The code is written in C# but I've only ever used Python myself.

In Python, writing to the camera, I would do this:

import serial
ser = serial.Serial(port = "COM2", baudrate=9600,
                       bytesize=8, timeout=2, stopbits=serial.STOPBITS_ONE)

inquiry   = 0x81,0x09,0x04,0x47,0xFF,0x4b
ser.write(inquiry)
print(ser.read(7))  

I'm reading 7 bytes because I know the camera will reply with 7 bytes. The output looks like this:

b'\x90P\x04\x00\x00\x00\xff' which is exactly what I'm looking for.

Now, I'm having trouble doing this using C#. Serial port is set up like this in C#:

        private void SetupAndOpen(string Comportname)
    {
        try
        {
            if (SP1.IsOpen)
            {
                SP1.Close();
            }
            SP1.BaudRate = baud;
            SP1.Parity = parity;
            SP1.DataBits = databit;
            SP1.StopBits = stopbit;
            SP1.Handshake = handshake;
            SP1.DtrEnable = true;
            SP1.RtsEnable = true;
            SP1.ReadTimeout = readtimeout;
            SP1.PortName = Comportname;
            SP1.Encoding = encoding;

            SP1.Open();
            SP1.ReadTimeout = 200;


            if (SP1.IsOpen)
            {
                output.Add("COM is Open!");
            }

        }
        catch (Exception ex)
        {
            errormessage = ex.Message;
        }

I'm able to send my command to the camera but I'm unable to read back the correct number of bytes. Here's what I have:

        Console.WriteLine(SP1.ReadByte());

This reads ONE byte:

144

Which, when converted to hex, equals 90 (the same as Python gave me).

Is there a way to read 7 bytes from serial in C#? I tried Readline but it throws this error:

"Exception thrown: 'System.TimeoutException' in System.dll"

Sorry for the stupid question - any help appriciated!

Aleks-CST
  • 3
  • 4
  • Look at the other methods available on the object, like [`Read`](https://learn.microsoft.com/en-us/dotnet/api/system.io.ports.serialport.read?view=dotnet-plat-ext-6.0). You'll have a choice of reading bytes or characters and as long as the serial port is synchronous, you should get what you want. Or ReadByte 7 times. – tdelaney Mar 09 '23 at 16:55
  • The following may be helpful: https://stackoverflow.com/a/68807066/10024425, https://stackoverflow.com/a/69946343/10024425, and https://stackoverflow.com/a/65971845/10024425 – Tu deschizi eu inchid Mar 09 '23 at 22:45

1 Answers1

0

Thanks for the replies. I was able to read the buffer with a loop using ReadByte():

        int[] posBuffer = new int[7];
        for (int i = 0; i < 7; i++)
        {
            posBuffer[i] = SP1.ReadByte();
        }
        Console.WriteLine("[{0}]", string.Join(", ", posBuffer));
Aleks-CST
  • 3
  • 4