博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
.Net Com口通信编程例子
阅读量:5098 次
发布时间:2019-06-13

本文共 3040 字,大约阅读时间需要 10 分钟。

private string _sComPortNumber; private bool _bFoundPortNumber; private System.Windows.Forms.Control _oStaticShow; private System.IO.Ports.SerialPort _oCIMControler; ///  /// COM口名 ///          public string ComPortName { get { return _sComPortNumber; } } ///  /// 编码 ///          public Encoding StringEncoding { get; set; } ///  /// 比特率 ///          public int BaudRate { get; set; } ///  /// 数据位 ///          public int DataBits { get; set; } ///  /// 奇偶检验 ///          public System.IO.Ports.Parity Parity { get; set; } ///  /// 停止位 ///          public System.IO.Ports.StopBits StopBits { get; set; } private bool OpenPortAndSendMsg()         {
foreach (string tmpName in System.IO.Ports.SerialPort.GetPortNames()) {
foreach (string sCurrentMachinePortNumber in System.IO.Ports.SerialPort.GetPortNames()) {
try {
if (_bFoundPortNumber == false) {
System.IO.Ports.SerialPort otmpsp = new System.IO.Ports.SerialPort(); otmpsp.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(otmpsp_DataReceived); otmpsp.PortName = sCurrentMachinePortNumber; otmpsp.BaudRate = this.BaudRate; otmpsp.DataBits = this.DataBits; otmpsp.Parity = this.Parity; otmpsp.StopBits = this.StopBits; otmpsp.Open(); //写数据************************ otmpsp.Write(new byte[] { 2 }, 0, 1); string Command = "ST"; otmpsp.Write(Command); otmpsp.Write(new byte[] { 3 }, 0, 1); otmpsp.Write(new byte[] { 6 }, 0, 1); otmpsp.Write(new byte[] { 5 }, 0, 1); //**************************** System.Threading.Thread.Sleep(500); otmpsp.Close(); } else {
return true; } } catch (Exception ex) {
} } } return false; } void otmpsp_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e) {
System.IO.Ports.SerialPort oSenderObject = sender as System.IO.Ports.SerialPort; if (oSenderObject.BytesToWrite > 0) {
oSenderObject.BaseStream.Flush(); } int iReadFlag = oSenderObject.BytesToRead; while (iReadFlag > 0) {
string sReturn = oSenderObject.ReadExisting(); if (sReturn.Contains("")) {
_bFoundPortNumber = true; _sComPortNumber = oSenderObject.PortName; } iReadFlag = oSenderObject.BytesToRead; } }

转载于:https://www.cnblogs.com/ZC_Mo-Blog/archive/2011/07/18/2109457.html

你可能感兴趣的文章
【.Net Core】Assets file project.assets.json not found. Run a NuGet package restore
查看>>
mybatis框架
查看>>
自己的ORMapping
查看>>
Java线程:线程状态的转换(转)
查看>>
视图以日期作为条件查询条件时虽显式转换?
查看>>
LintCode: Number of Islands
查看>>
git教程: 创建版本库
查看>>
Webstorm上面通过babel将es6转化为es5
查看>>
黑马程序员 参数化查询避免SQL注入漏洞攻击
查看>>
jzoj100029
查看>>
起底多线程同步锁(iOS)
查看>>
[BZOJ 1951] 古代猪文
查看>>
数据库系统原理——ER图转换成关系模式集的算法
查看>>
SPOJ KPSUM ★(数位DP)
查看>>
Python-requests之POST Data的json问题
查看>>
【Linux高级驱动】网卡驱动分析
查看>>
字符串处理函数
查看>>
jenkins修改时区
查看>>
比较git commit 两个版本之间次数
查看>>
jQuery.support
查看>>