Python Forum
waiting for barcode scanner output, while main program continues to run
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
waiting for barcode scanner output, while main program continues to run
#2
I haven't run the code. If you do not need access to thread and q from other functions, you can creates them inside a function.
I think your problem comes from scanner_thread.join() inside the loop. This blocks your code until the thread ends, but the thread does never end.

import threading
import serial
import queue


def thread_scanner(q):
    # serial.Serial should support context managers
    with serial.Serial("/dev/ttyACM0", 9600) as ser:
        while True:
            barcode = ser.readline()
            q.put(barcode)


def mainloop():
    """
    Starts the mainloop to print barcodes
    
    Everything else must be done inside this function or
    you put it on module level, if it's required.
    """
    q = queue.Queue()
    scanner_thread = threading.Thread(target=thread_scanner, args=(q,))
    scanner_thread.start()
    while True:
        barcode = q.get() # get blocks until it has an element available
        q.task_done()
        print(barcode)


if __name__ == "__main__":
    mainloop()
Since Python 3 serial.read* return bytes. You can decode them, if it's ASCII or some other kind of encoding.
If it's binary data, you've to convert it into data you can work with.
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply


Messages In This Thread
RE: waiting for barcode scanner output, while main program continues to run - by DeaD_EyE - Aug-27-2020, 08:57 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Waiting for input from serial port, then move on KenHorse 3 1,275 Apr-17-2024, 07:21 AM
Last Post: DeaD_EyE
  pip stops waiting for python walker 6 1,170 Nov-28-2023, 06:55 PM
Last Post: walker
  Use Barcode Scanner With Python Extra 2 1,675 Jul-14-2022, 09:52 AM
Last Post: Gribouillis
  Waiting for heavy functions question philipbergwerf 14 3,522 Apr-29-2022, 07:31 PM
Last Post: philipbergwerf
  port scanner Than999 0 1,227 Feb-01-2022, 12:24 PM
Last Post: Than999
  How to create waiting process? samuelbachorik 4 2,030 Sep-02-2021, 05:41 PM
Last Post: bowlofred
  Python continues after CTRL-C kjbolhuis 2 1,933 Aug-06-2021, 04:28 PM
Last Post: kjbolhuis
  Python BLE Scanner not detecting device alexanderDennisEnviro500 0 2,051 Aug-01-2021, 02:29 AM
Last Post: alexanderDennisEnviro500
  Waiting and listening test 2 2,205 Nov-13-2020, 04:43 PM
Last Post: michael1789
  Windows Python Memory Scanner Awesometech 1 24,447 Oct-14-2020, 07:44 AM
Last Post: badengagen

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020