Serial communiaction between python and arduino

I was creating a project where the following part of the code reads certain area of the display(which i screen shared from mobile)

import cv2 as cv
import numpy as np
from PIL import ImageGrab
import serial
arduinodata = serial.Serial('com5',9600)

def led_on():

def led_off():

while True:
    screen = np.array(ImageGrab.grab(bbox=(0,0,1920,1080)))
    #define the screen resulation
    screen_res = 1920, 1080
    scale_width = screen_res[0] / screen.shape[1]
    scale_height = screen_res[1] / screen.shape[0]
    scale = min(scale_width, scale_height)
    #resized window width and height
    window_width = int(screen.shape[1] * scale)
    window_height = int(screen.shape[0] * scale)
    #cv.namedWindow('Resized Window', cv.WINDOW_NORMAL)
    cv.resizeWindow('Resized Window', window_width, window_height)
    resized = screen.resize()
    health_bar = screen[262:268, 142:365]    
    health_grayed = cv.cvtColor(health_bar, cv.COLOR_BGR2GRAY)
    count1 = cv.countNonZero(health_grayed)

if i==1:
    e =count1

if e>count1:

if e<count1:

and whenever the value of the count1 variable decreases i want the Arduino led should be turned on

this was the arduino code

char serialData;

void setup() {
  // put your setup code here, to run once:


void loop() 
  // put your main code here, to run repeatedly:
  if(Serial.available() >0)


But the led is turning on but does not turns off . I don't know why

can anyone please help me

Python use indentation for structure, seems your if are not in the while True:
your arduino code never removes anything from the Serial buffer and you'll see the light always on because there is no second delay to blink.

note that you also read the Serial port in that case every 2s, so don't expect fast reaction. You might want to study blink without delay

@akash2345, your topic has been moved to a more suitable location on the forum.

A post was split to a new topic: Arduino / Python

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.