先不要用上位机通讯库做测试。用现成的、成熟的 API 或其他第三方的串口调试软件做测试你的串口状态。
和吹同志说的一样,首先检查你的PC机上是否有串口设备,即:在“设备管理--端口--COM1--属性--端口设置”,设备存在吗?有冲突吗?有黄色报警符号吗?
接下来测试串口的状态,其他第三方的串口调试软件网上太多了。
1. 用 MS 通讯库 MScomm32.ocx,参考:https://support.
或者 WMI 类库:https://msdn.
2. 用 API 方式:
可以用 API :CreateFile() 函数:http://www.
Do Decl
Local nIndex, cPort
For nIndex = 1 To 8
&& 枚举 1-8 的 COM 端口
cPort = "COM" + Transform(nIndex)
? "正在测试串口 " + m.cPort + ":", TestPort(m.cPort)
Endfor
* End of main
Function TestPort(cPort)
#Define FILE_SHARE_READ
1
#Define FILE_SHARE_WRITE
2
#Define OPEN_EXISTING
3
#Define GENERIC_READ
0x80000000
#Define GENERIC_WRITE
0x40000000
#Define FILE_FLAG_OVERLAPPED 0x40000000
#Define INVALID_HANDLE_VALUE -1
#Define FILE_ATTRIBUTE_NORMAL 128
Local hPort, lnErr
* hPort = CreateFile(cPort, GENERIC_READ, 0,0,;
OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0)
hPort = CreateFile(cPort,;
BITOR(GENERIC_READ,GENERIC_WRITE),;
0,0, OPEN_EXISTING,;
BITOR(FILE_FLAG_OVERLAPPED, FILE_ATTRIBUTE_NORMAL), 0)
If hPort = INVALID_HANDLE_VALUE
lnErr = GetLastError()
Return "错误 " + Transform(lnErr) +;
". " + GetErrorMessage(lnErr)
Else
= CloseHandle(hPort)
Return "Ok"
Endif
Endfunc
Procedure Decl
Declare Integer CreateFile In kernel32;
STRING lpFileName, Integer dwAccess, Integer dwShareMode,;
INTEGER lpSecurityAttr, Integer dwCreationDisp,;
INTEGER dwFlagsAndAttr, Integer hTemplateFile
Declare Integer CloseHandle In kernel32 Integer hObject
Declare Integer GetLastError In kernel32
Declare Integer FormatMessage In kernel32;
INTEGER dwFlags, Integer lpSource, Integer dwMessageId,;
INTEGER dwLanguageId, Integer @lpBuffer,;
INTEGER nSize, Integer Arguments
Declare RtlMoveMemory In kernel32 As CopyMemory;
STRING @Destination, Integer Source, Integer nLength
Endproc
Function GetErrorMessage(lnErr)
#Define FORMAT_MESSAGE_ALLOCATE_BUFFER 256
#Define FORMAT_MESSAGE_FROM_SYSTEM
4096
#Define FORMAT_MESSAGE_IGNORE_INSERTS
512
Local dwFlags, lpBuffer, lnLength, lpResult
dwFlags = FORMAT_MESSAGE_ALLOCATE_BUFFER +;
FORMAT_MESSAGE_FROM_SYSTEM + FORMAT_MESSAGE_IGNORE_INSERTS
lpBuffer = 0
lnLength = FormatMessage(dwFlags, 0, lnErr, 0, @lpBuffer, 0,0)
If lnLength <> 0
lpResult = Repli(Chr(0), 500)
= CopyMemory (@lpResult, lpBuffer, lnLength)
Return Strtran(Left(lpResult, lnLength), Chr(13) + Chr(10), "")
Else
Return "[]"
Endif
Endfunc