大致需求
最近有这样一个需求,采用某国内公司的测距模块,并形成指定样式的模块组,串口同学,有数据结构和通讯说明文档;
其实网上有很多提供源码的串口调试工具之类的资源,一般的需求都能从这些资源中找到解决方案,我这里也仅仅是记录一下我的开发过程,已经遇到过的一些问题和解决办法,希望能帮到一些需要的人。
首先,既然是模组,那就是要同时和多个模块建立通讯。网上的串口通讯工具一般都仅仅是单通讯,要实现同时与多个串口通讯,还是要注意一些问题的,比如并发问题就是很关键的一点。
.NET 2.0往后提供对串口的支持,最重要的就是SerialPort类,有相关类可以在命名空间System.IO.Ports下找到。如果有不清楚的可以自己百度
万物皆对象,将一个串口视为一个对象,简单封装一下
class ZYComports
{
#region 串口对象的基本参数设置
/// <summary>
/// 串口对象
/// </summary>
private SerialPort serialPort;
/// <summary>
/// 端口号
/// </summary>
private string comportName;
/// <summary>
/// 波特率
/// </summary>
private int baudRate = 115200;
/// <summary>
/// 读取超时
/// </summary>
private int readTimeout = 5000;
/// <summary>
/// 写入超时
/// </summary>
private int writeTimeout = 5000;
/// <summary>
/// 读取缓存大小
/// </summary>
private int readBufferSize = 1024;
/// <summary>
/// 写入缓存大小
/// </summary>
private int writeBufferSize = 1024;
/// <summary>
/// 数据位
/// </summary>
private int dataBits = 8;
/// <summary>
/// 停止位
/// </summary>
private Parity parity = 0;
/// <summary>
/// 接收位
/// </summary>
private int receivedBytesThreshold = 1;
#endregion
#region 串口硬件的安装参数
/// <summary>
/// 探测方向
/// </summary>
private Orientation orientation;
/// <summary>
/// 探测器的坐标、排列顺序为从左到右,从上到下,从1开始
/// </summary>
private UInt16 installIndex;
/// <summary>
/// 左边距或上边距,单位为像素px
/// </summary>
private UInt16 marginPX;
/// <summary>
/// X、或Y方向物理有效取值范围
/// </summary>
private UInt16 minEffective = 10; //单位cm
private UInt16 maxEffective = 1000; //单位cm
public int effectiveValue = 0;
#endregion
#region 业务逻辑变量参数
private Period period;
#endregion
public ZYComports()
{
serialPort = new SerialPort();
}
public string ComportName { get => comportName; set => comportName = value; }
public int BaudRate { get => baudRate; set => baudRate = value; }
public int ReadTimeout { get => readTimeout; set => readTimeout = value; }
public int WriteTimeout { get => writeTimeout; set => writeTimeout = value; }
public int ReadBufferSize { get => readBufferSize; set => readBufferSize = value; }
public int WriteBufferSize { get => writeBufferSize; set => writeBufferSize = value; }
public int DataBits { get => dataBits; set => dataBits = value; }
public Parity Parity { get => parity; set => parity = value; }
public int ReceivedBytesThreshold
{
get => receivedBytesThreshold; set => receivedBytesThreshold = value;
}