SerialPort控件的使用Word下载.docx

上传人:b****8 文档编号:22368710 上传时间:2023-02-03 格式:DOCX 页数:33 大小:47.33KB
下载 相关 举报
SerialPort控件的使用Word下载.docx_第1页
第1页 / 共33页
SerialPort控件的使用Word下载.docx_第2页
第2页 / 共33页
SerialPort控件的使用Word下载.docx_第3页
第3页 / 共33页
SerialPort控件的使用Word下载.docx_第4页
第4页 / 共33页
SerialPort控件的使用Word下载.docx_第5页
第5页 / 共33页
点击查看更多>>
下载资源
资源描述

SerialPort控件的使用Word下载.docx

《SerialPort控件的使用Word下载.docx》由会员分享,可在线阅读,更多相关《SerialPort控件的使用Word下载.docx(33页珍藏版)》请在冰豆网上搜索。

SerialPort控件的使用Word下载.docx

通常情况下,PortName正常返回的值为COM1、COM2……,SerialPort类最大支持的端口数突破了CommPort控件中CommPort属性不能超过16的限止,大大方便了用户串口设备的配置。

b.通讯格式

SerialPort类对分别用[BaudRate]、[Parity]、[DataBits]、[StopBits]属性设置通讯格式中的波特率、数据位、停止位和校验位,其中[Parity]和[StopBits]分别是枚举类型Parity、StopBits,Parity类型中枚举了Odd(奇)、Even(偶)、Mark、None、Space,Parity枚举了None、One、OnePointFive、Two。

SerialPort类提供了七个重载的构造函数,既可以对已经实例化的SerialPort对象设置上述相关属性的值,也可以使用指定的端口名称、波特率和奇偶校验位数据位和停止位直接初始化SerialPort类的新实例。

3.串口的打开和关闭

SerialPort类没有采用MSComm.PortOpen=True/False设置属性值打开关闭串口,相应的是调用类的Open()和Close()方法。

4.数据的发送和读取

Serial类调用重载的Write和WriteLine方法发送数据,其中WriteLine可发送字符串并在字符串末尾加入换行符,读取串口缓冲区的方法有许多,其中除了ReadExisting和ReadTo,其余的方法都是同步调用,线程被阻塞直到缓冲区有相应的数据或大于ReadTimeOut属性设定的时间值后,引发ReadExisting异常。

5.DataReceived事件

该事件类似于MSComm控件中的OnComm事件,DataReceived事件在接收到了[ReceivedBytesThreshold]设置的字符个数或接收到了文件结束字符并将其放入了输入缓冲区时被触发。

其中[ReceivedBytesThreshold]相当于MSComm控件的[Rthreshold]属性,该事件的用法与MsComm控件的OnComm事件在CommEvent为comEvSend和comEvEof时是一致的。

三.SerialPort的使用

对于熟悉MSComm控件的程序设计者,SerialPort类是相当容易上手的。

在进行串口通讯时,一般的流程是设置通讯端口号及波特率、数据位、停止位和校验位,再打开端口连接,发送数据,接收数据,最后关闭端口连接这样几个步骤。

数据接收的设计方法在这里比较重要,采用轮询的方法比较浪费时间,在VisualBasic中的延时方法中一般会调用API并用DOEvents方法来处理,但程序不易控制,建议采用DataReceived事件触发的方法,合理的设置ReceivedBytesThreshold的值,若接收的是定长的数据,则将ReceivedBytesThreshold设为接收数据的长度,若接收数据的结尾是固定的字符或字符串则可采用ReadTo的方法或在DataReceived事件中判断接收的字符是否满足条件。

SerialPort类读取数据的许多方法是同步阻塞调用,尽量避免在主线程中调用,可以使用异步处理或线程间处理调用这些读取数据的方法。

由于DataReceived事件在辅线程被引发,当收到完整的一条数据,返回主线程处理或在窗体上显示时,请注意跨线程的处理,C#可采用控件异步委托的方法Control.BeginInvoke及同步委托的方法Invoke。

四.结束语

在.NET平台下熟练使用SerialPort类,可以很好地开发出串口通讯类程序,对于过去使用MSComm控件设计了一些通讯程序,也可以将MSComm控件替换为SerialPort类,当然为了避免对以前的项目做大的改动,可以使用SerialPort类设计一些与MSComm控件具有相同接口的类,在今后工业控制中,SerialPort类将广泛地应用于串口通讯程序的设计中,发挥着与MSComm控件一样的作用。

C#SerialPort运行方式

SerialPort中串口数据的读取与写入有较大的不同。

由于串口不知道数据何时到达,因此有两种方法可以实现串口数据的读取。

一、线程实时读串口;

二、事件触发方式实现。

由于线程实时读串口的效率不是十分高效,因此比较好的方法是事件触发的方式。

在SerialPort类中有DataReceived事件,当串口的读缓存有数据到达时则触发DataReceived事件,其中SerialPort.ReceivedBytesThreshold属性决定了当串口读缓存中数据多少个时才触发DataReceived事件,默认为1。

另外,SerialPort.DataReceived事件运行比较特殊,其运行在辅线程,不能与主线程中的显示数据控件直接进行数据传输,必须用间接的方式实现。

如下:

SerialPort 

spSend;

//spSend,spReceive用虚拟串口连接,它们之间可以相互传输数据。

spSend发送数据

spReceive;

//spReceive接受数据

TextBox 

txtSend;

//发送区

txtReceive;

//接受区

Button 

btnSend;

//数据发送按钮

delegate 

void 

HandleInterfaceUpdateDelegate(string 

text);

//委托,此为重点

HandleInterfaceUpdateDelegate 

interfaceUpdateHandle;

public 

InitClient() 

//窗体控件已在初始化

{

interfaceUpdateHandle 

new 

HandleInterfaceUpdateDelegate(UpdateTextBox);

//实例化委托对象

spSend.Open();

//SerialPort对象在程序结束前必须关闭,在此说明

spReceive.DataReceived 

+= 

Ports.SerialDataReceivedEventHandler(spReceive_DataReceived);

spReceive.ReceivedBytesThreshold 

1;

spReceive.Open();

}

btnSend_Click(object 

sender,EventArgs 

e)

spSend.WriteLine(txtSend.Text);

spReceive_DataReceived(object 

sender,Ports.SerialDataReceivedEventArgs 

byte[] 

readBuffer 

byte[spReceive.ReadBufferSize];

spReceive.Read(readBuffer, 

0, 

readBuffer.Length);

this.Invoke(interfaceUpdateHandle, 

string[] 

Encoding.Unicode.GetString(readBuffer) 

});

private 

UpdateTextBox(string 

text)

txtReceive.Text 

text;

点评:

这个例子包括了这个控件几乎所有的操作,非常有参考价值.serialPort是在.netframework2.0中才有的东西,感觉这个东西和MSCOMM很相似.这里给出的例子是基于和CSHAPE

的,相应的可以在Cshape和c++中使用,基本上都是一样的.

ImportsSystem

ImportsSystem.IO.Ports

ImportsSystem.Threading

PublicClassPortChat

Shared_continueAsBoolean

Shared_serialPortAsSerialPort

PublicSharedSubMain()

DimnameAsString

DimmessageAsString

DimsComparerAsStringComparer=StringComparer.OrdinalIgnoreCase

DimreadThreadAsThread=NewThread(AddressOfRead)

'

CreateanewSerialPortobjectwithdefaultsettings.

_serialPort=NewSerialPort()

Allowtheusertosettheappropriateproperties.

_serialPort.PortName=SetPortName(_serialPort.PortName)

_serialPort.BaudRate=SetPortBaudRate(_serialPort.BaudRate)

_serialPort.Parity=SetPortParity(_serialPort.Parity)

