can

CAN bus interface: initialise the bus, receive frames with a callback, and transmit standard or extended frames.

Available on: Flexs Q5 Pro

The can object connects the device to a CAN bus. Initialise the bus with a data rate, register a receive handler, and transmit frames with can.tx() — including extended IDs, CAN FD and remote (RTR) frames.

Functions

can.init()

can.init(dataRate, canFD, autoRetransmit)

Initialises the CAN bus interface.

Arguments

NameTypeRequiredDefaultDescription
dataRate number (kbps) yes Bus data rate in kbps, e.g. 125, 250, 500.
canFD boolean yes Enable CAN FD framing.
autoRetransmit boolean yes Enable automatic retransmission.

Example

can.init(125, false, false); // 125 kbps, classic CAN, no auto retransmission

can.listen()

can.listen(callback)

Registers a receive handler for incoming CAN frames.

The callback receives a message object with the frame id and data payload. Decode binary payloads with the bin functions.

Arguments

NameTypeRequiredDefaultDescription
callback function yes Callback function(msg){ … }msg = { id, data }.

Example

can.listen(function(msg){
  print(string(msg)); // {"id":164242,"data":"hello from canbus"}
});

can.tx()

can.tx(id, payload, extendedId, canFD, remoteFrame)

Transmits a CAN frame.

Arguments

NameTypeRequiredDefaultDescription
id number yes Frame identifier.
payload string yes Frame payload — pack binary data with the bin functions.
extendedId boolean yes true for a 29-bit extended identifier.
canFD boolean yes true to send as a CAN FD frame.
remoteFrame boolean yes true to send a remote (RTR) frame.

Example

can.tx(
  12,             // id
  "Test Payload", // payload
  false,          // extended id
  false,          // canFD
  false           // remote frame (RTR)
);