ENP-CAN
can
library implements CAN bus communication for the ENP-CAN module.
can.init
-- @param baud_rate number Baud rate in kbps, values: 1000, 800, 500, 250, 100
-- @param can_handler function Handler of incoming CAN packets
-- @return number
function can.init(baud_rate, can_handler)
end
-- @param msg_id number CAN message ID
-- @param data string CAN data frame, up to 8 bytes
function can_handler(msg_id, data)
end
Initializes hardware for CAN communication. Must be called before any other communication function.
baudrate
should be provided in kbps with value options: 1000
,800
, 500
, 250
, 100
.
Optional handler
function can be provided. It will be called every time a CAN packet is received. The function must receive CAN message ID as the first argument and string as the second argument, it will contain CAN data frame (up to 8 bytes), see example below.
Returns 0
if initialization is performed successfully, otherwise returns error code (use can.err_to_str
to convert it to string representation).
Example
function can_handler(msg_id, data)
bytes = { string.byte(data, 1, -1) } -- convert to array of bytes
enapter.log("CAN frame received: " .. tostring(msg_id) .. "[" .. table.concat(bytes) .. "]")
if msg_id == 0x01D0 then
enapter.log("Sensor data: " .. bytes[1]) -- interpret first byte as a sensor value
end
end
result = can.init(500, can_handler)
if result ~= 0 then
enapter.log("CAN failed: "..result.." "..can.err_to_str(result), "error", true)
end
can.send
-- @param msg_id number CAN message ID
-- @param data string CAN data frame, up to 8 bytes
-- @return number
function can.send(msg_id, data)
end
Sends CAN frame to CAN bus. Data must be a string of up to 8 bytes.
Returns 0
if data was sent successfully, otherwise returns error code (use can.err_to_str
to convert it to string representation).
Example
data = string.pack("I1I1", 58, 92) -- pack two 1 byte values
result = can.send(0x01D0, data)
if result ~= 0 then
enapter.log("Sending CAN frame failed: "..result.." "..can.err_to_str(result), "error", true)
end
can.err_to_str
-- @param error number
-- @return string
function can.err_to_str(error)
end
Returns string representation of can
function return code.