Aug-08-2020, 10:22 PM
I´d appreciate some expert advice for this program - I´m a beginner in Python and suppose some things could be better! For example there must be a better way to end a program than with Ctrl-C. I´m asking myself if the program is polling the serial to much and waste processor power. The serial only gets one value per minute - otherwise it would flood the file that I´ts writing to. I use the program to monitor a motor and one value per minute is enough for that purpose! I´m looking forward to your answers!!!
#!/usr/bin/env python # -*- coding: utf-8 -*- import datetime import serial ser = serial.Serial(port='/dev/ttyAMA0', baudrate = 9600, timeout=1) #open serial_1 on the Raspi filename = datetime.datetime.now().strftime("%d-%m-%Y_%H-%M-%S") #create a unique filename file = open(f"/media/pi/Raspberry-Stick/{filename}.txt","w") #open the correspondent file try: while 1: rpm = ser.readline() # read data from serial_1 and assign it to variable "rpm" print(rpm) # output in the console ser.write(rpm) # write the value to TxD for further processing on a different computer rpm = rpm.decode('utf-8') # bytes to string conversion file.write(rpm) # write the correspondent value to the file except(KeyboardInterrupt, SystemExit): # Keyboard Interrupt [STRG]+[C] End of program print("Exit - File is saved") ser.close() # close serial file.close() # save file