Android Question Trouble with usb thermal printer

fabton1963

Member
Licensed User
Longtime User
Hello,
I am using this code, which I found in a previus post in the forum, to print reservation tickets with an usb thermal printer

B4X:
Sub aprostampante() As Int
    Dim portausb As Int
    
    portausb = usbport
    
    If PrintBuffer.Length > 0 Then
        If usb1.UsbPresent(portausb) = usb1.USB_NONE Then    ' Ver_2.4
            Log("Msgbox - no device")
            Msgbox("No USB device or accessory detected!", "Error")
            Log("Msgbox - returned")
            Return 0
        End If

        If (usb1.HasPermission(portausb)) Then    ' Ver_2.4

            usb1.SetCustomDevice(usb1.DRIVER_SILABS,  0xdd4,  0x198)

            Dim dev As Int
          
            dev = usb1.Open(19200, portausb) 'STMicroeletronics

            If dev <> usb1.USB_NONE Then
                Log("Connected successfully! 1")
                astreams1.Initialize(usb1.GetInputStream, usb1.GetOutputStream, "astreams1")
                'THIS IS VERY IMPORTANT- PARAMETER
                usb1.SetParameters(19200, usb1.DATABITS_8,usb1.STOPBITS_1, usb1.PARITY_NONE)
                'START PRINT
                astreams1.Write(PrintBuffer.GetBytes("UTF8"))
                astreams1.Close
                Return 1
            Else
                Log("Error opening USB port "&portausb)
            End If
        Else
            usb1.RequestPermission(portausb)  ' Ver_2.4
        End If
    Else
        Return 0
    End If
End Sub

Through this code, the printer manages to print a few copies and then suddenly stops printing without returning any error message. If the program is asked to print once more, it states that it's currently printing but the USB printer is not working. After restarting the program, I am able to print again a few times before this bug occurs.
What am I missing?
 

Erel

B4X founder
Staff member
Licensed User
Longtime User
I don't know whether it is related or not however it is a mistake to call Close like this. You need to wait for the data to be sent.

Two options:
1. Call astream1.SendAllAndClose instead of Close.
2. Add Sleep(1000) before closing. As you are returning a value from this sub, you will need to do some additional simple changes. See the resumable subs video tutorial: https://www.b4x.com/etp.html
 
Upvote 0

fabton1963

Member
Licensed User
Longtime User
Solved,
As you suggest I replaced close with astream1.SendAllAndClose and added Sleep(1000).
Now all is working as expected.
Thank you Erel.
 
Upvote 0
Top