Python Forum
My first Python program
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
My first Python program
#1
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
Reply
#2
Hey Herbert,
you can use "break" to end a loop, and system exit to end a program. You can even pair it with datetime to automatically end a program at a given time.
import sys
sys.exit()
#or
x = datetime.datetime.now()
while x.minute() != 25: #example of minute
    #run code
import sys
sys.exit()
Reply
#3
Dear MattKahn13....thanks for your useful tip...you must be a mind reader - indeed I´m planning to end the program after 8 hour by itself - now I know how after even asking!! Pretty cool!!!!
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020