Created
December 16, 2015 20:01
-
-
Save parthpower/37b0b2652ddd316aadbe to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#author: Parth Parikh | |
#Distributed under MIT License | |
#Simple Serial CSV Logger | |
import serial | |
import datetime | |
LOG_FILE = datetime.datetime.now().strftime('%d_%m_%Y_%H_%M_%S')+"_log.csv" | |
BAUD = 9600 | |
def available_ports(): | |
ports =['COM%s'%(i+1) for i in range(256)] | |
result = [] | |
for port in ports: | |
try: | |
s = serial.Serial(port) | |
s.close() | |
result.append(port) | |
except (OSError, serial.SerialException): | |
pass | |
return result | |
def get_data(interface): | |
#Input data is like \r111 cm\r\n length is 9 byte | |
buf = interface.readline() | |
while len(buf) != 9: #confirm data is read from the begaining | |
buf = interface.readline() | |
return int(buf[1:4]) | |
def get_time(): | |
return datetime.datetime.now().strftime('%d-%m-%Y %H:%M:%S') | |
if __name__ == "__main__": | |
portList = available_ports() | |
i = 1 | |
for port in portList: | |
print(str(i) +')'+port) | |
i+=1 | |
print("0)Exit") | |
selectedPortId = raw_input("SelectPort:") | |
if(selectedPortId == "0"): | |
exit() | |
try: | |
i = int(selectedPortId) | |
selectedPort = portList[i-1] | |
except Exception,e: | |
print("Wrong Input!!!!!!!!!!!!!!!") | |
raise e | |
try: | |
interface = serial.Serial(selectedPort,BAUD) | |
except Exception, e: | |
raise e | |
fp = open(LOG_FILE,"w") | |
fp.write("Time,Distance(cm)"+'\n') | |
fp.close() | |
while True: | |
data = get_data(interface) | |
csv = get_time()+','+str(data) | |
print(csv) | |
fp = open(LOG_FILE,"a") | |
fp.write(csv+'\n') | |
fp.close() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment