欢迎来到天天文库
浏览记录
ID:40532689
大小:153.00 KB
页数:8页
时间:2019-08-04
《C#串口通信总结》由会员上传分享,免费在线阅读,更多相关内容在教育资源-天天文库。
1、C#串口通信总结作者:不详出处:网络转载2011/10/1016:01:52阅读0次 我们知道对于标准DLL,可以采用DllImport进行调用。例如:[DllImport("KMY350X.dll")]privatestaticexternintOpenPort(intPortNum,intBaudRate);甘特图Xgantt(全球首款甘特图32年历史)VisualWebGui(完美的用户界面解决方案)StimulsoftReports.Net(报表生成控件)DXperienceUniPremium白金版(慧都独家) 如果一些
2、厂家比较懒的话,没有提供相应的dll,我们只能对它进行串口通信编程了。以前从没接触过串口编程,最近在一个项目中有几个地方都需要采用串口通信,跟公司一个老手请教后,感觉学到了很多东西,特在此做个总结: 一:首先我们来认识下什么是串口: 右键我的电脑-管理-设备管理器-端口,选择一个端口,点击属性。 我们可以看到该串口的属性,在C#中我们使用SerialPort类来表示串口 ConfigClassconfig=newConfigClass();comm.serialPort.PortName=config.ReadConfig("
3、SendHealCard");//波特率comm.serialPort.BaudRate=9600;//数据位comm.serialPort.DataBits=8;//两个停止位comm.serialPort.StopBits=System.IO.Ports.StopBits.One;//无奇偶校验位comm.serialPort.Parity=System.IO.Ports.Parity.None;comm.serialPort.ReadTimeout=100;comm.serialPort.WriteTimeout=-1; 二:
4、串口调试工具: 在对串口进行编程时候,我们要向串口发送指令,然后我们解析串口返回的指令。在这里向大家推荐一款工具。 串口调试助手.exe 将要发送的指令用空格隔开,选择HEX显示为放回的字符串。 三:正式编程: 编写Comm类: publicclassComm{publicdelegatevoidEventHandle(byte[]readBuffer);publiceventEventHandleDataReceived; publicSerialPortserialPort;Threadthread;volatile
5、bool_keepReading; publicComm(){serialPort=newSerialPort();thread=null;_keepReading=false;} publicboolIsOpen{get{returnserialPort.IsOpen;}} privatevoidStartReading(){if(!_keepReading){_keepReading=true;thread=newThread(newThreadStart(ReadPort));thread.Start();}} priv
6、atevoidStopReading(){if(_keepReading){_keepReading=false;thread.Join();thread=null;}} privatevoidReadPort(){while(_keepReading){if(serialPort.IsOpen){intcount=serialPort.BytesToRead;if(count>0){byte[]readBuffer=newbyte[count];try{Application.DoEvents();serialPort.Read(
7、readBuffer,0,count);if(DataReceived!=null)DataReceived(readBuffer);Thread.Sleep(100);}catch(TimeoutException){}}}}} publicvoidOpen(){Close();serialPort.Open();if(serialPort.IsOpen){StartReading();}else{MessageBox.Show("串口打开失败!");}} publicvoidClose(){StopReading();seri
8、alPort.Close();} publicvoidWritePort(byte[]send,intoffSet,intcount){if(IsOpen){serialPort.Write(send,offSet,c
此文档下载收益归作者所有