RegisterSearchFAQMemberlistUsergroupsLog in
Reply to topic Page 1 of 1
Looking for help with out of memory errors
Author Message
Reply with quote
Post Looking for help with out of memory errors 
Hey folks,

I am trying to implement some Shift2X stuff and my program has begun to behave weirdly. I was getting sporadic out of memory errors and I cut out some stuff - but the program will run for a while and then act up oddly which I am assuming means out of memory stuff.

I'm pretty novice at LUA and I was wondering if you had any suggestions on streamlining this to reduce memory usage.

I am running this through a minifier - so that strips out all the comments and such.

I was thinking of abandoning the Shift2X routines and simply writing to the LEDs. That would be a bummer but it seems like the Shift2X stuff is when I started to get issues.

Is there any way to determine how much memory this program will use and how close I am to running into memory errors?

Any suggestions (that sort of maintain functionality) would be really appreciated.


Code:

--Udder Chaos Lua Script File
-- Revision Log
-- Version   Date    Description
-- 1   April 17  Road America - first Race
-- 2   August 17 Gingerman Race
--     Removed piggy back gages
--     Added brake sensor
--     Adding CAN bus functionalty to OBDII
--     Adding shift light sensor
--    8-15 added can Sniffer
--    brake light script
-- 3  Road America Second Race
--    added virtual channel for brakes and gears
-- 4  April 2018 Road America - First Race
--    Adding in Shift2X LED display
--    Debug of brake light delay and trying to add the CAN bus back in
--    Remove can bus

-- Useful Reference Stuff: - channels start at 0 (i.e. AN1 = channel 0)
--   AN1 = OIL PRESSURE
--   AN2 = TRANS TEMP
--   AN3 = OIL TEMP
--   AN4 = H20 TEMP
--   AN5 = FUEL
--   AN6 = 02
--   AN7 = MAP
--   RPM1 = TACH
--   Shift2X is on CAN1

--   debug = true  -- flag used to turn on various rountines when debugging the program - uncomment if needed

-- Adding virtual Channels
   fuel_damped = addChannel("Fuel_Level", 10, 1, 0,12.6,"%")  -- Fuel_damped is a virtual channel that smooths out fuel sloshing
   brake_status = addChannel("Brake_stat", 10, 0)  --- A virtual channel used to report when the brake is pressed for logging.
   gearId = addChannel("Gear",5)  -- A virtual channel used to track which gear we are in. 

-- Fuel Anti-sloshing routine stuff
   maxAvg = 75 --change this to make a bigger averaging window
   fuelAvg={} -- define fuelAvg as a LUA array
   fuel_damped_Index = 1

-- Function updateFuelAverage - called by tick - smooths out fuel
function updateFuelAvg(value)
  local i
  if #fuelAvg == 0 then
    --initialize averaging table
    for i = 1, maxAvg do fuelAvg[i]=0 end
  end
  fuelAvg[fuel_damped_Index] = value
  fuel_damped_Index = fuel_damped_Index + 1
  if fuel_damped_Index > maxAvg then fuel_damped_Index = 1 end
  local sum = 0
  for i = 1, #fuelAvg do
    sum = sum + fuelAvg[i]
  end
  setChannel(fuel_damped, sum / maxAvg)
end

-- Function check_gear updates the gear position - called every tick
function check_gear()
-- Constants for Gear Determination
-- Put these directly into code to save memory
-- local _1stGear = 3.54
-- local _2ndGear = 2.13
-- local _3rdGear = 1.36
-- local _4thGear = 1.03
-- local _5thGear = .81
-- local FinalDrive = 3.94
local TireDia = 23.0  -- in inches
local gearErr = 0.1--allowable error of gear ratio to allow for measurement variation
local rpmSpeedRatio = 0
local gearPos = 0 --initialized to 0 so if it doesn't work you know
local speed = getGpsSpeed()
local rpm = getTimerRpm(0)

if speed > 10 then
    --makes sure your rolling so as not to divide by 0
   rpmSpeedRatio = (rpm/speed)/(FinalDrive*1056/(TireDia*3.14159))
   if ((3.54 - rpmSpeedRatio)^2) < (gearErr^2) then gearPos = 1 end
   if ((2.13 - rpmSpeedRatio)^2) < (gearErr^2) then gearPos = 2 end
   if ((1.36 - rpmSpeedRatio)^2) < (gearErr^2) then gearPos = 3 end
   if ((1.03 - rpmSpeedRatio)^2) < (gearErr^2) then gearPos = 4 end
   if ((.81 - rpmSpeedRatio)^2) < (gearErr^2) then gearPos = 5 end
else gearPos = 0 end
setChannel(gearId, gearPos) --outputs to virtual channel
end

-- ShiftX2 is connected to CAN1. 0=CAN1, 1=CAN2
sxCan = 0

-- 0=first ShiftX2 on bus, 1=second ShiftX2 (if ADR1 jumper is cut)
sxId=0

--how often ontick is updated
tickRate=10

--Brightness, 0-100. 0=automatic brightness
sxBright=0

function sxOnUpdate()
 
-- To keep things simple for the driver we are not attempting to map LEDs to specific warnings or danger conditions. If ANY
-- threshold is exceeded, the two end LEDs on the ShiftX will light up (yellow for warning - red for danger).  The driver
-- should be able to see what the specific problem is by looking at the gages. 

local warning = false  -- Boolean variable tracking warning threshold has been exceeded.
local danger = false  -- Boolean variable tracking that danger threshold has been exceeded.

--     Thresholds These are in here for convenience and must be updated in the code below
--                                       Warning     Danger
--     AN1 (Channel 0) = OIL PRESSURE     35          20    (PSI)
--     AN2 (Channel 1) = TRANS TEMP       185         200   (Degrees F)
--     AN3 (Channel 2) = OIL TEMP         220         250   (Degrees F)
--     AN4 (Channel 3) = H20 TEMP         212         230   (Degrees F)

-- Go get the readings from the analog gages for Oil pressure, Trans Temp, Oil Temp and coolant temp
 oil_pressure = getAnalog(0)
 trans_temp = getAnalog(1)
 oil_temp = getAnalog(2)
 H20_temp = getAnalog(3)
 
 if debug then println('oilpressure = '..oil_pressure) end

 if oil_pressure < 35 then warning = true
  end
  if oil_pressure < 20 then danger=true
  end
 if trans_temp > 185 then warning=true
 end
  if trans_temp > 200 then danger=true
 end
  if oil_temp > 220 then warning=true
  end
 if oil_temp > 250 then danger=true
 end
  if H20_temp > 212 then warning=true
  end
  if H20_temp > 230 then danger=true
 end

-- If one of the warning flags has been set - set the two end LEDS (7 and 8) to yellow. 
  if warning  and (not  danger ) then
     sxSetLed(8,1,255,255,0,0)
     sxSetLed(7,1,255,255,0,0)
-- If one of the danger flags has been set - set the two end LEDs (7 and 8) to red and flash them. 
   elseif danger and warning then
     sxSetLed(8,1,255,0,0,0)
     sxSetLed(7,1,255,0,0,0)
-- Otherwise set the two end LEDs to green (no warning and no danger)     
   else
      sxSetLed(8,1,0,255,0,0)
     sxSetLed(7,1,0,255,0,0)
   end
 
 -- Update the linear graph with the current RPM 
  sxUpdateLinearGraph(getTimerRpm(0))
end

function sxOnInit()
  --config shift light
  sxCfgLinearGraph(0,0,0,7000) --left to right graph, linear style, 0 - 7000 RPM range
  sxSetLinearThresh(0,0,3000,0,255,0,0) --green at 3000 RPM
  sxSetLinearThresh(1,0,5800,255,255,0,0) --yellow at 5800 RPM
  sxSetLinearThresh(2,0,6200,255,0,0,10) --red+flash at 6200 RPM
end

---ShiftX2 functions

function sxSetLed(i,l,r,g,b,f)
  sxTx(10,{i,l,r,g,b,f})
end

function sxSetLinearThresh(id,s,th,r,g,b,f)
  sxTx(41,{id,s,spl(th),sph(th),r,g,b,f})
end

function sxSetAlertThresh(id,tid,th,r,g,b,f)
  sxTx(21,{id,tid,spl(th),sph(th),r,g,b,f})
end

function setBaseConfig(bright)
  sxTx(3,{bright})
end

function sxSetAlert(id,r,g,b,f)
  sxTx(20,{id,r,g,b,f})
end

function sxUpdateAlert(id,v)
  if v~=nil then sxTx(22,{id,spl(v),sph(v)}) end
end

function sxCfgLinearGraph(rs,ls,lr,hr)
  sxTx(40,{rs,ls,spl(lr),sph(lr),spl(hr),sph(hr)})
end

function sxUpdateLinearGraph(v)
  if v ~= nil then sxTx(42,{spl(v),sph(v)}) end
end

function sxInit()
  setBaseConfig(sxBright)
  if sxOnInit~=nil then sxOnInit() end
end

function sxChkCan()
  id,ext,data=rxCAN(sxCan,0)
  if id==sxCanId then sxInit() end
  if id==sxCanId+60 and sxOnBut~=nil then sxOnBut(data[1]) end
end

function sxProcess()
  sxChkCan()
  if sxOnUpdate~=nil then sxOnUpdate() end
end

function sxTx(offset, data)
  txCAN(sxCan, sxCanId + offset, 1, data)
  sleep(10)
end

function spl(v) return bit.band(v,0xFF) end
function sph(v) return bit.rshift(bit.band(v,0xFF00),8) end


-- Function onTick is the main loop for the program. 
-- Ontick will call update fuel average to create a smoothed out fuel level
function onTick()
  collectgarbage() -- This deletes objects in LUA that are unsuable 
  updateFuelAvg(getAnalog(4))-- call the fuel average routine and pass it the current fuel tank reading to smooth out.
   check_gear()  -- call the routine that checks to see what gear we are in
  sxProcess()  --  Process the shift-2X routines to update the LED dashboard display
 
  -- Turn on logging anytime the speed of the car is >10mph. Otherwise stop logging. 
    if getGpsSpeed() > 10 then
      startLogging()
    else
      stopLogging()
    end
 
  -- Check Input a and see if the brake lights have been pushed. if so, set a virtual channel to 1
  if getGpio(1) == 0 then
    setChannel(brake_status,0)
  else
    setChannel(brake_status,1)
  end
end

sxCanId = 0xE3600 + (256 * sxId)

setTickRate(tickRate)
sxInit()


View user's profile Send private message
Reply with quote
Post  
Why aren't you using the Alert LEDs to indicate the danger/warning status? Just trying to understand so I can create an alternative script for you.


_________________
--Paulo
View user's profile Send private message
Reply with quote
Post  
You may try the following script. It should do exactly the same thing as your own script (except for the Alert lights).

Please note you don't need the "brake status" channel, as it was the same thing as the Gpio(1) input, which is already logged anyway. You can just rename the Gpio channel in GUI (RCP APP).

If it works and crashes at some point, it's probably something else than a memory problem. If it doesn't work at all, I will re-check it.

Code:

sleep(5000)
setTickRate(10)

--Variables
local maxAvg, fuelAvg, fuel_damped_Index, RPM = 75, {}, 1, 0


--Channels
local fuel_damped, gearId


fuel_damped = addChannel("Fuel_Level", 10, 1, 0,12.6,"%")
gearId = addChannel("Gear",5)

--ShiftX2 txCAN function

local function sxTx(offset, data)
    txCAN(0, 0xE3600 + offset, 1, data)
    sleep(10)
end


--Fuel average function

local function updateFuelAvg(value)
    local sum, i = 0
    if #fuelAvg == 0 then
        --initialize averaging table
        for i = 1, maxAvg do fuelAvg[i]=0 end
    end
    fuelAvg[fuel_damped_Index] = value
    fuel_damped_Index = fuel_damped_Index + 1
    if fuel_damped_Index > maxAvg then fuel_damped_Index = 1 end
    for i = 1, #fuelAvg do
        sum = sum + fuelAvg[i]
    end
    setChannel(fuel_damped, sum / maxAvg)
end


-- Function check_gear updates the gear position - called every tick

local function check_gear()

    local TireDia, gearErr, rpmSpeedRatio, gearPos, speed = 23, 0.1, 0, 0, getGpsSpeed()

    if speed > 10 then
        --makes sure your rolling so as not to divide by 0
        rpmSpeedRatio = (RPM/speed)/(3.94*1056/(TireDia*3.14159))
        if ((3.54 - rpmSpeedRatio)^2) < (gearErr^2) then gearPos = 1 end
        if ((2.13 - rpmSpeedRatio)^2) < (gearErr^2) then gearPos = 2 end
        if ((1.36 - rpmSpeedRatio)^2) < (gearErr^2) then gearPos = 3 end
        if ((1.03 - rpmSpeedRatio)^2) < (gearErr^2) then gearPos = 4 end
        if ((0.81 - rpmSpeedRatio)^2) < (gearErr^2) then gearPos = 5 end
    else gearPos = 0 end
    setChannel(gearId, gearPos) --outputs to virtual channel
end




local function ShiftX2()

    --     Thresholds These are in here for convenience and must be updated in the code below
    --                                       Warning     Danger
    --     AN1 (Channel 0) = OIL PRESSURE     35          20    (PSI)
    --     AN2 (Channel 1) = TRANS TEMP       185         200   (Degrees F)
    --     AN3 (Channel 2) = OIL TEMP         220         250   (Degrees F)
    --     AN4 (Channel 3) = H20 TEMP         212         230   (Degrees F)

    -- Go get the readings from the analog gages for Oil pressure, Trans Temp, Oil Temp and coolant temp

    local Alert, oil_pressure, trans_temp, oil_temp, H20_temp, RPM_H, RPM_L = 1, getAnalog(0), getAnalog(1), getAnalog(2), getAnalog(3)

    -- Alert variable -> 1 = No problem; 2 = Warning; 3 = danger

    if (oil_pressure < 35 or trans_temp > 185 or oil_temp > 220 or H20_temp > 212) then Alert = 2 end
    if (oil_pressure < 20 or trans_temp > 200 or oil_temp > 250 or H20_temp > 230) then Alert = 3 end

    sxTx(22,{0,Alert,0})
    sxTx(22,{1,Alert,0})

    -- Update the linear graph with the current RPM

    RPM_L = RPM%256
    RPM_H = math.floor(RPM/256)
    sxTx(42, {RPM_L,RPM_H})

