命名空间:using System.IO.Ports;
该类提供了同步 I/O 和事件驱动的 I/O、对管脚和中断状态的访问以及对串行驱动程序属性的访问。

操作类声明: SerialPort sp = null;

/// <summary>
/// 打开串口
/// </summary>
/// <param name="protName">串口号</param>
/// <param name="baudRate">波特率</param>
/// <param name="dataBit">数据位</param>
/// <param name="stopBits">停止位</param>
/// /// <param name="parity">校验位</param>
/// <returns></returns>
public bool OpenCom(string protName, int baudRate, int dataBit, float stopBits, int parity)
{
bool flag = true;
if (sp == null)
{
sp = new SerialPort();
}
sp.PortName = protName;//串口号
sp.BaudRate = baudRate;//波特率
float f = stopBits;//停止位
if (f == 0)
{
sp.StopBits = StopBits.None;
}
else if (f == 1.5)
{
sp.StopBits = StopBits.OnePointFive;
}
else if (f == 1)
{
sp.StopBits = StopBits.One;
}
else
{
sp.StopBits = StopBits.Two;
}

sp.DataBits = dataBit;//数据位

if (parity == 0)
{
sp.Parity = Parity.None;
}
else if (parity == 1)
{
sp.Parity = Parity.Odd;
}
else if (parity == 2)
{
sp.Parity = Parity.Even;
}
else
{
sp.Parity = Parity.None;
}

// sp.ReadTimeout = 1000;//设置超时读取时间
// sp.WriteTimeout = 1000;//超时写入时间
try
{
if (!sp.IsOpen)
{
sp.Open();

}
}
catch (Exception)
{
flag = false;
}
return flag;
}
/// <summary>
/// 关闭端口
/// </summary>
/// <returns></returns>
public bool CloseCom()
{
try
{
if (sp.IsOpen)
{
sp.Close();
}
return true;
}
catch
{
return false;
}
}
串口的打开和关闭

相关文章:

  • 2021-11-18
  • 2022-12-23
  • 2022-12-23
  • 2021-12-29
  • 2021-06-12
  • 2022-02-08
猜你喜欢
  • 2021-07-05
  • 2021-10-16
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案