how to remove the delay in obtaining data from the Arduino via COM?
Question: I have an Arduino connected to the joystick. Arduino sends the data via COM
port to my PC. On PC, the data processed by the program in Python, in which
the circle moving with joystick. The fact is that after a few minutes there is
a delay between the joystick and circle.

Code for Arduino

    
    
    #define axis_X 0
    #define axis_Y 1
    
    int value_X, value_Y = 0;
    
    void setup() {
        Serial.begin(9600);
    }
    
    void loop() {
      value_X = analogRead(axis_X);
      Serial.print(value_X, DEC);
      Serial.print("|");
      value_Y = analogRead(axis_Y);
      Serial.print(value_Y, DEC);
      Serial.print("\n");
      delay(20);
    }
    

Code for PC

    
    
    import Tkinter as tk
    import serial
    import os
    import sys
    import time
    
    #connect to COM
    ser = serial.Serial('COM11', 9600, dsrdtr = 1,timeout = 0)
    
    def data():
        time.sleep(0.02)
        serialline = ser.readline().split("\n")
        coord = []
        if serialline[0]:
            string = serialline[0]
            coord = string.split("|")
        return coord
    
    #create window
    
    root = tk.Tk()
    canvas = tk.Canvas(root, width=1000, height=700, borderwidth=0, highlightthickness=0, bg="black")
    canvas.grid()
    
    def _create_circle(self, x, y, r, **kwargs):
        return self.create_oval(x-r, y-r, x+r, y+r, **kwargs)
    tk.Canvas.create_circle = _create_circle
    
    r = 50
    x = 100
    y = 100
    sm = 200
    
    cir = canvas.create_circle(x, y, r, fill="blue", outline="#DDD", width=1)
    root.wm_title("Circles and Arcs")
    
    while 1:
        coord = data()
        x = int(coord[0])/5
        y = int(coord[1])/5
        canvas.coords(cir,x+ sm,y+sm,x+sm + 2*r,y+sm + 2*r)
        root.update()
    

How to solve this problem?


Answer: In the Arduino code, only send the coordinates if the coordinates change:

    
    
    int value_X = 0, value_Y = 0;
    int old_X = 0, old_Y = 0;
    
    void loop() {
      value_X = analogRead(axis_X);
      value_Y = analogRead(axis_Y);
      if ( value_X != old_X || value_Y != old_Y )
      {
          Serial.print(value_X, DEC);
          Serial.print("|");
          Serial.print(value_Y, DEC);
          Serial.print("\n");
          old_X = value_X;
          old_Y = value_Y;
      }
      delay(20);
    }
    

In the python code, remove the delay (`time.sleep(0.02)`). My guess is that
the Arduino is sending data faster than the python code is receiving data, so
eventually you have a queue of unread messages for the python code to process.

