【VB开源代码栏目提醒】:网学会员--在 VB开源代码编辑为广大网友搜集整理了:vb串口 - 讲义教程绩等信息,祝愿广大网友取得需要的信息,参考学习。
第第66章章 VVBB串串口口通通信信程程序序设设计计典典型型实实例例 利用
VB开发串口通信程序既可以使用MSComm控件也可以调用Windows API函数实现。
不过只要MSComm控件可以被选用我们推荐选择此控件实现因为MSComm控件的功能和API调用一样强甚至比它还好且使用起来更加简单。
在本章提供的串口通信程序设计中除了PC与PC串口通信外PC与单片机、PC与智能仪表、PC与PLC、PC与GSM短信模块等串口通信任务的实现均采用MSComm控件。
6.1 PC与PC串口通信程序设计 当两台串口设备通信距离较近时可以直接连接最简单的情况在通信中只需3根线发送线、接收线、信号地线便可实现全双工异步串行通信。
本设计通过两台PC串口3线连接介绍了利用API函数和MSComm控件设计串口通信程序的方法包括字符与文件的发送与接收。
6.1.1 PC与PC串口通信程序设计目的 1掌握PC与PC串口通信的线路连接方法。
2利用MSComm控件和API函数实现PC与PC串口通信的程序设计方法。
6.1.2 PC与PC串口通信程序设计用软、硬件 本设计用到的硬件和
软件清单如表6-1所示。
表6-1 设计用软、硬件 序 号 名 称 数 量 1 PC或IPC 2 2 串口通信线三线制 1 3 Visual Basic 6.0 1 6.1.3 PC与PC串口通信程序硬件线路图 线路说明在计算机通电前按图6-1所示将两台PC通过串口线连接起来计算机A串口COM1端口的TXD与计算机B串口COM1端口的RXD相连计算机A串口COM1端口的RXD与计算机B串口COM1端口的TXD相连计算机A串口COM1端口的GND与计算机B串口COM1端口的GND相连。
第6章
VB串口通信程序设计典型实例 – 173 – COM1PC机AGNDRXDTXDCOM1PC机BGNDRXDTXD 图6-1 PC与PC串口通信线路 6.1.4 设计任务 利用MSComm控件和
VB API函数编写程序实现PC与PC串口通信。
任务要求两台计算机互发字符并自动接收如一台
计算机输入字符串“Please return abc123”单击“发送字符”命令另一台计算机若收到就输入字符串“abc123”单击“发送字符”命令信息返回到第一组的计算机。
实际上就是编写一个简单的双机聊天程序。
6.1.5 任务实现 6.1.5.1 利用MSComm控件实现字符型数据发送与接收 1建立新工程
VB使用“工程”来管理每一个应用程序要使用的所有文件每建立一个新程序就要新建一个工程。
一个工程由窗体、标准模块、控件及应用所需的开发环境设置等组成。
运行
VB程序出现“新建工程”对话框选择“标准EXE”单击“打开”命令按钮进入
VB工程集成开发环境窗体设计器中自动出现一个名为Form1的空白窗体。
2程序界面设计 向空白窗体添加各种控件以完成预定的各种功能。
开始一个项目的设计时
VB的工具箱中会有许多默认的控件让
设计者予以选用这些原本就出现在工具箱中的控件是内置控件它提供了一些基本的系统设计组件给设计者但功能比较特别的控件就不会出现在其中如用来设计串口通信功能的控件MSComm就不在其中。
1添加串口通信控件MSComm。
由于
VB的串行通信组件并不会主动出现在工具箱里中当我们需要MSComm控件时首先要把它加入到工具箱中。
让MSComm控件出现在工具箱中的步骤如下。
选择“工程”菜单下的“部件…”子菜单在弹出的“部件”对话框中在“控件”选项卡属性中选中“Microsoft Comm Control 6.0”复选框单击“确定”按钮后在工具箱中就出现了一个形似“电话”的图标它就是MSComm控件。
计算机A 计算机B Visual Basic数据采集与串口通信测控应用实战 – 174 – 工具箱中有了MSComm控件就可以选择MSComm控件的图标后将其添加到程序窗体上利用该控件编程PC就可以通过
VB实现与串口设备的串口
通信了。
由于每个使用的MSComm控件对应着一个串行端口如果应用程序需要访问多个串行端口必须添加多个MSComm控件。
2为了实现连续的自动接收将工具箱中的Timer控件添加到程序窗体上。
3添加两个文本框控件Text1 和Text2用于输入要发送的字符和显示要接收的字符。
4添加两个标签控件Label1和Label2作为发送和接收字符区的标签。
5添加一个按钮控件Command1执行发送字符命令。
程序设计界面如图6-2所示。
3属性设置 从属性窗口设置属性时只需从对象列表框中选择待设置属性的对象然后从属性
列表的左列选择属性最后在属性列表的右列中输入或选择新的属性值。
程序窗体、控件对象的主要属性设置如表6-2所示。
表6-2 窗体、控件对象的主要属性设置 控 件 类 型 主 要 属 性 功 能 Form 名称 COMForm 窗体控件 BorderStyle 3 运行时窗体固定大小 Caption PC与PC串口通信 窗体标题栏显示程序名称 Label 名称 Label1 标签控件 Caption 显示接收字符区 标签文本 Label 名称 Label2 标签控件 Caption 输入发送字符区 标签文本 TextBox 名称 Textsend 文本框控件 MultiLine True 允许多行显示 ScrollBars 2-Vertical 垂直滚动条可用 TextBox 名称 TextReceive 文本框控件 MultiLine True 允许多行显示 ScrollBars 2-Vertical 垂直滚动条可用 CommandButton 名称 Cmdsend 按钮控件 Caption 发送字符 手动发送字符 MSComm 名称 MSComm1 串口通信控件 其他属性在程序中设置 Timer 名称 Timer1 时钟控件 Enabled True 时钟初始可用 Interval 500 设置发送周期ms 图6-2 程序窗体界面 第6章
VB串口通信程序设计典型实例 – 175 – 两台计算机中
VB程序界面及属性设置应完全相同尤其MSComm控件的InputMode和Settings属性值应相同。
4程序
代码设计 程序要实现自动发送或读取在
VB程序中有两个方式可以达到一是查询方式利用
查询事件是否发生当发生时去执行默认的程序
代码。
可以使用计时器控件Timer该控件属性中的Interval可以控制计时器被启动的时间间隔当时间间隔一到便会执行原先放在计时器中的程序
代码。
下面是利用查询方式编写的PC与PC串口通信的参考
程序代码如下所示 串口初始化 Private Sub Form_Load MSComm1.CommPort 1 设置通信端口号为COM1 MSComm1.Settings quot9600n81quot 设置串口1参数 MSComm1.InputMode 0 接收文本型数据 MSComm1.PortOpen True 打开通信端口1 End Sub 把字符通过串口发送出去 Private Sub Cmdsend_Click If Textsend.Text quotquot Then pp MsgBoxquot发送的数据不能为空quot 16 Exit Sub End If MSComm1.Output TrimTextsend.Text For i 1 To 20000000 Next i End Sub 通过时钟控制来自动接收字符 Private Sub Timer1_Timer Dim buf buf TrimMSComm1.Input 将缓冲区内的数据读入buf变量中 If Lenbuf ltgt 0 Then 判断缓冲区内是否存在数据 TextReceive.Text TextReceive.Text Chr13 Chr10 buf //回车换行 End If End Sub 关闭通信端口停止程序运行 Private Sub Cmdquit_Click MSComm1.PortOpen False Unload Me End Sub 在Windows系统环境下串口是系统资源的一部分。
应用程序要使用串口进行通信必须在使用之前向操作
系统提出资源申请要求打开串口通信完成后必须释放资源关闭串口。
在Windows系统的系统函数中均包含了支持通信中断的功能。
二是使用事件方式。
MSComm控件提供事件回应功能可以利用此功能达到自动发送/接收的目的。
下面是利用事件方式编写的PC与PC串口通信的参考程序界面设计与图6-2基本相同区别是事件方式不需要时间控件。
串口初始化 Private Sub Form_Load MSComm1.CommPort 1 设置通信端口号为COM1 Visual Basic数据采集与串口通信测控应用实战 – 176 – MSComm1.Settings quot9600n81quot 设置串口参数 MSComm1.InputMode 0 接收文本型数据 MSComm1.RThreshold 1 接收缓冲区每收到一个字符都会使 MSComm 控件触发OnComm 事件 MSComm1.PortOpen True 打开通信端口1 End Sub 把字符通过串口发送出去 启动定时器 Private Sub Cmdsend_Click If Textsend.Text quotquot Then pp MsgBoxquot发送的数据不能为空quot 16 Exit Sub End If MSComm1.Output TrimTextsend.Text End Sub MSComm 的 OnComm 由 CommEvent 属性值的不同将各自的程序
代码写入相关的子程序中 只要 RThresold 中的设定字符数到达时便会使得 CommEvent 属性值变成 comEvReceive 因此接收的子程序便会被执行 Private Sub MSComm1_OnComm Dim buf Select Case MSComm1.CommEvent 通过取代每一个 case 表达式来处理每个事件与错误 Case comEvCD CD 线的状态发生变化 Case comEvCTS CTS 线的状态发生变化 Case comEvDSR DSR 线的状态发生变化 Case comEvReceive buf TrimMSComm1.Input 将缓冲区内的数据读入buf变量中 Case comEvSend End Select TextReceive.Text TextReceive.Text amp buf End Sub 停止程序运行 Private Sub Cmdquit_Click Unload Me End Sub 关闭通信端口 Private Sub Form_UnloadCancel As Integer MSComm1.PortOpen False End Sub 5运行程序 程序设计、调试完毕单击工具栏快捷按钮“启动”运行程序。
两台计算机同时运行本程序。
首先在一台计算机程序窗体中发送字符区输入要发送的字符如“我是第一组收到请回话”单击“发送字符”按钮发送区的字符串通过COM1口发送出去。
如果联网通信的另一台计算机程序收到字符则返回字符串如“收到我是第2组”如果通信正常该字符串将显示在接收区中。
程序运行界面如图6-3所示。
第6章
VB串口通信程序设计典型实例 – 177 – 图6-3 程序运行界面 6.1.5.2 利用API函数实现字符型数据发送与接收 1建立新工程 运行
VB创建标准的工程项目文件设计程序窗体。
① 添加两个TextBox控件用于输入要发送的字符和显示需接收的字符。
② 添加两个Label控件作为发送和接收字符区的标签。
③ 添加一个Timer控件用于周期性地读取串口数据。
④ 添加两个CommandButton控件分别执行发送字符、关闭程序等命令。
设计的程序界面如图6-4所示。
2属性设置 程序窗体、控件对象的主要属性设置如表6-3所示。
表6-3 窗体、控件对象的主要属性设置 控 件 类 型 名 称 主 要 属 性 功 能 Form COMForm BorderStyle 3 运行时窗体固定大小 Caption API串口通讯 窗体标题栏显示程序名称 Label Label1 Caption 发送数据区 标签 Label Label2 Caption 接收数据区 标签 TextBox Textsend MultiLine True 允许多行显示 ScrollBars 2-Vertical 垂直滚动条可用 TextBox TextReceive MultiLine True 允许多行显示 ScrollBars 2-Vertical 垂直滚动条可用 CommandButton BTNSend Caption 发送数据 手动间断发送字符 CommandButton BTNCloseCom Caption 关闭程序 关闭程序 Timer TMRComm Interval 500 设置发送周期ms 图6-4 程序窗体界面 Visual Basic数据采集与串口通信测控应用实战 – 178 – 3程序
代码设计 在程序标准模块SerialPort.bas的说明部分放置使用的API函数声明及所用的结构、常数的声明 Option Explicit Global ComNum As Long Global bRead255 As Byte Type COMSTAT fCtsHold As Long fDsrHold As Long fRlsdHold As Long fXoffHold As Long fXoffSent As Long fEof As Long fTxim As Long fReserved As Long cbInQue As Long cbOutQue As Long End Type Type COMMTIMEOUTS ReadIntervalTimeout As Long ReadTotalTimeoutMultiplier As Long ReadTotalTimeoutConstant As Long WriteTotalTimeoutMultiplier As Long WriteTotalTimeoutConstant As Long End Type Type DCB DCBlength As Long BaudRate As Long fBinary As Long fParity As Long fOutxCtsFlow As Long fOutxDsrFlow As Long fDtrControl As Long fDsrSensitivity As Long fTXContinueOnXoff As Long fOutX As Long fInX As Long fErrorChar As Long fNull As Long fRtsControl As Long fAbortOnError As Long fDummy2 As Long wReserved As Integer XonLim As Integer XoffLim As Integer ByteSize As Byte Parity As Byte StopBits As Byte XonChar As Byte XoffChar As Byte ErrorChar As Byte 第6章
VB串口通信程序设计典型实例 – 179 – EofChar As Byte EvtChar As Byte End Type Type OVERLAPPED Internal As Long InternalHigh As Long offset As Long OffsetHigh As Long hEvent As Long End Type Type SECURITY_ATTRIBUTES nLength As Long lpSecurityDescriptor As Long bInheritHandle As Long End Type Declare Function CloseHandle Lib quotkernel32quot ByVal hObject As Long As Long Declare Function GetLastError Lib quotkernel32quot As Long Declare Function ReadFile Lib quotkernel32quot ByVal hFile As Long lpBuffer As Any ByVal nNumberOfBytesToRead As Long lpNumberOfBytesRead As Long lpOverlapped As Long As Long Declare Function WriteFile Lib quotkernel32quot ByVal hFile As Long lpBuffer As Any ByVal nNumberOfBytesToWrite As Long lpNumberOfBytesWritten As Long lpOverlapped As Long As Long Declare Function SetCommTimeouts Lib quotkernel32quot ByVal hFile As Long lpCommTimeouts As COMMTIMEOUTS As Long Declare Function GetCommTimeouts Lib quotkernel32quot ByVal hFile As Long lpCommTimeouts As COMMTIMEOUTS As Long Declare Function BuildCommDCB Lib quotkernel32quot Alias quotBuildCommDCBAquot ByVal lpDef As String lpDCB As DCB As Long Declare Function SetCommState Lib quotkernel32quot ByVal hCommDev As Long lpDCB As DCB As Long Declare Function CreateFile Lib quotkernel32quot Alias quotCreateFileAquot ByVal lpFileName As String ByVal dwDesiredAccess As Long ByVal dwShareMode As Long ByVal lpSecurityAttributes As Long ByVal dwCreationDisposition As Long ByVal dwFlagsAndAttributes As Long ByVal hTemplateFile As Long As Long Declare Function FlushFileBuffers Lib quotkernel32quot ByVal hFile As Long As Long 窗体模块程序如下 初始化串口 Private Sub Form_Load If Not Init_ComquotCOM1:quot quot9600n81quot Then MsgBox quot端口quot amp quot 无效quot Exit Sub End If End Sub 发送字符 Private Sub BTNSend_Click If WriteCOM32txt2 amp vbCr ltgt Lentxt2 Then MsgBox quot写入错误quot Exit Sub End If End Sub 向串口写数据 Function WriteCOM32COMString As String As Integer On Error GoTo handelwritelpt Dim RetBytes As Long LenVal As Long Dim retval As Long Visual Basic数据采集与串口通信测控应用实战 – 180 – If LenCOMString gt 255 Then WriteCOM32 LeftCOMString 255 WriteCOM32 RightCOMString LenCOMString - 255 Exit Function End If For LenVal 0 To LenCOMString - 1 bReadLenVal AscMidCOMString LenVal 1 1 Next LenVal retval WriteFileComNum bRead0 LenCOMString RetBytes 0 WriteCOM32 RetBytes handelwritelpt: Exit Function End Function 读取数据 Private Sub TMRComm_Timer Dim Ans As String i As Integer RtnStr As String Ans ReadCommPure If Ans quotquot Then Exit Sub RtnStr RtnStr amp CleanStrAns txtRec.Text RtnStr FlushComm End Sub 从串口读取数据 Function ReadCommPure As String On Error GoTo handelpurecom Dim RetBytes As Long i As Integer ReadStr As String retval As Long Dim CheckTotal As Integer CheckDigitLC As Integer retval ReadFileComNum bRead0 255 RetBytes 0 ReadStr quotquot If RetBytes gt 0 Then For i 0 To RetBytes - 1 ReadStr ReadStr amp ChrbReadi Next i Else FlushComm End If ReadCommPure ReadStr handelpurecom: Exit Function End Function Function CleanStrTextLine As String As String Dim i As Integer RtnStr As String RtnStr quotquot For i 1 To LenTextLine Select Case AscMidTextLine i 1 Case ampH5D RtnStr RtnStr amp quotltACKgtquot Case ampH5B RtnStr RtnStr amp quotltNAKgtquot Case Is gt ampH30 RtnStr RtnStr amp MidTextLine i 1 Case 13 第6章
VB串口通信程序设计典型实例 – 181 – RtnStr RtnStr amp quotltCRgtquot Case 10 RtnStr RtnStr amp quotltLFgtquot Case Else RtnStr RtnStr amp quotquot End Select Next i CleanStr RtnStr End Function 清空文件缓冲区 Function FlushComm FlushFileBuffers ComNum End Function 初始化端口 Function Init_ComComNumber As String Comsettings As String As Boolean On Error GoTo handelinitcom Dim ComSetup As DCB Answer Stat As COMSTAT RetBytes As Long Dim retval As Long Dim CtimeOut As COMMTIMEOUTS BarDCB As DCB 打开通讯口读/写ampHC0000000. 必须指定存在的文件 3. ComNum CreateFileComNumber ampHC0000000 0 0amp ampH3 0 0 If ComNum -1 Then MsgBox quot端口 quot amp ComNumber amp quot无效. 请设置正确.quot 48 Init_Com False Exit Function End If 超时 CtimeOut.ReadIntervalTimeout 20 CtimeOut.ReadTotalTimeoutConstant 1 CtimeOut.ReadTotalTimeoutMultiplier 1 CtimeOut.WriteTotalTimeoutConstant 10 CtimeOut.WriteTotalTimeoutMultiplier 1 retval SetCommTimeoutsComNum CtimeOut If retval -1 Then retval GetLastError MsgBox quot端口超时设定无效 quot amp ComNumber amp quot 错误: quot amp retval retval CloseHandleComNum Init_Com False Exit Function End If retval BuildCommDCBComsettings BarDCB If retval -1 Then retval GetLastError MsgBox quot无效设备 DCB 块 quot amp Comsettings amp quot 错误: quot amp retval retval CloseHandleComNum Init_Com False Exit Function End If retval SetCommStateComNum BarDCB If retval -1 Then retval GetLastError Visual Basic数据采集与串口通信测控应用实战 – 182 – MsgBox quot无效设备 DCB 块 quot amp Comsettings amp quot 错误: quot amp retval retval CloseHandleComNum Init_Com False Exit Function End If Init_Com True handelinitcom: Exit Function End Function 关闭程序 Private Sub BTNCloseCom_Click Unload Me End Sub 关闭端口 Private Sub Form_UnloadCancel As Integer CloseHandle ComNum .