Skip to content

Instantly share code, notes, and snippets.

@brentpicasso
Created May 26, 2017 22:51
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 brentpicasso/5d4067d4f6d8b53a3cc72bcdf4a397fd to your computer and use it in GitHub Desktop.
Save brentpicasso/5d4067d4f6d8b53a3cc72bcdf4a397fd to your computer and use it in GitHub Desktop.
OBDII PID simulator in Lua, supports 29 bit mode and 11 bit mode
--500K baud. set your baud rate here.
initCAN(0, 500000)
--standard 11 bit PID request 0x7DF
--extended 29 bit PID request 0x18DB33F1
--standard 11 bit PID response 0x7E8
--extended 29 bit PID response 0x18DAF110
standard = false
--this function drains all pending CAN messages
--and outputs messages to the log
function checkPidResponse()
local pid = nil
local id
local ext
local data
id, ext, data = rxCAN(0, 1000)
if ext == 1 and id == 0x18DAF110 then
pid = data[3]
end
if ext == 0 and id == 0x7E8 then
pid = data[3]
end
if pid ~= nil then
local mapper = mappers[pid]
if mapper ~= nil then
local value = mapper(data)
local chId = pids[pid]
setChannel(chId, value)
return true
end
end
end
function request_pid(pid)
local r
if standard then
r = txCAN(0, 0x7DF,0 , {2, 1, pid})
else
r = txCAN(0, 0x18DB33F1,1 , {2, 1, pid})
end
-- println('request pid ' ..pid ..' result ' ..r)
end
function onTick()
request_pid(query[queryIndex])
checkPidResponse()
queryIndex = queryIndex + 1
if queryIndex > queryLen then queryIndex = 1 end
end
function rpmMapper(data)
a = data[4]
b = data[5]
return (a * 256 + b) / 4
end
function tpsMapper(data)
return data[4] / 2.55
end
function tempMapper(data)
local degC = data[4] - 40
local degF = degC * 1.8 + 32
return degF
--return degC
end
rpmId = addChannel("RPM", 25, 0, 0, 10000)
tpsId = addChannel("TPS", 25, 0, 0, 100)
tempId = addChannel("EngineTemp", 1, 0, 0, 300)
setTickRate(50)
pids = {}
pids[12] = rpmId
pids[17] = tpsId
pids[5] = tempId
query = {12,17, 12,17, 12,17, 12,17, 12,17, 5}
queryLen = #query
queryIndex = 1
mappers = {}
mappers[12] = rpmMapper
mappers[17] = tpsMapper
mappers[5] = tempMapper
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment