этот код из enumport
Код:
Option Explicit
Type DCB
DCBlength As Long
BaudRate As Long
fBitFields 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
EofChar As Byte
EvtChar As Byte
wReserved1 As Integer
End Type
Type COMMCONFIG
dwSize As Long
wVersion As Integer
wReserved As Integer
dcbx As DCB
dwProviderSubType As Long
dwProviderOffset As Long
dwProviderSize As Long
wcProviderData As Byte
End Type
Public Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)
Declare Function GetDefaultCommConfig Lib "kernel32" _
Alias "GetDefaultCommConfigA" (ByVal lpszName As String, _
lpCC As COMMCONFIG, lpdwSize As Long) As Long
Function EnumSerPorts(Port As Integer) As Long 'Функция вернет 1 , если порт есть
Dim cc As COMMCONFIG, ccsize As Long
ccsize = LenB(cc) '
EnumSerPorts = GetDefaultCommConfig("COM" + Trim(str(Port)) + Chr(0), cc, ccsize)
End Function
Function SearchSerPort(ByVal TimeSleep As Integer) As Boolean 'Перебор номеров портов от 1 до 255
Dim Port_ As Integer, ok As Boolean
For Port_ = 1 To 255
ok = PortCom(Port_, TimeSleep)
If ok Then
SearchSerPort = True
Exit Function
End If
Next Port_
SearchSerPort = False 'Возвращаем False если ни один порт не ответил
End Function
Function PortCom(ByVal Port_ As Integer, ByVal TimeSleep As Integer) As Boolean 'Проверка определенного порта
UserForm.GRBLAnswerFlag = False
If EnumSerPorts(Port_) Then
UserForm.MSComm.CommPort = Port_
UserForm.MSComm.Settings = "115200,N,8,1"
UserForm.MSComm.InputLen = 0
UserForm.MSComm.PortOpen = True
DoEvents 'Отдаем обработку событиям
Sleep (TimeSleep) 'Засыпаем
DoEvents 'Отдаем обработку событиям
If UserForm.GRBLAnswerFlag Then 'GRBLAnswerFlag=True когда событие comEvReceive в MSComm_OnComm получило "GRBL"
PortCom = True 'Порт подключили и он ответил Grbl
UserForm.PortNum = Port_
Exit Function
End If
UserForm.MSComm.PortOpen = False ' Если время вышло (порт не ответил grbl)
'Отключаемся от него и переходим к следующему порту
End If
PortCom = False
End Function