Access Lab

Como escribir a un puerto serie
Colaboración del amigo Edwin Blancovitch

Copia el siguiente código en un nuevo módulo:

Option Explicit
Declare Function WriteFile& Lib "kernel32" _
    (ByVal hFile As Long, lpBuffer As Any, _
    ByVal nNumberOfBytesToWrite&, _
    lpNumberOfBytesWritten&, ByVal lpOverlapped&)
Declare Function CreateFile& Lib "kernel32" Alias "CreateFileA" _
    (ByVal lpFileName$, ByVal dwDesiredAccess&, _
    ByVal dwShareMode&, ByVal lpSecurityAttributes&, _
    ByVal dwCreationDisposition&, ByVal dwFlagsAndAttributes&, _
    ByVal hTemplateFile&)
Declare Function CloseHandle& Lib "kernel32" (ByVal hObject&)
Declare Function FlushFileBuffers& Lib "kernel32" (ByVal hFile&)

Function OCD(Mensaje As String, CommPort As String) As Boolean
Dim bModemCommand(256) As Byte
Dim OpenPort As Long
Dim RetVal As Long, RetBytes As Long, i As Integer
OCD = False
OpenPort = CreateFile(CommPort, &HC0000000, 0, 0, 3, 0, 0)
If OpenPort = -1 Then
    MsgBox "Error al abrir el puerto " & CommPort
    Exit Function
End If
For i = 0 To Len(Mensaje) - 1
    bModemCommand(i) = Asc(Mid(Mensaje, i + 1, 1))
Next
RetVal = WriteFile(OpenPort, bModemCommand(0), Len(Mensaje), RetBytes, 0)
If RetVal = 0 Then
    MsgBox "Error al escribir en " & CommPort
Else
    RetVal = FlushFileBuffers(OpenPort)
    OCD = True
End If
RetVal = CloseHandle(OpenPort)
End Function

Para enviar, por ejemplo, la cadena "ABRIR" al puerto COM1:, ejecuta la función:

OCD "ABRIR", "COM1"

Obviamente, hay que configurar el puerto COM1 con los parámetros de comunicaciones adecuados a la configuración del equipo conectado.


Volver a AccessLab