_serialPort.DataBits=SetPortDataBits(_serialPort.DataBits)

_serialPort.StopBits=SetPortStopBits(_serialPort.StopBits)

_serialPort.Handshake=SetPortHandshake(_serialPort.Handshake)

Settheread/writetimeouts

_serialPort.ReadTimeout=500

_serialPort.WriteTimeout=500

_serialPort.Open()

_continue=True

readThread.Start()

Console.Write("

Name:

"

name=Console.ReadLine()

Console.WriteLine("

TypeQUITtoexit"

While(_continue)

message=Console.ReadLine()

IfsComparer.Equals("

quit"

message)Then

_continue=False

Else

_serialPort.WriteLine(_

String.Format("

<

{0}>

:

{1}"

name,message))

EndIf

endwhile

readThread.Join()

_serialPort.Close()

EndSub

PublicSharedSubRead()

Try

DimmessageAsString=_serialPort.ReadLine()

Console.WriteLine(message)

CatchexAsTimeoutException

Donothing

EndTry

EndWhile

PublicSharedFunctionSetPortName(ByValdefaultPortNameAsString)AsString

DimnewPortNameAsString

AvailablePorts:

"

DimsAsString

ForEachsInSerialPort.GetPortNames()

{0}"

s)

Nexts

COMport({0}):

defaultPortName)

newPortName=Console.ReadLine()

IfnewPortName="

Then

newPortName=defaultPortName

ReturnnewPortName

EndFunction

PublicSharedFunctionSetPortBaudRate(ByValdefaultPortBaudRateAsInteger)AsInteger

DimnewBaudRateAsString

BaudRate({0}):

defaultPortBaudRate)

newBaudRate=Console.ReadLine()

IfnewBaudRate="

newBaudRate=defaultPortBaudRate.ToString()

ReturnInteger.Parse(newBaudRate)

PublicSharedFunctionSetPortParity(ByValdefaultPortParityAsParity)AsParity

DimnewParityAsString

AvailableParityoptions:

ForEachsIn[Enum].GetNames(GetType(Parity))

Parity({0}):

defaultPortParity.ToString())

newparity=Console.ReadLine()

Ifnewparity="

newparity=defaultPortParity.ToString()

ReturnCType([Enum].Parse(GetType(Parity),newParity),Parity)

PublicSharedFunctionSetPortDataBits(ByValdefaultPortDataBitsAsInteger)AsInteger

DimnewDataBitsAsString

DataBits({0}):

defaultPortDataBits)

newDataBits=Console.ReadLine()

IfnewDataBits="

newDataBits=defaultPortDataBits.ToString()

ReturnInteger.Parse(newDataBits)

PublicSharedFunctionSetPortStopBits(ByValdefaultPortStopBitsAsStopBits)AsStopBits

DimnewStopBitsAsString

AvailableStopBitsoptions:

ForEachsIn[Enum].GetNames(GetType(StopBits))

StopBits({0}):

defaultPortStopBits.ToString())

newStopBits=Console.ReadLine()

IfnewStopBits="

newStopBits=defaultPortStopBits.ToString()

ReturnCType([Enum].Parse(GetType(StopBits),newStopBits),StopBits)

PublicSharedFunctionSetPortHandshake(ByValdefaultPortHandshakeAsHandshake)AsHandshake

DimnewHandshakeAsString

AvailableHandshakeoptions:

ForEachsIn[Enum].GetNames(GetType(Handshake))

defaultPortHandshake.ToString())

newHandshake=Console.ReadLine()

IfnewHandshake="

newHandshake=defaultPortHandshake.ToString()

ReturnCType([Enum].Parse(GetTyp

展开阅读全文
相关资源
猜你喜欢
相关搜索

当前位置:首页 > 高等教育 > 医学

copyright@ 2008-2022 冰豆网网站版权所有

经营许可证编号:鄂ICP备2022015515号-1