Hi All,
I often try and display debug data to a serial monitor like PuTTY but one of the problems I run into is I make use of SLEEP in my code so it makes it very difficult requiring me to reconnect the serial interface after every sleep cycle. This is also great to reconnect if you had a WDT event.
I cobbled together a little python that can be used for a monitor that will reconnect automatically
I figured I would share
# ser.py
# written by @HardWater
import os,serial,time,subprocess
from time import sleep
from subprocess import Popen, PIPE, STDOUT
#******************************************************************************************
def find_usb_device(comPort):
command = "C:\\devcon\\i386\\devcon find *usb*"
p = Popen(command, shell=True, stdout=PIPE, stdin=PIPE)
search_phrase = 'matching device'
retcode = ''
i = 0
line = ''
found = 0
while line.find(search_phrase) == -1:
line = p.stdout.readline().rstrip()
#print i,line
if line.find(comPort) > -1:
#this comPort is listed
return(True)
#time.sleep(0.1)
i += 1
return(False)
#******************************************************************************************
comPort = 'COM146'
ser = serial.Serial()
ser.baudrate = 9600
ser.port = int(comPort[3:]) - 1
os.system('cls')
lasttime = 0
while 1:
if time.time() > lasttime + 1 and ser.isOpen() == True:
if find_usb_device(comPort) == False:
#print 'closing serial connection'
ser.close()
time.sleep(3)
else:
lasttime = time.time()
if ser.isOpen() == False:
#print 'opening serial connection'
while ser.isOpen() == False:
try:
ser.open()
except serial.serialutil.SerialException:
pass
print '-------------------------- ser.py %s (re)opened -------------------------' % (comPort)
lasttime = time.time()
while ser.inWaiting() > 0:
c = ser.read()
print '\b%s' % (c),
lasttime = time.time()
Anyways it is not very fancy and could use lots of improvement but maybe you have a use for it
It is dependent on devcon.exe which can be found here https://support.microsoft.com/en-us/kb/311272 and also pySerial
Lastly to make it easy to catch a restart I add a 2 second delay before turning on serial in the device
void setup()
{
delay(2000);
Serial.begin(9600);
}