I have the following Python code which is just reading from an Arduino, and writing to a file:
import serial
from datetime import datetime
import time
ser = serial.Serial('COM3', 9600, timeout=0)
text_file = open("voltages.txt", 'w')
while 1:
x=ser.readline()
print(str(datetime.now()), x)
data = [str(datetime.now()),x]
text_file.write("{}\n".format(data))
text_file.flush()
time.sleep(1)
Whenever I interrupt the script, I always have to type ser.close() in the console, otherwise I cannot start the script again (in the same console).
How can I close the serial communication automatically whenever I interrupt the script?