在VB中利用API进行串口通信

本文转自http://blog.csdn.net/lyserver/article/details/4153335

‘* ******************************************************* *
‘*    程序名称:basComm.bas
‘*    程序功能:在VB中利用API进行串口通信
‘*    作者:lyserver
‘*    联系方式:http://blog.csdn.net/lyserver
‘* ******************************************************* *
Option Explicit
Option Base 0
Private Declare Function CreateFile Lib "kernel32" Alias "CreateFileA" (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
Private Declare Function ReadFile Lib "kernel32" (ByVal hFile As Long, lpBuffer As Any, ByVal nNumberOfBytesToRead As Long, lpNumberOfBytesRead As Long, ByVal lpOverlapped As Long) As Long
Private Declare Function WriteFile Lib "kernel32" (ByVal hFile As Long, lpBuffer As Any, ByVal nNumberOfBytesToWrite As Long, lpNumberOfBytesWritten As Long, ByVal lpOverlapped As Long) As Long
Private Declare Function CloseHandle Lib "kernel32" (ByVal hObject As Long) As Long
Private Const GENERIC_READ = &H80000000
Private Const GENERIC_WRITE = &H40000000
Private Const OPEN_EXISTING = 3
Private Const INVALID_HANDLE_VALUE = -1

Private Declare Function GetCommState Lib "kernel32" (ByVal nCid As Long, lpDCB As DCB) As Long
Private Declare Function SetCommState Lib "kernel32" (ByVal hCommDev As Long, lpDCB As DCB) As Long
Private Declare Function SetCommTimeouts Lib "kernel32" (ByVal hFile As Long, lpCommTimeouts As COMMTIMEOUTS) As Long
Private Declare Function SetupComm Lib "kernel32" (ByVal hFile As Long, ByVal dwInQueue As Long, ByVal dwOutQueue As Long) As Long
Private Declare Function PurgeComm Lib "kernel32" (ByVal hFile As Long, ByVal dwFlags As Long) As Long
Private Const PURGE_TXABORT = &H1     ‘  Kill the pending/current writes to the comm port.
Private Const PURGE_RXABORT = &H2     ‘  Kill the pending/current reads to the comm port.
Private Const PURGE_TXCLEAR = &H4     ‘  Kill the transmit queue if there.
Private Const PURGE_RXCLEAR = &H8     ‘  Kill the typeahead buffer if there.
Private Type DCB
        DCBlength As Long
        BaudRate As Long
        fBitFields As Long ‘See Comments in Win32API.Txt
        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
        EOFChar As Byte
        EvtChar As Byte
        wReserved1 As Integer ‘Reserved; Do Not Use
End Type
Private Type COMMTIMEOUTS
        ReadIntervalTimeout As Long
        ReadTotalTimeoutMultiplier As Long
        ReadTotalTimeoutConstant As Long
        WriteTotalTimeoutMultiplier As Long
        WriteTotalTimeoutConstant As Long
End Type

Private Declare Function SafeArrayGetDim Lib "oleaut32.dll" (ByRef saArray() As Any) As Long

‘串口操作演示
Sub Main()
    Dim hComm As Long
    Dim szTest As String
   
    ‘打开串口1
    hComm = OpenComm(1)
   
    If hComm <> 0 Then
        ‘设置串口通讯参数
        SetCommParam hComm
       
        ‘设置串口超时
        SetCommTimeOut hComm, 2, 3
       
        ‘向串口写入字符串123
        szTest = "123"
        WriteComm hComm, StringToBytes(szTest)
       
        ‘读串口
        szTest = BytesToString(ReadComm(hComm))
        Debug.Print szTest
       
        ‘关闭串口
        CloseComm hComm
    End If
End Sub

‘打开串口
Function OpenComm(ByVal lComPort As Long) As Long
    Dim hComm As Long
   
    hComm = CreateFile("COM" & lComPort, GENERIC_READ Or GENERIC_WRITE, 0, 0, OPEN_EXISTING, 0, 0)
    If hComm = INVALID_HANDLE_VALUE Then
        OpenComm = 0
    Else
        OpenComm = hComm
    End If
End Function

‘关闭串口
Sub CloseComm(hComm As Long)
    CloseHandle hComm
    hComm = 0
End Sub

‘读串口
Function ReadComm(ByVal hComm As Long) As Byte()
    Dim dwBytesRead As Long
    Dim BytesBuffer() As Byte
   
    ReDim BytesBuffer(4095)
    ReadFile hComm, BytesBuffer(0), UBound(BytesBuffer) + 1, dwBytesRead, 0
    If dwBytesRead > 0 Then
        ReDim Preserve BytesBuffer(dwBytesRead)
        ReadComm = BytesBuffer
    End If
End Function

‘写串口
Function WriteComm(ByVal hComm As Long, BytesBuffer() As Byte) As Long
    Dim dwBytesWrite
   
    If SafeArrayGetDim(BytesBuffer) = 0 Then Exit Function
    WriteFile hComm, BytesBuffer(0), UBound(BytesBuffer) + 1, dwBytesWrite, 0
    WriteComm = dwBytesWrite
End Function

‘设置串口通讯参数
Function SetCommParam(ByVal hComm As Long, Optional ByVal lBaudRate As Long = 9600, _
        Optional ByVal cByteSize As Byte = 8, Optional ByVal cStopBits As Byte = 0, _
        Optional ByVal cParity As Byte = 0, Optional ByVal cEOFChar As Long = 26) As Boolean
       
    Dim dc As DCB
    If hComm = 0 Then Exit Function
   
    If GetCommState(hComm, dc) Then
        dc.BaudRate = lBaudRate
        dc.ByteSize = cByteSize
        dc.StopBits = cStopBits
        dc.Parity = cParity
        dc.EOFChar = cEOFChar
       
        SetCommParam = CBool(SetCommState(hComm, dc))
    End If
End Function

‘设置串口超时
Function SetCommTimeOut(ByVal hComm As Long, Optional ByVal dwReadTimeOut As Long = 2, _
        Optional ByVal dwWriteTimeOut As Long = 3) As Boolean
       
    Dim ct As COMMTIMEOUTS
    If hComm = 0 Then Exit Function
   
    ct.ReadIntervalTimeout = dwReadTimeOut ‘读操作时,字符间超时
    ct.ReadTotalTimeoutMultiplier = dwReadTimeOut ‘读操作时,每字节超时
    ct.ReadTotalTimeoutConstant = dwReadTimeOut ‘读操作时,固定超时(总超时=每字节超时*字节数+固定超时)
    ct.WriteTotalTimeoutMultiplier = dwWriteTimeOut ‘写操作时,每字节超时
    ct.WriteTotalTimeoutConstant = dwWriteTimeOut ‘写操作时,固定超时(总超时=每字节超时*字节数+固定超时)
   
    SetCommTimeOut = CBool(SetCommTimeouts(hComm, ct))
End Function

‘设置串口读写缓冲区大小
Function SetCommBuffer(ByVal hComm As Long, Optional ByVal dwBytesRead As Long = 1024, _
        Optional ByVal dwBytesWrite As Long = 512) As Boolean
   
    If hComm = 0 Then Exit Function
    SetCommBuffer = CBool(SetupComm(hComm, dwBytesRead, dwBytesWrite))
End Function

‘清空串口缓冲区
Sub ClearComm(ByVal hComm As Long, Optional ByVal InBuffer As Boolean = True, Optional ByVal OutBuffer As Boolean = True)
    If hComm = 0 Then Exit Sub
    If InBuffer And OutBuffer Then ‘清空输入输出缓冲区
        PurgeComm hComm, PURGE_TXABORT Or PURGE_RXABORT Or PURGE_TXCLEAR Or PURGE_RXCLEAR
    ElseIf InBuffer Then ‘清空输入缓冲区
        PurgeComm hComm, PURGE_RXABORT Or PURGE_RXCLEAR
    ElseIf OutBuffer Then ‘清空输出缓冲区
        PurgeComm hComm, PURGE_TXABORT Or PURGE_TXCLEAR
    End If
End Sub

‘辅助函数:BSTR字符串转换为CHAR字符串
Function StringToBytes(ByVal szText As String) As Byte()
    If Len(szText) > 0 Then
        StringToBytes = StrConv(szText, vbFromUnicode)
    End If
End Function

‘辅助函数:CHAR字符串转换为BSTR字符串
Function BytesToString(bytesText() As Byte) As String
    If SafeArrayGetDim(bytesText) <> 0 Then
        BytesToString = StrConv(bytesText, vbUnicode)
    End If
End Function

‘辅助函数:获得CHAR字符串长度
Function Byteslen(bytesText() As Byte) As Long
    If SafeArrayGetDim(bytesText) <> 0 Then
        Byteslen = UBound(bytesText) + 1
    End If
End Function

时间: 2024-08-09 19:08:17

在VB中利用API进行串口通信的相关文章

telosb中的Oscilloscope解析-串口通信

Oscilloscope的这个例子包括了PC与串口的接发送消息,很值得研究一番. 大体的思想是传感器节点采集数据,每采集十个数据发送一个数据包给另外一个Base节点,然后Base节点把数据转发给PC端.PC端有一个java程序收集数据并且显示.所以运行这个例子要两个节点,一个烧录Oscilloscope,一个烧录Base节点,还需要一台PC,连接Base节点,运行java程序.但是在运行java程序之前要启动SerialForward工具,这样PC和Base节点才能通信.具体命令不详细描述. 在

使用win32 API 实现串口通信 (二)

通常对于串口通信协议规定,有命令帧与应答帧. 1.协议规定,如头+命令字+数据块长度+数据块+校验. 对于协议规定的具体帧,可以为每一个帧,建立一个结构体数据,用于存储我将要接收的数据,这样我们可以事先建立多个结构体,通常大概会建立10到50不等,这与通信的数据协议有关. 2.现在我们要考虑的是如何将一个完整的数据帧去掉头.命令字.校验,存入结构体中,以便我们可以直接使用结构体中数据成员,也方便使用.通常C++的做法是使用运算符重载进行复制,将一个我们接收到buffer数据帧,复制到结构体中.

串口通信IN C++(适用于Microsoft Visual Studio 2010/2012/2013 ,VC++6.0 )

                 向无数拼命工作的 程序猿 及 攻城狮 致敬! 软硬件平台简介 CPU:P4 2G及以上兼容于80x86架构的中央处理器 内存:1G及以上 硬盘:80G及以上 网卡:100M及以上 操作系统:Windows XP及以上 软件:VS2010/2012/2013  Visual C++ 6.0  Keil uVision3-4   STC_ISP_V488/友善串口助手 硬件:众多.不胜数 2.总体设计思想 串口通讯把数据的字节分解成单个的二进制比特流依次传输,其

Qt实现串口通信总结

注意: Qt5发布之前,Qt实现串口通信一般是采用第三方类库qextserialport.Qt5发布后自带了QtSerialPort 能够支持串口通信. 1.Qextserialport类介绍 在Qt5之前的版本中并没有特定的串口控制类,现在大部分人使用的是第三方写的qextserialport类,本文章主要是讲解怎样利用此类实现串口通信. 2.文件下载地址: http://sourceforge.net/projects/qextserialport/files/ 3.文件内容:     3.

串口通信(基础)

参考文章:http://www.cnblogs.com/aierong/archive/2009/08/21/1551589.html http://www.cnblogs.com/procoder/archive/2009/04/07/1430871.html http://blog.csdn.net/cy757/article/details/4474930 SerialPort Class Windows 7 虚拟串口 VSPD 6 最近总结了串口(COM)读写操作的三种方式:第1种方式是

AIR串口通信

最近公司的项目中需要用到串口通信,项目是用基于AIR的,AIR本身是不支持串口通信的,本想用 c#或java另写一个负责串口通信的模块,又感觉很烦不想那么弄,就想到了ANE.可惜以前也没弄过 ANE,现研究也感觉麻烦,主要也是因为自己很懒就想在网上找看看有没有现成的ANE,结果还真找到了. 废话说的有点多. 先放上 ANE地址 http://code.google.com/p/as3-arduino-connector/ 虽然是老外写的,但是用起来还是挺容易挺方便的. //-----------

SPCOMM控件在Delphi串口通信中的应用

SPCOMM控件在Delphi串口通信中的应用 2010-07-08 22:20:31|  分类: 个人日记 |举报 |字号 订阅 2009-03-01 05:35 摘要:利用Delphi开发工业控制系统软件成为越来越多的开发人员的选择,而串口通信是这个过程中必须解决的问题之一.本文在对几种常用串口通信方法分析比较的基础上,着重讨论了Delphi开发环境下利用Spcomm控件实现PC机与单片机之间串口通信的方法,研究了Spcomm串口通信的关键技术问题,并通过一个实例给出了Spcomm控件在De

VC中利用多线程技术实现线程之间的通信

文章来源:[url]http://www.programfan.com/article/showarticle.asp?id=2951[/url] 当前流行的Windows操作系统能同时运行几个程序(独立运行的程序又称之为进程),对于同一个程序,它又可以分成若干个独立的执行流,我们称之为线程,线程提供了多任务处理的能力.用进程和线程的观点来研究软件是当今普遍采用的方法,进程和线程的概念的出现,对提高软件的并行性有着重要的意义.现在的大型应用软件无一不是多线程多任务处理,单线程的软件是不可想象的.

引用kernel32.dll中的API来进行串口通讯

串口通讯可以引出kernel32.dll中的API来操作,相关源码如下:using System;using System.Runtime.InteropServices; namespace Telehome.GSM{/// <summary>/// ************************************************************************************/// /// Function: 连接,断开串口;发送,接收串口数据,使用