Barcode Scanner Optimization for Raspberry Pi

Although we have successfully ported Dynamsoft Barcode Reader SDK to Raspberry Pi, the performance is not as good as I expected. In my previous article, I demonstrated how to integrate the SDK into a barcode scanner application, in which the detection code works with webcam frame in the same thread. Apparently, it will block UI if the algorithm costs too much time. In this post, I will do three things: optimize the code with thread, beautify the code with clang-format, and make the webcam barcode scanner auto-launched after the system booted.

raspberry pi webcam barcode scanner

Webcam Barcode Scanner Optimization

Move barcode detection code to thread

To avoid blocking the UI thread, we should move the heavy work to a worker thread. The UI thread continuously writes frame to the shared buffer. In the meantime, the worker thread loads the shared buffer after every detection work is done.

Create mutex for locking the shared resource:

pthread_mutex_t image_mutex;

int res = pthread_mutex_init(&image_mutex, NULL);
if (res) {
    perror("Mutex initialization failed");

memcpy(, (char *), size);


Create a thread function and a thread using pthread:

void *thread_function(void *arg) {
  int width, height, size, elemSize;
  char *buffer;
  // Get frame info
  width = imageData.width;
  height = imageData.height;
  elemSize = imageData.elemSize;
  size = imageData.size;
  buffer = (char *)malloc(size);

  while (isDBRWorking) {
    // Get the frame buffer
    memcpy(buffer,, size);

    // Decode barcode
  printf("Thread is over. \n");

isDBRWorking = true;
pthread_t dbr_thread;
res = pthread_create(&dbr_thread, NULL, thread_function, NULL);
if (res) {
    perror("Thread creation failed");

Beautify C/C++ code with clang-format

Install clang-format:

sudo apt-get install clang-format-3.7

Beautify the code with Google style:

clang-format-3.7 –style=Google barcodereader.cpp > output.cpp

Auto-launch barcode scanner after booting Raspberry Pi

Assume you want to create a robot with webcam and Raspberry Pi for barcode detection. There is no display screen connected, and you want to automatically launch the barcode scanning application once the Pi system booted. How to make it?

  1. Set boot option with Console Autologin:
    sudo raspi-config

    rpi boot option
    rpi auto login

  1. Create a shell script
  1. Edit /etc/profile:
    sudo vim /etc/profile
    # Add the following line to the end of the file
    . /home/pi/
  1. Reboot system to automatically launch webcam barcode scanner:
    sudo reboot

Source Code