I have an arduino that sends values through the serial port, what I want to do is read the data and save it in a .txt file but it does not save the data. Can you help me?
import time
try:
import serial
arduino = serial.Serial('COM5', baudrate=9600, timeout=1.0)
# Nota: provocamos un reseteo manual de la placa para leer desde
# el principio, ver http://stackoverflow.com/a/21082531/554319
arduino.setDTR(False)
time.sleep(1)
arduino.flushInput()
arduino.setDTR(True)
except (ImportError, serial.SerialException):
# No hay módulo serial o placa Arduino disponibles
import io
with arduino:
while True:
try:
# En Python 3 esta función devuelve un objeto bytes, ver
# http://docs.python.org/3/library/stdtypes.html#typebytes
f = open ('holamundo.txt','w')
line = arduino.readline()
f.write(line)
f.close()
# Con errors='replace' se evitan problemas con bytes erróneos, ver
# http://docs.python.org/3/library/stdtypes.html#bytes.decode
# Con end='' se evita un doble salto de línea
print(line.decode('ascii', errors='replace'), end='')
except KeyboardInterrupt:
print("Exiting")
break