2.5. can — CAN bus

A Controller Area Network (CAN bus) is a vehicle bus standard designed to allow microcontrollers and devices to communicate with each other in applications without a host computer. It is a message-based protocol, designed originally for multiplex electrical wiring within automobiles, but is also used in many other contexts.

Below is a short example of how to use this module. The error handling is left out for readability.

struct can_frame_t can_rx_buf[8];
struct can_frame_t frame;

/* Initialize and start the CAN conroller. */
can_init(&can,
         &can_device[0],
         CAN_SPEED_500KBPS,
         can_rx_buf,
         sizeof(can_rx_buf)) == 0);
can_start(&can);

/* Read a frame from the bus. */
can_read(&can, &frame, sizeof(frame));

/* Stop the CAN controller. */
can_stop(&can);

Source code: src/drivers/can.h, src/drivers/can.c

Test code: tst/drivers/can/main.c


Defines

CAN_SPEED_1000KBPS
CAN_SPEED_500KBPS
CAN_SPEED_250KBPS

Functions

int can_init(struct can_driver_t *self_p, struct can_device_t *dev_p, uint32_t speed, void *rxbuf_p, size_t size)

Initialize given driver object from given configuration.

Return
zero(0) or negative error code.
Parameters
  • self_p: Driver object to initialize.
  • dev_p: CAN device to use.
  • speed: Can bus speed. One of the defines with the prefixCAN_SPEED_.
  • rxbuf_p: CAN frame reception buffer.
  • size: Size of the reception buffer in bytes.

int can_start(struct can_driver_t *self_p)

Starts the CAN device using configuration in given driver object.

Return
zero(0) or negative error code.
Parameters
  • self_p: Initialized driver object.

int can_stop(struct can_driver_t *self_p)

Stops the CAN device referenced by given driver object.

Return
zero(0) or negative error code.
Parameters
  • self_p: Initialized driver object.

ssize_t can_read(struct can_driver_t *self_p, struct can_frame_t *frame_p, size_t size)

Read one or more CAN frames from the CAN bus. Blocks until the frame(s) are received.

Return
Number of bytes read or negative error code.
Parameters
  • self_p: Initialized driver object.
  • frame_p: Array of read frames.
  • size: Size of frames buffer in bytes. Must be a multiple of sizeof(struct can_frame_t).

ssize_t can_write(struct can_driver_t *self_p, const struct can_frame_t *frame_p, size_t size)

Write one or more CAN frames to the CAN bus. Blocks until the frame(s) have been transmitted.

Return
Number of bytes written or negative error code.
Parameters
  • self_p: Initialized driver object.
  • frame_p: Array of frames to write.
  • size: Size of frames buffer in bytes. Must be a multiple of sizeof(struct can_frame_t).

Variables

struct can_device_t can_device[CAN_DEVICE_MAX]
struct can_frame_t

Public Members

uint32_t id
int extended_frame
int size
int rtr
uint32_t timestamp
uint8_t u8[8]
uint32_t u32[2]
union can_frame_t::@0 can_frame_t::data