end

--config shift light
sxTx(40,{0,0,0,0,88,27}) -- RPM range -> 0 to 7000 (27*256 + 88)
sxTx(41,{0,0,184,11,0,255,0,0}) -- green at 3000 (11*256 + 184)
sxTx(41,{0,0,168,22,255,255,0,0}) -- yellow at 5800 (22*256 + 168)
sxTx(41,{0,0,56,24,255,0,0,10}) -- red+flash 6200 (24*256 + 56)

--config Alert Lights
sxTx(21,{0,0,1,0,0,255,0,0}) -- Green
sxTx(21,{0,1,2,0,255,255,0,0}) -- Yellow
sxTx(21,{0,2,3,0,255,0,0,10}) -- Flashing red

sxTx(21,{1,0,1,0,0,255,0,0}) -- Green
sxTx(21,{1,1,2,0,255,255,0,0}) -- Yellow
sxTx(21,{1,2,3,0,255,0,0,10}) -- Flashing red



-- Function onTick is the main loop for the program.
-- Ontick will call update fuel average to create a smoothed out fuel level

function onTick()

    collectgarbage() -- This deletes objects in LUA that are unsuable

    updateFuelAvg(getAnalog(4))-- call the fuel average routine and pass it the current fuel tank reading to smooth out.

    RPM = getTimerRpm(0)

    check_gear()  -- call the routine that checks to see what gear we are in

    ShiftX2()  --  Process the shift-2X routines to update the LED dashboard display

    -- Turn on logging anytime the speed of the car is >10mph. Otherwise stop logging.

    if getGpsSpeed() > 10 then
        startLogging()
    else
        stopLogging()
    end

end





_________________
--Paulo
View user's profile Send private message
Reply with quote
Post Looking for help with out of memory errors 
Paulo,

Thanks for your response. I originally started using the ShifX2 Alert routines but I quickly began to run into memory errors (the program would run for a brief period of time and then go into Disco Light mode).

I tried simply turning on the end LEDS manually in the event of a warning/danger and then used the center LEDs for the RPM indicator. My intent was to eventually eliminate the various Shift2X routines that I wasn't using to try to save memory. Someone else on here was suggesting that.

We LOVE the Shift2X - it's completely changed the way we drive. Basically our implementation of it is drop-dead simple - we only use the center LEDs for the RPM gage and simply light up the LEDs on the end if any of the gages we are tracking go into warning or danger mode. In this way, during a race, the driver only has to look at the Shift2X. If the end LEDs go yellow or begin blinking red he can then turn to the Android tablet and see which gage is of concern.

It's made driving much simpler and the driver can focus on driving without having to worry about constantly checking gages. We had a few instances of drivers missing overheating transmission temps just because they were so focused on driving. With the Shift2X that hasn't been an issue. The problem is that when we added in the Shift2X we almost immediately began to get our of memory errors.

So far we've been able to solve the errors by eliminating the gear and brake checking which is a shame because we'd like to log this for telemetry.

It seems like the canned routines for the Shift2X take tremendous amounts of memory - based on what others have said I don't think we're the only ones with this issue.

I can try your routine - but again I think the problem is an out-of-memory one. The program will run fine for a short period of time and then I get disco lights.

If Brent is monitoring this -

- Is my assumption that our problem is the size of the included Shift2X routines or something else?
- Is there any way to strip down this size of these routines?
- Is there any way to check and see how much memory your program is consuming and what the limit of LUA is so you definitively know if you have a problem before starting a race?

Sorry if my approach and questions are dumb - I'm not very good at LUA or programming.

Again - we think the Shift2X is an awesome product - one of the best investments we've made as it really allows the driver to focus on driving and not on the gages. But right now it comes at the expense of some of the other telemetry we'd live to log which is a shame.

Dave

View user's profile Send private message
Reply with quote
Post  
Yes, you can see I reduced the number of ShiftX2 scripts from 15 (or so) to only 1 (kept sxTx). This way you shouldn't have any memory issues. Believe me, my personal script is much bigger and more complex and I don't have issues even when I run RCP continuously for hours. If the script runs (I didn't test it) and you have problems after some time, it must be something else, like a script error when a variable doesn't receive the expected data type (for exemple, it receives "null" and there is another operation that will only work with numbers).


_________________
--Paulo
View user's profile Send private message
Display posts from previous:
Reply to topic Page 1 of 1
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum
You cannot attach files in this forum
You cannot download files in this forum