I have a simple method that simply waits for an input, computes a response, and sends it:
void loop() {
if (Serial.available() > 0){
input = Serial.read();
if (input == 10){
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = PulseDuration(echoPin, HIGH, 6000);
distance = duration * 0.00034/2; // 0.00034 m/us is speed of sound
Serial.println(distance, 4);
}
}
}
My question: What happens to the arduino if I close the serial connection from the receiving end while it's printing out data (in the last line of the loop)?
Context and motivation:
The program works well most times. I can open a python program that sends the requests and prints out the reply using pyserial. After I close the python side and reopen it, connection is set and I can start listening on the side nicely just like the first time. Sometimes, however, when I try to restart the python program, I get a connection error saying that the port is already opened (I'm running in Windows.. there are tons of posts about this problem, but none of them have been helpful). Some other times, when connecting with the python program (which connects with connection = serial.Serial(self.arduino_port, 9600, timeout=0)
it just blocks and doesn't connect, it doesn't give the "port already opened" error, and it doesn't advance to the next statement.
I am confident I did close the previous python run before attempting a new one (process explorer shows no active python programs running, it also shows no open processes using a serial handler). I'm not here to solve that problem directly, though, just to ask a related question.
I'm also confident running connection.close()
does not terminate the arduino program, as I have been able to restart my python program without having to reset the arduino or anything, suggesting the arduino kept running its loop after I closed the connection on the python side.
All that to say that my latest hypothesis is that these issues arise when I close the serial connection connection.close()
while the arduino is printing, but because the port is closed, that Arduino is stuck and cannot do the Serial.println(), as the USB never asks to flush the data in its buffer.
Is this possible/does it make sense? What happens to the arduino if I close the serial connection while it's printing out data?
I'm not posting my python program here as it's not directly relevant to the question and I can't seem to make a minimum reproducible program that doesn't expose confidential code.