Skip to content

Instantly share code, notes, and snippets.

@kenny-macchina
Last active April 13, 2021 11:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save kenny-macchina/cf47daf663f9091460fc3454f5e38de9 to your computer and use it in GitHub Desktop.
Save kenny-macchina/cf47daf663f9091460fc3454f5e38de9 to your computer and use it in GitHub Desktop.
import can
from can.interface import Bus
from can import Message
import os
from datetime import datetime
from datetime import time
import csv
os.system('sudo ip link set can0 down')
os.system('sudo ip link set can0 up type can bitrate 500000')
can.rc['interface']='socketcan'
can.rc['channel']='can0'
can.rc['bitrate']=500000
print('CAN0 Setup Complete')
bus=Bus()
msg_mph=Message(is_extended_id=False, arbitration_id=0x7DF, data=[2,1,0xD,0xAA,0xAA,0xAA,0xAA,0xAA])
msg_rpm=Message(is_extended_id=False, arbitration_id=0x7DF, data=[2,1,0xC,0xAA,0xAA,0xAA,0xAA,0xAA])
msg_temp=Message(is_extended_id=False, arbitration_id=0x7DF, data=[2,1,5, 0xAA,0xAA,0xAA,0xAA,0xAA])
last=datetime.now()
fields=['Time','Vehicle Speed (MPH)','Engine Speed (RPM)','Coolant Temperature (C)']
newRow=[' ',' ',' ',' ']
pollTime=0.1
rpmSend=False
tempSend=False
fileName='dataLog.csv'
x=datetime.now()
fileName=str(x.year)+str(x.month).zfill(2)+str(x.day).zfill(2)+str(x.hour).zfill(2)+str(x.minute).zfill(2)+fileName
with open(os.path.dirname(__file__)+'/../'+fileName,'w') as csvfile:
csvwriter=csv.writer(csvfile)
csvwriter.writerow(fields)
print('CSV File Created')
for msg in bus:
if (datetime.now()-last).total_seconds()>pollTime:
print('Polling('+str(datetime.now().hour).zfill(2)+':'+str(datetime.now().minute).zfill(2)+':'+str(datetime.now().second).zfill(2)+')...')
last=datetime.now()
bus.send(msg_mph)
#print('Sending speed request at '+str(datetime.now().time()))
rpmSend=True
tempSend=True
if rpmSend and (datetime.now()-last).total_seconds()>pollTime/3.0:
rpmSend=False
bus.send(msg_rpm)
#print('Sending rpm request at '+str(datetime.now().time()))
if tempSend and (datetime.now()-last).total_seconds()>pollTime*2.0/3.0:
tempSend=False
bus.send(msg_temp)
#print('Sending temp request at '+str(datetime.now().time()))
if (msg.arbitration_id>2015 and msg.arbitration_id<2032):
#SPEED
if (msg.data[1]==65 and msg.data[2]==13):
#print('Speed: '+str(msg.data[3]*0.621371))
newRow[0]=str(datetime.now().time())
newRow[1]=str(msg.data[3]*0.621371)
#RPM
elif (msg.data[1]==65 and msg.data[2]==12):
#print('RPM: '+str(64.0*msg.data[3]+0.25*msg.data[4]))
newRow[2]=str(64.0*msg.data[3]+0.25*msg.data[4])
#TEMP
elif (msg.data[1]==65 and msg.data[2]==5):
#print('Temp: '+str(msg.data[3]-40))
newRow[3]=str(msg.data[3]-40)
csvwriter.writerow(newRow)
else:
continue
else:
continue
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment