lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


Hi,

I'm running lua 5.1.3 on a Linux 2.6 uClibc system.

My Lua script writes to an SPI driver 256 bytes at a time. Unfortunately the 
time it takes to get the 256 bytes to the driver is almost 2 seconds! 

I need this to write about 2MB of data in total, so this rate is unfortunately 
not acceptable.

Please have a look below at a description of the script. Am I doing too much 
memory copying? Or could it be something else?

I think memory copying happens when-

-In step 2, when the 2MB is broken into 256 byte chunks
-In step 3, when a new string is effectively created because of the 
concatenation
-In step 4, the explicit memcopy()

Cheers,
Daniel


This is what happens in the script:

1) The entire 2MB is read in one go from a file-

local dataIn = file:read("*all")


2) Each 256-byte chunk of the 2MB is then passed to a 'pageProgram()'-

local block = 256
local i = 0

while true do
  local bytes = string.sub(dataIn, (i+1), (i+block))
  pageProgram(address, dataAddress, bytes)
  i = i + block
  if i > #dataIn then break end
 .
 .
 .


3) pageProgram() constructs the SPI Message to be passed to the driver:

 local spiMessage = write_format(true, PP, dataAddress[1], dataAddress[2], 
dataAddress[3]) .. data

-- write_format() has been adapted from:
-- http://lua-users.org/wiki/ReadWriteFormat

4) pageProgram() then calls a C library function to interact with the driver:

int l_spiExchangeBytes(lua_State *L)
{
 //The first and second input params deal with basic mangling of the SPI 
Address.
 .
 .
 .
  //The third input parameter is the Data (represented by a Lua String):
  dataIn = (BYTE*) luaL_checkstring(L, 3);
  
  count = lua_objlen(L, 3); 

  data = (BYTE*) malloc( (sizeof(BYTE)) * count );

  //dataIn is a const, so we must memcpy:
  if(memcpy(data, dataIn, count) == NULL)
  {
   ...
  }


 .
 .
 .
 // data is then passed to the SPI driver. 
 // (note that the memcopy is required because the SPI driver will
 // use the same buffer to write back a result, therefore the 
 // buffer must NOT be a const.)