公告

國明的網路筆記

2023年7月24日 星期一

.Net SerialPort.Open 方法

 .Net SerialPort.Open 方法

https://learn.microsoft.com/zh-tw/dotnet/api/system.io.ports.serialport.open?view=dotnet-plat-ext-7.0


C#

public static void Main() { string name; string message; StringComparer stringComparer = StringComparer.OrdinalIgnoreCase; Thread readThread = new Thread(Read); // Create a new SerialPort object with default settings. _serialPort = new SerialPort(); // Allow the user to set the appropriate properties. _serialPort.PortName = SetPortName(_serialPort.PortName); _serialPort.BaudRate = SetPortBaudRate(_serialPort.BaudRate); _serialPort.Parity = SetPortParity(_serialPort.Parity); _serialPort.DataBits = SetPortDataBits(_serialPort.DataBits); _serialPort.StopBits = SetPortStopBits(_serialPort.StopBits); _serialPort.Handshake = SetPortHandshake(_serialPort.Handshake); // Set the read/write timeouts _serialPort.ReadTimeout = 500; _serialPort.WriteTimeout = 500; _serialPort.Open(); _continue = true; readThread.Start(); Console.Write("Name: "); name = Console.ReadLine(); Console.WriteLine("Type QUIT to exit"); while (_continue) { message = Console.ReadLine(); if (stringComparer.Equals("quit", message)) { _continue = false; } else { _serialPort.WriteLine( String.Format("<{0}>: {1}", name, message)); } } readThread.Join(); _serialPort.Close(); } public static void Read() { while (_continue) { try { string message = _serialPort.ReadLine(); Console.WriteLine(message); } catch (TimeoutException) { } } }


沒有留言:

張貼留言