Skip to content

Instantly share code, notes, and snippets.

@runion
Created December 13, 2012 22:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save runion/4280596 to your computer and use it in GitHub Desktop.
Save runion/4280596 to your computer and use it in GitHub Desktop.
This program monitors the serial connection between the computer and an attached Arduino. It accepts only the characters 1, 2, 3, or 4, and returns a text file based on which character is read. It normally runs as a background process, so the print statements are ignored. The text files are generated via a separate program, set up as a CRON job,…
import serial, time, os
def main():
pid = os.getpid()
pidFile = open("/home/davidr/solar/solarSerial.pid", "w")
pidFile.truncate()
pidFile.write(str(pid))
pidFile.close()
print "getting started here"
s = serial.Serial('/dev/ttyACM0', 9600)
time.sleep(1)
while(True):
if s.isOpen():
print "Serial port is open"
read = int(s.read(3).strip().strip(":")[-1:])
if read == 1:
print "1 has been read"
s.write(open("/home/davidr/solar/current.txt").read().strip())
elif read == 2:
print "2 has been read"
s.write(open("/home/davidr/solar/daily.txt").read().strip())
elif read == 3:
print "3 has been read"
s.write(open("/home/davidr/solar/wk_mo.txt").read().strip())
elif read == 4:
print "4 has been read"
s.write(open("/home/davidr/solar/lifetime.txt").read().strip())
else:
print "we read something: "
print read
s.write("ERROR")
else:
print "serial connection not open"
time.sleep(2)
if __name__ == '__main__':
main()
@runion
Copy link
Author

runion commented Dec 13, 2012

One thing to note is that this script saves a pid file with the process ID of the program. A separate script run via CRON reads that file and verifies that there is a running program (this program) with that PID. If not, the separate program restarts this script.
That will restart this script if the USB cable is disconnected (which causes this program to abort) or if the computer is rebooted, or if some other error occurs which causes this program to abort.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment