Page 1 of 1

Can't query virtual channels mapped via CAN

Posted: Mon Aug 17, 2015 2:49 am
by madjak
I have the RCP working atm but I'm pretty sure how I've implemented it isn't ideal.

Basically I'm using the standard CAN script to read the CAN data and map it to virtual channels, however once mapped, Lua can query the value for use in other scripts. For example, I'm mapping rpmId via the CAN, I can see it on the dashboard but can't query the variable rpmId in Lua even via a print(rpmId).

here is a snippet of my code...

Code: Select all

Can_map = {
[864] = function(data) 
    map_chan(rpmId, data, 0, 2, 1, 0)
end
}

onTick()
  processCAN()
  if rpmId > 5000 then setAnalog(1,10) end
  print (rpmId)
end

function processCAN()
  repeat
    local id, e, data = rxCAN(0)
    if id ~= nil then
      local map = CAN_map[id]
      if map ~= nil then
        map(data) --this runs map_chan function with the CAN 'data'
      end
    end
  until id == nil
end

function map_chan(cid, data, offset, len, mult, add) --eg (rpmId, data, 0, 2, 1, 0)
  offset = offset + 1
  local value = 0
  while len > 0 do
    value = (value * 256) + data[offset]
    offset = offset + 1
    len = len - 1
  end
  setChannel(cid, (value * mult) + add)
end
processCAN() is your standard CAN function from the wiki.

So the lights won't work, and no print will occur. It's like the variable rpmId doesn't exist. Once the virtual channel is mapped the variable rpmId returns nothing. Am I meant to query the mapped channel differently?

What I've done to get around this issue is build an array of values for each of my variables and query that instead. Basically it places rpmId in position 1, mapId in position 2, tpsId in pos3 etc. Here is a snippit of my code:

Code: Select all

VarArray = {0,0,0,0,0,0,0,0,0}

onTick()
  ProcessCAN()
  if VarArray[1] > 5000 then setAnalog(1,10) end
  print (VarArray[1])
end

Can_map = {
[864] = function(data) 
    map_chan(1, rpmId, data, 0, 2, 1, 0)
    map_chan(2, mapId, data, 2, 2, 0.1, -101.3)
    map_chan(3, tpsId, data, 4, 2, 0.1, 0)
end
}

function map_chan(var, cid, data, offset, len, mult, add)
  offset = offset + 1
  local value = 0
  while len > 0 do
    value = (value * 256) + data[offset]
    offset = offset + 1
    len = len - 1
  end
  setChannel(cid, (value * mult) + add)
  VarArray[var] = (value * mult) + add
end
This isn't the nicest way to query the variables but it works. Once I map the virtual channel in the CAN script how do I then query it and use it in Lua?

Posted: Thu Sep 10, 2015 7:33 pm
by rdoherty
Hi madjak, the reason why rpmId doesn't exist is because it's never set. You need to first create the RPM virtual channel like so:

rpmId = addChannel("RPM", 10, 0, 0, 10000)

Then you can pass the rpmId to the CAN map. To be clear 'rpmId' is *not* the current RPM value, it is simply a number for the Luascript to keep track of virtual channels.

Hope that helps!