How to use a C# serial port in the way it is used in Python

Viewed 35

I am trying to send the bytes (b'\x03\r') to a device on COM5. The result will be the micropython board on the other end crashing. The python code results in the board freezing (As intended). The C# code results in no changes on the device's end, and the serial port not working until it is replugged. How can I get the C# code to do the same thing that the python code does?

This python code works:

import serial # this is installed with 'pip install pyserial'

ser = serial.Serial(
    port='COM5',
    baudrate=115200,
)
ser.write(b'\x03\r')

I tried to make this C# code to do the same thing but it does not work

using System.IO.Ports;
public static class tester {
    public static void main(/* String[] args */) {
        SerialPort sport = new SerialPort("COM5", 115200); 
        sport.Open();
        sport.Write(new byte[]{0x03, 0xD}, 0, 2);
        sport.Close();
    }
}

Thanks for trying to help me :)

1 Answers

The solution as @kunif and @Hans Passant said was that I needed to set certain parameters as their defaults are not the same on different implementations of serial port libraries. To use a serial device that works fine with the default settings of PySerial use the following code. You will likely have to change the baud rate based on your specific device.

SerialPort sport = new SerialPort("COM5", 115200);
// I love StackOverflow
sport.Handshake = Handshake.None;
sport.DtrEnable = true;
sport.RtsEnable = true;
sport.StopBits = StopBits.One;
sport.DataBits = 8;
sport.Parity = Parity.None;
sport.Open();
Related