微软最简单的例子,其帮助文件中有详细用法说明,到msdn中查找就可以,很详细。
The following simple example shows basic serial communications using a modem:
Private Sub Form_Load ()
' Buffer to hold input string
Dim Instring As String
' Use COM1.
MSComm1.CommPort = 1
' 9600 baud, no parity, 8 data, and 1 stop bit.
MSComm1.Settings = "9600,N,8,1"
' Tell the control to read entire buffer when Input
' is used.
MSComm1.InputLen = 0
' Open the port.
MSComm1.PortOpen = True
' Send the attention command to the modem.
MSComm1.Output = "ATV1Q0" & Chr$(13) ' Ensure that
' the modem responds with "OK".
' Wait for data to come back to the serial port.
Do
DoEvents
Buffer$ = Buffer$ & MSComm1.Input
Loop Until InStr(Buffer$, "OK" & vbCRLF)
' Read the "OK" response data in the serial port.
' Close the serial port.
MSComm1.PortOpen = False
End Sub
Note The MSComm control can use polling or an event-driven method to retrieve data from the port. This simple example uses the polling method. For an example of the event-driven method, see help for the OnComm event.
串行通讯的基本知识
每台计算机都提供了一个或多个串行端口。它们被依次命名为:COM1、COM2 等等。在标准的 PC 中,鼠标通常被连接到 COM1 端口。调制解调器可能连接到 COM2,扫描仪被连接到 COM3,等等。串行端口提供了计算机与这些外部串行设备之间的数据传输通道。
串行端口的本质功能是作为 CPU 和串行设备间的编码转换器。当数据从 CPU 经过串行端口发送出去时,字节数据被转换为串行的位。在接收数据时,串行的位将被转换为字节数据。
要完成数据的传输,还需要进一步一个解释层。在操作系统一边,Windows 使用了通讯驱动程序 Comm.drv,以便使用标准的 Windows API 函数发送和接收数据。驱动程序通常由串行设备制造商提供,以便将其硬件与 Windows 连接。在使用 Communications 控件时,实际上使用了 API 函数,API 函数将被 Comm.drv 解释并传输给设备驱动程序。
作为程序员,只需关心如何与 Windows 打交道。作为 Visual Basic 程序员,只需要关心 Communications 控件提供的对 Windows 通讯驱动程序的 API 函数的接口。换句话说,只需要设置和监视 Communications 控件的属性和事件。