Help with Serial communication between Python and Arduino

Hi all, I'm working on a simple autonomous vehicle project, and I want to be able to select gps coordinates in a tkinter app I made, then send them to the arduino via Serial. I have successfully done this, but consistently I lose the first 2 coordinates I send. I cannot for the life of me figure out why I'm not getting the first 2.

Here's the arduino code that should recieve and process coords:

struct GPSCoordinate {
  float latitude;
  float longitude;
};

char inData[14];
int numCoords = 0;
GPSCoordinate coordinates[32];

void setup() {
  Serial.begin(9600);
  while (true) {
    int index = 0;
    while (true) {
      if (Serial.available() > 0) {
        char c = Serial.read();
        if (c == '\n') {
          inData[index++] = '\0';
          break;
        } else {
          inData[index++] = c;
        }
      }
    }
    
    if (strcmp(inData, "␄") == 0) {
      break;
    }
    
    coordinates[numCoords] = parseCoordinateString(inData);
    numCoords = numCoords+1;
  }
}

void loop() {
  Serial.print(numCoords);
  Serial.println(" List of Coordinates:");
  for (int i = 0; i < numCoords; i++) {
    Serial.print("Latitude: ");
    Serial.print(coordinates[i].latitude, 8);
    Serial.print(", Longitude: ");
    Serial.println(coordinates[i].longitude, 8);
  }
  delay(1000);
}

GPSCoordinate parseCoordinateString(char* gpsString) {
  GPSCoordinate coord;
  char *lat_str = strtok(gpsString, ",");
  char *lon_str = strtok(NULL, ",");
  if (lat_str != NULL && lon_str != NULL) {
    float lat = atof(lat_str);
    float lon = atof(lon_str);
    coord = {lat, lon};
  }
  return coord;
}

And here's the relevant python code:

    def sendWaypoints(self):
        coordList = []
        for waypoint in self.waypointList:
            coordList.append(list(waypoint.position))
        print(coordList)
        serialCon = serial.Serial(self.serial_port, 9600)
        for coord in coordList:
            lat = "{:.10f}".format(coord[0])
            lon = "{:.10f}".format(coord[1])
            lat_lon_str = lat+','+lon+'\n'
            bytes = serialCon.write(lat_lon_str.encode())
            time.sleep(.5)
        time.sleep(1)
        bytes = serialCon.write("␄\n".encode())

#This loop is here for debugging purposes while getting this to work
        while True:
            line = serialCon.readline().decode().strip()
            print(line)

        serialCon.close()
        tkinter.messagebox.showinfo(title="", message="Waypoints sent!")

And finally here is a sample output to the terminal:

[[34.241481450236876, -77.95466705986328], [34.22530239557737, -77.95432373710938], [34.207416666176755, -77.95810028740235]]

1 List of Coordinates:
Latitude: 34.20741653, Longitude: -77.95809173

As you can see, the first 2 have vanished, and only the third has been stored, and numCoords has only been incremented 1 time.

I would appreciate any help. Thanks!

Welcome to the forum

The Arduino resets when you open the Serial port. Could that be a problem ?

1 Like

Never really thought about that. I just threw a time.sleep(5) after python initiates the serial connection and it's working perfectly now. Thanks!

Glad that I could help

Does the arduino also reset upon closing the serial connection? If so I’ll have to rethink my coordinate transmission strategy.

I don't believe that a reset occurs on closing the serial connection, but I am not sure

Guess I’ll have to do some testing. I appreciate the help!

Which Arduino board are you using ?

I’m using an uno r3

I think a small change could help you to implement a stringer protocol. Instead of sending the coordinates without knowing if the other party is ready, just wait for a specific "ready" signal from Arduino (to be sent once on starting, i.e. the setup()), you could just send a single character command like "R\n" (as "Ready"), then the sender knows can start sending the coordinates, making this phase in sync.

1 Like

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