1、添加using System.IO.Ports;命名空间,因为调用串口需要使用SerialPort类,这个类在此命名空间内。
2、我在添加的时候,发现SerialPort类识别不出来,后来搜索到的原因是没有安装一个NuGet包,于是就需要安装此包。安装方式如下:
在程序包管理控制台中,粘贴:Install-Package Microsoft.Windows.Compatibility -Version 5.0.2
等待安装完成。
3、编写测试代码。
// Use this code inside a project created with the Visual C# > Windows Desktop > Console Application template.
// Replace the code in Program.cs with this code.
using System;
using System.IO.Ports;
using System.Threading;
public class PortChat
{
static bool _continue;
static SerialPort _serialPort;
public static void Main()
{
string name;
string message;
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 = "COM2";
_serialPort.BaudRate = 115200;
_serialPort.Parity = Parity.None;
_serialPort.DataBits = 8;
_serialPort.StopBits = StopBits.One;
_serialPort.Handshake = Handshake.None;
// 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 (message.ToLower() == "quit")
{
_continue = false;
}
else
{
_serialPort.WriteLine(
String.Format("<{0}>: {1}", name, message));
}
}
readThread.Join();//阻塞调用,直到main线程退出
_serialPort.Close();
}
public static void Read()
{
while (_continue)
{
try
{
string message = _serialPort.ReadLine();
Console.WriteLine(message);
}
catch (TimeoutException) { }
}
}
}
4、测试使用的是虚拟串口,使用UDP虚拟出一个串口2,测试结果如下。