StopBitsVBA 中使用 API 串口通信 Serial Port (英文)

declare_serial  时间:2021-02-14  阅读:()

'

-------------------------------------------------------------------------------

'

' This VB module is a collection of routines to perform serial port I/O without' using the Microsoft Comm Control component. This module uses the Windows API' to perform the overlapped I/O operations necessary for serial communications.'

' The routine can handle up to 4 serial ports which are identified with a

' Port ID.

'

'All routines (with the exception of CommRead and CommWrite) return an error' code or 0 if no error occurs. The routine CommGetError can be used to get' the complete error message.

'

-------------------------------------------------------------------------------

'

-------------------------------------------------------------------------------

' Public Constants

'

-------------------------------------------------------------------------------

'Output Control Lines (CommSetLine)

Const LINE_BREAK= 1

Const LINE_DTR= 2

Const LINE_RTS = 3

' Input Control Lines (CommGetLine)

Const LINE_CTS =&H10&

Const LINE_DSR=&H20&

Const LINE_RING=&H40&

Const LINE_RLSD=&H80&

Const LINE_CD=&H80&

'

-------------------------------------------------------------------------------

' System Constants

'

-------------------------------------------------------------------------------

Private Const ERROR_IO_INCOMPLETE = 996&

Private Const ERROR_IO_PENDING= 997

Private Const GENERIC_READ=&H80000000

Private Const GENERIC_WRITE=&H40000000

Private Const FILE_ATTRIBUTE_NORMAL =&H80

Private Const FILE_FLAG_OVERLAPPED=&H40000000

Private Const FORMAT_MESSAGE_FROM_SYSTEM=&H1000

Private Const OPEN_EXISTING= 3

' COMM Functions

Private Const MS_CTS_ON=&H10&

Private Const MS_DSR_ON=&H20&

Private Const MS_RING_ON=&H40&

Private Const MS_RLSD_ON=&H80&

Private Const PURGE_RXABORT =&H2

Private Const PURGE_RXCLEAR=&H8

Private Const PURGE_TXABORT =&H1

Private Const PURGE_TXCLEAR=&H4

' COMM Escape Functions

Private Const CLRBREAK= 9

Private Const CLRDTR= 6

Private Const CLRRTS = 4

Private Const SETBREAK= 8

Private Const SETDTR= 5

Private Const SETRTS = 3

'

-------------------------------------------------------------------------------

' System Structures

'

-------------------------------------------------------------------------------

Private Type COMSTATfBitFields As Long ' See Comment in Win32API.TxtcbInQue As LongcbOutQue As Long

End Type

Private Type COMMTIMEOUTS

ReadIntervalTimeout As Long

ReadTotalTimeoutMultiplier As Long

ReadTotalTimeoutConstant As Long

WriteTotalTimeoutMultiplier As Long

WriteTotalTimeoutConstant As Long

End Type

'

' The DCB structure defines the control setting for a serial

' communications device.

'

Private Type DCB

DCBlength As Long

BaudRate As LongfBitFields As Long ' See Comments in Win32API.TxtwReserved 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 BytewReserved1 As Integer 'Reserved;Do Not Use

End Type

Private Type OVERLAPPED

Internal As Long

InternalHigh As Longoffset As Long

OffsetHigh As LonghEvent As Long

End Type

Private Type SECURITY_ATTRIBUTESnLength As LonglpSecurityDescriptor As LongbInheritHandle As Long

End Type

'

-------------------------------------------------------------------------------

' System Functions

'

-------------------------------------------------------------------------------

'

' Fills a specified DCB structure with values specified in

' a device-control string.

'

Private Declare Function BuildCommDCB Lib "kernel32"Alias "BuildCommDCBA"

_

(ByVal lpDef As String, lpDCB As DCB)As Long

'

'Retrieves information about a communications error and reports

' the current status of a communications device. The function is

' called when a communications error occurs, and it clears the

' device's error flag to enable additional input and output

' (I/O) operations.

'

Private Declare Function ClearCommError Lib "kernel32" _

(ByVal hFile As Long, lpErrors As Long, lpStat As COMSTAT)As Long

'

' Closes an open communications device or file handle.

'

Private Declare Function CloseHandle Lib "kernel32" (ByVal hObject As Long)As Long'

' Creates or opens a communications resource and returns a handle

' that can be used to access the resource.

'

Private Declare Function CreateFile Lib "kernel32"Alias "CreateFileA" _

(ByVal lpFileName As String,ByVal dwDesiredAccess As Long, _

ByVal dwShareMode As Long, lpSecurityAttributes As Any, _

ByVal dwCreationDisposition As Long,ByVal dwFlagsAndAttributes As Long, _

ByVal hTemplateFile As Long)As Long

'

'Directs a specified communications device to perform a function.

'

Private Declare Function EscapeCommFunction Lib "kernel32" _

(ByVal nCid As Long,ByVal nFunc As Long)As Long

'

' by anoher function.

'

Private Declare Function FormatMessage Lib "kernel32"Alias "FormatMessageA" _(ByVal dwFlags As Long, lpSource As Any,ByVal dwMessageId As Long, _ByVal dwLanguageId As Long,ByVal lpBuffer As String,ByVal nSize As Long, _Arguments As Long)As Long

'

'Retrieves modem control-register values.

'

Private Declare Function GetCommModemStatus Lib "kernel32" _

(ByVal hFile As Long, lpModemStat As Long)As Long

'

'Retrieves the current control settings for a specified

' communications device.

'

Private Declare Function GetCommState Lib "kernel32" _

(ByVal nCid As Long, lpDCB As DCB)As Long

'

'Retrieves the calling thread's last-error code value.

'

Private Declare Function GetLastError Lib "kernel32" ()As Long

'

'Retrieves the results of an overlapped operation on the

' specified file, named pipe, or communications device.

'

Private Declare Function GetOverlappedResult Lib "kernel32" _

(ByVal hFile As Long, lpOverlapped As OVERLAPPED, _lpNumberOfBytesTransferred As Long,ByVal bWait As Long)As Long

'

'Discards all characters from the output or input buffer of a

' specified communications resource. It can also terminate

' pending read or write operations on the resource.

'

Private Declare Function PurgeComm Lib "kernel32" _

(ByVal hFile As Long,ByVal dwFlags As Long)As Long

'

'Reads data from a file, starting at the position indicated by the

' file pointer.After the read operation has been completed, the

' file pointer is adjusted by the number of bytes actually read,

' unless the file handle is created with the overlapped attribute.

' If the file handle is created for overlapped input and output

' (I/O), the application must adjust the position of the file pointer

' after the read operation.

'

Private Declare Function ReadFile Lib "kernel32" _

(ByVal hFile As Long,ByVal lpBuffer As String, _

ByVal nNumberOfBytesToRead As Long,ByRef lpNumberOfBytesRead As Long, _lpOverlapped As OVERLAPPED)As Long

'

' Configures a communications device according to the specifications

' in a device-control block (a DCB structure). The function

' reinitializes all hardware and control settings, but it does not

' empty output or input queues.

'

Private Declare Function SetCommState Lib "kernel32" _

(ByVal hCommDev As Long, lpDCB As DCB)As Long

'

' Sets the time-out parameters for all read and write operations on a

' specified communications device.

'

Private Declare Function SetCommTimeouts Lib "kernel32" _

(ByVal hFile As Long, lpCommTimeouts As COMMTIMEOUTS)As Long

'

' Initializes the communications parameters for a specified

' communications device.

'

Private Declare Function SetupComm Lib "kernel32" _

(ByVal hFile As Long,ByVal dwInQueue As Long,ByVal dwOutQueue As Long)As Long'

'Writes data to a file and is designed for both synchronous and a

' synchronous operation.The function starts writing data to the file

' at the position indicated by the file pointer.After the write

' operation has been completed, the file pointer is adjusted by the

' number of bytes actually written, except when the file is opened with

' FILE_FLAG_OVERLAPPED. If the file handle was created for overlapped

' input and output (I/O), the application must adjust the position of

' the file pointer after the write operation is finished.

'

Private Declare Function WriteFile Lib "kernel32" _

(ByVal hFile As Long,ByVal lpBuffer As String, _

ByVal nNumberOfBytesToWrite As Long, lpNumberOfBytesWritten As Long, _lpOverlapped As OVERLAPPED)As Long

Private Declare Sub AppSleep Lib "kernel32"Alias "Sleep" (ByVal dwMilliseconds As Long)'

-------------------------------------------------------------------------------

'

-------------------------------------------------------------------------------

Private Const MAX_PORTS = 4

'

-------------------------------------------------------------------------------

' Program Structures

'

-------------------------------------------------------------------------------

Private Type COMM_ERRORlngErrorCode As LongstrFunction As String

strErrorMessage As String

End Type

Private Type COMM_PORTlngHandle As LongblnPortOpen As BooleanudtDCB As DCB

End Type

'

-------------------------------------------------------------------------------

' Program Storage

'

-------------------------------------------------------------------------------

Private udtCommOverlap As OVERLAPPED

Private udtCommError As COMM_ERROR

Private udtPorts(1 To MAX_PORTS)As COMM_PORT

'

-------------------------------------------------------------------------------

'GetSystemMessage -Gets system error text for the specified error code.

'

-------------------------------------------------------------------------------

Public Function GetSystemMessage(lngErrorCode As Long)As String

Dim intPos As Integer

Dim strMessage As String, strMsgBuff As String * 256

Call FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, 0, lngErrorCode, 0, strMsgBuff,255, 0)intPos = InStr(1, strMsgBuff, vbNullChar)

If intPos > 0 ThenstrMessage = Trim$(Left$(strMsgBuff, intPos - 1))

ElsestrMessage = Trim$(strMsgBuff)

End If

GetSystemMessage = strMessage

End Function

Public Function PauseApp(PauseInSeconds As Long)

Call AppSleep(PauseInSeconds * 1000)

End Function

'

-------------------------------------------------------------------------------

' CommOpen -Opens/Initializes serial port.

'

'

' Parameters:

' intPortID - Port ID used when port was opened.

' strPort -COM port name. (COM1,COM2,COM3,COM4)

' strSettings -Communication settings.

' Example: "baud=9600 parity=N data=8 stop=1"

'

'Returns:

' Error Code - 0 =No Error.

'

'

-------------------------------------------------------------------------------

Public Function CommOpen(intPortID As Integer, strPort As String, _strSettings As String)As Long

Dim lngStatus As Long

Dim udtCommTimeOuts As COMMTIMEOUTS

On Error GoTo Routine_Error

' See if port already in use.

If udtPorts(intPortID).blnPortOpen ThenlngStatus = -1

With udtCommError

.lngErrorCode = lngStatus

.strFunction = "CommOpen"

.strErrorMessage = "Port in use."

End With

GoTo Routine_Exit

End If

'Open serial port.udtPorts(intPortID).lngHandle =CreateFile(strPort,GENERIC_READ Or _

GENERIC_WRITE, 0,ByVal 0&,OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0)If udtPorts(intPortID).lngHandle = -1 ThenlngStatus = SetCommError("CommOpen (CreateFile)")

GoTo Routine_Exit

End IfudtPorts(intPortID).blnPortOpen = True

' Setup device buffers (1K each).lngStatus = SetupComm(udtPorts(intPortID).lngHandle, 1024, 1024)

If lngStatus = 0 ThenlngStatus = SetCommError("CommOpen (SetupComm)")

GoTo Routine_Exit

End If

' Purge buffers.lngStatus = PurgeComm(udtPorts(intPortID).lngHandle, PURGE_TXABORT Or _

PURGE_RXABORT Or PURGE_TXCLEAR Or PURGE_RXCLEAR)

If lngStatus = 0 ThenlngStatus = SetCommError("CommOpen (PurgeComm)")

GoTo Routine_Exit

End If

' Set serial port timeouts.

With udtCommTimeOuts

.ReadIntervalTimeout = -1

.ReadTotalTimeoutMultiplier = 0

.ReadTotalTimeoutConstant = 1000

.WriteTotalTimeoutMultiplier = 0

.WriteTotalTimeoutMultiplier = 1000

End WithlngStatus = SetCommTimeouts(udtPorts(intPortID).lngHandle, udtCommTimeOuts)If lngStatus = 0 ThenlngStatus = SetCommError("CommOpen (SetCommTimeouts)")

GoTo Routine_Exit

End If

'Get the current state (DCB).lngStatus =GetCommState(udtPorts(intPortID).lngHandle, _udtPorts(intPortID).udtDCB)

If lngStatus = 0 ThenlngStatus = SetCommError("CommOpen (GetCommState)")

GoTo Routine_Exit

End If

'Modify the DCB to reflect the desired settings.lngStatus = BuildCommDCB(strSettings, udtPorts(intPortID).udtDCB)

If lngStatus = 0 ThenlngStatus = SetCommError("CommOpen (BuildCommDCB)")

GoTo Routine_Exit

End If

' Set the new state.lngStatus = SetCommState(udtPorts(intPortID).lngHandle, _udtPorts(intPortID).udtDCB)

If lngStatus = 0 ThenlngStatus = SetCommError("CommOpen (SetCommState)")

GoTo Routine_Exit

End IflngStatus = 0

Routine_Exit:

CommOpen = lngStatus

Exit Function

Routine_Error:

lngStatus = Err.Number

With udtCommError

.lngErrorCode = lngStatus

.strFunction = "CommOpen"

.strErrorMessage =Err.Description

End With

Resume Routine_Exit

End Function

Private Function SetCommError(strFunction As String)As Long

With udtCommError

.lngErrorCode = Err.LastDllError

.strFunction = strFunction

.strErrorMessage =GetSystemMessage(.lngErrorCode)

SetCommError = .lngErrorCode

End With

End Function

Private Function SetCommErrorEx(strFunction As String, lngHnd As Long)As LongDim lngErrorFlags As Long

Dim udtCommStat As COMSTAT

With udtCommError

.lngErrorCode =GetLastError

.strFunction = strFunction

.strErrorMessage =GetSystemMessage(.lngErrorCode)

Call ClearCommError(lngHnd, lngErrorFlags, udtCommStat)

.strErrorMessage = .strErrorMessage&" COMM Error Flags = "&_

Hex$(lngErrorFlags)

SetCommErrorEx = .lngErrorCode

End With

End Function

'

-------------------------------------------------------------------------------

' CommSet -Modifies the serial port settings.

'

' Parameters:

' intPortID - Port ID used when port was opened.

spinservers($89/月),圣何塞10Gbps带宽服务器,达拉斯10Gbps服务器

spinservers是Majestic Hosting Solutions LLC旗下站点,主要提供国外服务器租用和Hybrid Dedicated等产品的商家,数据中心包括美国达拉斯和圣何塞机房,机器一般10Gbps端口带宽,高配置硬件,支持使用PayPal、信用卡、支付宝或者微信等付款方式。目前,商家针对部分服务器提供优惠码,优惠后达拉斯机房服务器最低每月89美元起,圣何塞机房服务器最低每月...

妮妮云(30元),美国300G防御 2核4G 107.6元,美国高速建站 2核2G

妮妮云的来历妮妮云是 789 陈总 张总 三方共同投资建立的网站 本着“良心 便宜 稳定”的初衷 为小白用户避免被坑妮妮云的市场定位妮妮云主要代理市场稳定速度的云服务器产品,避免新手购买云服务器的时候众多商家不知道如何选择,妮妮云就帮你选择好了产品,无需承担购买风险,不用担心出现被跑路 被诈骗的情况。妮妮云的售后保证妮妮云退款 通过于合作商的友好协商,云服务器提供2天内全额退款,超过2天不退款 物...

Cloudxtiny:£1.5/月,KVM-512MB/100GB/英国机房

Cloudxtiny是一家来自英国的主机商,提供VPS和独立服务器租用,在英国肯特自营数据中心,自己的硬件和网络(AS207059)。商家VPS主机基于KVM架构,开设在英国肯特机房,为了庆祝2021年欧洲杯决赛英格兰对意大利,商家为全场VPS主机提供50%的折扣直到7月31日,优惠后最低套餐每月1.5英镑起。我们对这场比赛有点偏见,但希望这是一场史诗般的决赛!下面列出几款主机套餐配置信息。CPU...

declare_serial为你推荐
手游运营手册游戏发展国主机开发怎么做 怎么开发主机bbsxp老大!!您好!我是初学者!请问我的bbsxp如何更改顶端左面的LOGO??博客外链怎么用博客发外链?湖南商标注册湖南长沙怎么注册商标中国电信互联星空电信的互联星空服务是什么?金山杀毒怎么样金山杀毒好吗邮箱打不开怎么办我的邮箱打不开怎么办吴晓波频道买粉罗辑思维,晓松奇谈,鸿观,吴晓波频道,财经郎眼哪个更有深度畅想中国20年后中国会变成什么样?--畅想一下未来的中国!!迅雷云点播账号求一个迅雷云点播vip的账号,只是看的,绝不动任何手脚。
域名查询工具 花生壳域名贝锐 阿里云搜索 duniu t牌 jsp主机 10t等于多少g 韩国网名大全 南通服务器 上海联通宽带测速 新世界服务器 河南移动梦网 dnspod 免费网络空间 asp空间 hdsky 石家庄服务器 tko 赵荣博客 ddos攻击器下载 更多