Attribute VB_Name = "FlushSerialPort"
'-------------------------------------------------------------------------------
Option Explicit

' This module is used to flush all data from output queues for serial ports.
' Ports Com1, Com2 and Com3 are handled.
'
' Example code using Com1:
'
'  Private InBuff(1 To 10) As Byte
'  Private OutBuff(1 To 20) As Byte
'  Public Sub Main()
'
'      Call OpenQueue(InBuff, 10)
'      Call OpenQueue(OutBuff, 20)
'      Call OpenCom(1, 19200, InBuff, OutBuff)
'      Do
'          Call PrimePort(1)
'
'          Call PutQueueStr(OutBuff, "Hello world")
'          Call PutQueueStr(OutBuff, Chr(13) & Chr(10))
'
'          Call FlushOutputBuffer(1, OutBuff)
'          Delay 0.2
'      Loop
'
'  End Sub
'-------------------------------------------------------------------------------
Public Sub PrimePort( _
    ByVal PortNumber As Byte)

' This procedure should be called at least once before writing anything to
' Com1.
'
' Warning -- this procedure should not be called unless data is actually
' written to Com1. Otherwise the program may hang if you subsequently use
' bit TXC to judge whether a transmission is complete.

    ' UART Transmit Complete.
    Const TXC As Byte = bx0100_0000

    If (PortNumber = 1) Then

        ' Clear TXC by writing 1 to it.
        Register.USR = Register.USR Or TXC
    End If

End Sub
'-------------------------------------------------------------------------------
Public Sub FlushOutputBuffer( _
    ByVal PortNumber As Byte, _
    ByRef OutputQueue() As Byte)

' Returns as soon as all characters in the serial port output queue have
' been transmitted.

    ' For Com1 -- UART Transmit Complete.
    Const TXC As Byte = bx0100_0000

    ' For Com2.
    Const OCIE1A As Byte = bx0100_0000

    ' For Com3.
    Const Com3Status As Integer = 21
    Const TXC3 As Byte = bx0100_0000

    ' Wait until queue is empty.
    Do While StatusQueue(OutputQueue)
    Loop

    ' Wait for transmission to complete.
    Select Case PortNumber
        Case 1
            Do Until ( (Register.USR And TXC) = TXC )
            Loop
        Case 2
            Do While ( (Register.TIMSK And OCIE1A) = OCIE1A )
            Loop
        Case 3
            Do While ( (RAMpeek(CuInt(Com3Status)) And TXC3) = TXC3 )
            Loop
    End Select

End Sub
'-------------------------------------------------------------------------------
