WinForms Serial Port Data Tutorial

To achieve data transmission on a serial port in WinForm, you can follow these steps:

  1. Include the System.IO.Ports namespace to utilize the SerialPort class.
  2. In the WinForm designer, add a SerialPort control and name it serialPort1.
  3. Set the relevant parameters of the serial port in the code, such as baud rate, data bits, and parity. This can be done in the Form’s Load event, as shown below:
private void Form1_Load(object sender, EventArgs e)
{
    serialPort1.BaudRate = 9600;  // 设置波特率
    serialPort1.DataBits = 8;     // 设置数据位
    serialPort1.Parity = Parity.None;  // 设置校验位
    serialPort1.StopBits = StopBits.One;  // 设置停止位
}
  1. Implement the event handling function for receiving data through the serial port. Use the serialPort1.DataReceived event to read the data received from the serial port in the event handling function, as shown below:
private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
    string receivedData = serialPort1.ReadExisting();  // 读取串口接收的数据
    // 处理接收到的数据
    // ......(根据具体需求进行操作)
}
  1. Call the function to send data through the serial port. Use the serialPort1.Write method to send the data to the port wherever needed, as shown below.
private void SendData(string sendData)
{
    if (serialPort1.IsOpen)
    {
        serialPort1.Write(sendData);  // 发送数据
    }
}
  1. To open and close the serial port, you can use the methods serialPort1.Open and serialPort1.Close.

The above are the basic steps to implement serial data communication in WinForm. Depending on specific requirements, additional operations may be needed, such as error handling and timeout settings.

bannerAds