I've been using http://www.lua.org/cgi-bin/demo to test lua code and I've got something that works there, but when trying it on the RCP, the script crashes (red light, script doesn't run). I'm a lua noob, so perhaps I'm using some functions that work in the demo site, but not on the controller. Anyway, here's the code:
Code: Select all
--Take 8 bytes of CAN Data and return a decimal value
--Inputs: 8 bytes of data, start bit, length in bits
function CANbytes2dec(CAN_data,start_bit, length_bits)
function toBits(num,bits)
local numf = num
local bitsf = bits
local t={} -- will contain the bits
for b=bitsf,1,-1 do
if numf % 2 == 0 then
t[b]=0;
else
t[b]=1;
end
numf=(numf-t[b])/2
end
return t
end
--inputs: starting bit and bit length, multiplier and offset
--output: Value in decimal for variable
--given: function for turning decimal values into bits
local end_bit = start_bit + length_bits - 1
--create an array of 1's and 0's for whether each
--byte is part of the message
--create a local variable and replace it each
--time the function for dec2bin is called
local var_bits = {}
local count_bits = 0;
for i = 1,8,1 do
--check if byte is included and bits are left to be added
if ((i*8+1)> start_bit) and (count_bits < length_bits) then
local bits_from_dec = {}
bits_from_dec = toBits(CAN_data[i],8)
for j=1,8,1 do
if ((i-1)*8+j>=start_bit) and ((i-1)*8+j<=end_bit) then
count_bits = count_bits+1;
var_bits[count_bits] = bits_from_dec[j];
end
end
end
end
--take bits and convert to raw decimal value by multiplying by 2^x
local dec_val_raw = 0
local sum_bit = 0;
for n = count_bits,1,-1 do
sum_bit = sum_bit+1;
dec_val_raw = dec_val_raw + var_bits[sum_bit]*2^(n-1);
end
return dec_val_raw
end
local Test_CAN_Data = {147, 231, 125, 145, 68, 129, 146, 228}
local test_start_bit = 6
local test_length_bits = 10
function onTick()
dec_val_test = CANbytes2dec(Test_CAN_Data,test_start_bit, test_length_bits)
print(dec_val_test)
end
--onTick() <- remove this comment to run on demo page