'pyserial read qr code and take action on arduino

I'm reading qr code using opencv and pyzbar, i'm communicating with an arduino uno using pyserial.

my python code

from pyzbar.pyzbar import decode 
import cv2
import serial
import time

arduino = serial.Serial(port='COM6', baudrate=115200, timeout=1)

def write_read(x):
  arduino.write(bytes(x, 'utf-8'))
  time.sleep(0.05)
  data = arduino.readline()
  return data

cap = cv2.VideoCapture(0)


def get_qr_data(input_frame):
  try:
      return decode(input_frame)
  except:
      return []

while True:
    _, frame = cap.read()
    qr_obj = get_qr_data(frame)
    cv2.imshow("DD", frame)
    print(qr_obj)
    # cv2.imshow("DD2", frame2)

    if cv2.waitKey(1) & 0xFF == ord('q'):


        break


cap.release()
cv2.destroyAllWindows()

from qr_obj = get_qr_data(frame) i get the result [Decoded(data='asd', type='QRCODE', rect=Rect(left=115, top=155, width=225, height=223), polygon=[Point(x=115, y=378), Point(x=340, y=370), Point(x=335, y=155), Point(x=119, y=155)], quality=1, orientation='UP')]

im trying to print the qr data in arduino serial monitor and turn on the arduino built in led

my arduino code

char x;
void setup() {
Serial.begin(115200);
Serial.setTimeout(1);
pinMode(LED_BUILTIN, OUTPUT);
}
void loop() {
while (!Serial.available());
x = Serial.read();
Serial.println(x);

    if(Serial.read() == x)
   {
      digitalWrite(LED_BUILTIN, HIGH);
     }
 } 

The built in led doesn't turn on and nothing is written in the serial monitor



Solution 1:[1]

I assume you want to copy everything you get. You will need some way to know when the transmission is complete. So, in your Python:

def write_read(x):
  arduino.write(bytes(x, 'utf-8'))
  arduino.write(b'\n')
  time.sleep(0.05)
  data = arduino.readline()
  return data

Then, in Arduino land, something like this:

void loop() {
  while (!Serial.available());
  digitalWrite(LED_BUILTIN, HIGH);
  while( (x = Serial.Read()) != '\n' )
  {
    Serial.print(x);
  }
  Serial.print('\n');
} 

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Tim Roberts