1.. _can_api:
2
3CAN Controller
4##############
5
6.. contents::
7    :local:
8    :depth: 2
9
10Overview
11********
12
13Controller Area Network is a two-wire serial bus specified by the
14Bosch CAN Specification, Bosch CAN with Flexible Data-Rate specification and the
15ISO 11898-1:2003 standard.
16CAN is mostly known for its application in the automotive domain. However, it
17is also used in home and industrial automation and other products.
18
19.. warning::
20
21   CAN controllers can only initialize when the bus is in the idle (recessive)
22   state for at least 11 recessive bits. Therefore you have to make sure that
23   CAN RX is high, at least for a short time. This is also necessary for
24   loopback mode.
25
26The bit-timing as defined in ISO 11898-1:2003 looks as following:
27
28.. image:: timing.svg
29   :width: 40%
30   :align: center
31   :alt: CAN Timing
32
33A single bit is split into four segments.
34
35* Sync_Seg: The nodes synchronize at the edge of the Sync_Seg. It is always one time quantum in length.
36
37* Prop_Seg: The signal propagation delay of the bus and other delays of the transceiver and node.
38
39* Phase_Seg1 and Phase_Seg2 :Define the sampling point. The bit is sampled at the end of Phase_Seg1.
40
41The bit-rate is calculated from the time of a time quantum and the values
42defined above.
43A bit has the length of Sync_Seg plus Prop_Seg plus Phase_Seg1 plus Phase_Seg2
44multiplied by the time of single time quantum.
45The bit-rate is the inverse of the length of a single bit.
46
47A bit is sampled at the sampling point.
48The sample point is between Phase_Seg1 and PhaseSeg2 and therefore is a
49parameter that the user needs to choose.
50The CiA recommends setting the sample point to 87.5% of the bit.
51
52The resynchronization jump width (SJW) defines the amount of time quantum the
53sample point can be moved.
54The sample point is moved when resynchronization is needed.
55
56The timing parameters (SJW, bitrate and sampling point, or bitrate, Prop_Seg,
57Phase_Seg1and Phase_Seg2) are initially set from the device-tree and can be
58changed at run-time from the timing-API.
59
60CAN uses so-called identifiers to identify the frame instead of addresses to
61identify a node.
62This identifier can either have 11-bit width (Standard or Basic Frame) or
6329-bit in case of an Extended Frame. The Zephyr CAN API supports both Standard
64and Extended identifiers concurrently. A CAN frame starts with a dominant
65Start Of Frame bit. After that, the identifiers follow. This phase is called the
66arbitration phase. During the arbitration phase, write collisions are allowed.
67They resolve by the fact that dominant bits override recessive bits.
68Nodes monitor the bus and notice when their transmission is being overridden and
69in case, abort their transmission.
70This effectively gives lower number identifiers priority over higher number
71identifiers.
72
73Filters are used to whitelist identifiers that are of interest for the specific
74node. An identifier that doesn't match any filter is ignored.
75Filters can either match exactly or a specified part of the identifier.
76This method is called masking.
77As an example, a mask with 11 bits set for standard or 29 bits set for extended
78identifiers must match perfectly.
79Bits that are set to zero in the mask are ignored when matching an identifier.
80Most CAN controllers implement a limited number of filters in hardware.
81The number of filters is also limited in Kconfig to save memory.
82
83Errors may occur during transmission. In case a node detects an erroneous frame,
84it partially overrides the current frame with an error-frame.
85Error-frames can either be error passive or error active, depending on the state
86of the controller.
87In case the controller is in error active state, it sends six consecutive
88dominant bits, which is a violation of the stuffing rule that all nodes can
89detect. The sender may resend the frame right after.
90
91An initialized node can be in one of the following states:
92
93* Error-active
94* Error-passive
95* Bus-off
96
97After initialization, the node is in the error-active state. In this state, the
98node is allowed to send active error frames, ACK, and overload frames.
99Every node has a receive- and transmit-error counter.
100If either the receive- or the transmit-error counter exceeds 127,
101the node changes to error-passive state.
102In this state, the node is not allowed to send error-active frames anymore.
103If the transmit-error counter increases further to 255, the node changes to the
104bus-off state. In this state, the node is not allowed to send any dominant bits
105to the bus. Nodes in the bus-off state may recover after receiving 128
106occurrences of 11 concurrent recessive bits.
107
108You can read more about CAN bus in this
109`CAN Wikipedia article <https://en.wikipedia.org/wiki/CAN_bus>`_.
110
111Zephyr supports following CAN features:
112
113* Standard and Extended Identifiers
114* Filters with Masking
115* Loopback and Silent mode
116* Remote Request
117
118Sending
119*******
120
121The following code snippets show how to send data.
122
123
124This basic sample sends a CAN frame with standard identifier 0x123 and eight
125bytes of data. When passing NULL as the callback, as shown in this example,
126the send function blocks until the frame is sent and acknowledged by at least
127one other node or an error occurred. The timeout only takes effect on acquiring
128a mailbox. When a transmitting mailbox is assigned, sending cannot be canceled.
129
130.. code-block:: C
131
132  struct can_frame frame = {
133          .flags = 0,
134          .id = 0x123,
135          .dlc = 8,
136          .data = {1,2,3,4,5,6,7,8}
137  };
138  const struct device *const can_dev = DEVICE_DT_GET(DT_CHOSEN(zephyr_canbus));
139  int ret;
140
141  ret = can_send(can_dev, &frame, K_MSEC(100), NULL, NULL);
142  if (ret != 0) {
143          LOG_ERR("Sending failed [%d]", ret);
144  }
145
146
147This example shows how to send a frame with extended identifier 0x1234567 and
148two bytes of data. The provided callback is called when the message is sent, or
149an error occurred. Passing :c:macro:`K_FOREVER` to the timeout causes the
150function to block until a transfer mailbox is assigned to the frame or an error
151occurred. It does not block until the message is sent like the example above.
152
153.. code-block:: C
154
155  void tx_callback(const struct device *dev, int error, void *user_data)
156  {
157          char *sender = (char *)user_data;
158
159          if (error != 0) {
160                  LOG_ERR("Sending failed [%d]\nSender: %s\n", error, sender);
161          }
162  }
163
164  int send_function(const struct device *can_dev)
165  {
166          struct can_frame frame = {
167                  .flags = CAN_FRAME_IDE,
168                  .id = 0x1234567,
169                  .dlc = 2
170          };
171
172          frame.data[0] = 1;
173          frame.data[1] = 2;
174
175          return can_send(can_dev, &frame, K_FOREVER, tx_callback, "Sender 1");
176  }
177
178Receiving
179*********
180
181Frames are only received when they match a filter.
182The following code snippets show how to receive frames by adding filters.
183
184Here we have an example for a receiving callback as used for
185:c:func:`can_add_rx_filter`. The user data argument is passed when the filter is
186added.
187
188.. code-block:: C
189
190  void rx_callback_function(const struct device *dev, struct can_frame *frame, void *user_data)
191  {
192          ... do something with the frame ...
193  }
194
195The following snippet shows how to add a filter with a callback function.
196It is the most efficient but also the most critical way to receive messages.
197The callback function is called from an interrupt context, which means that the
198callback function should be as short as possible and must not block.
199Adding callback functions is not allowed from userspace context.
200
201The filter for this example is configured to match the identifier 0x123 exactly.
202
203.. code-block:: C
204
205  const struct can_filter my_filter = {
206          .flags = 0U,
207          .id = 0x123,
208          .mask = CAN_STD_ID_MASK
209  };
210  int filter_id;
211  const struct device *const can_dev = DEVICE_DT_GET(DT_CHOSEN(zephyr_canbus));
212
213  filter_id = can_add_rx_filter(can_dev, rx_callback_function, callback_arg, &my_filter);
214  if (filter_id < 0) {
215    LOG_ERR("Unable to add rx filter [%d]", filter_id);
216  }
217
218Here an example for :c:func:`can_add_rx_filter_msgq` is shown. With this
219function, it is possible to receive frames synchronously. This function can be
220called from userspace context.  The size of the message queue should be as big
221as the expected backlog.
222
223The filter for this example is configured to match the extended identifier
2240x1234567 exactly.
225
226.. code-block:: C
227
228  const struct can_filter my_filter = {
229          .flags = CAN_FILTER_IDE,
230          .id = 0x1234567,
231          .mask = CAN_EXT_ID_MASK
232  };
233  CAN_MSGQ_DEFINE(my_can_msgq, 2);
234  struct can_frame rx_frame;
235  int filter_id;
236  const struct device *const can_dev = DEVICE_DT_GET(DT_CHOSEN(zephyr_canbus));
237
238  filter_id = can_add_rx_filter_msgq(can_dev, &my_can_msgq, &my_filter);
239  if (filter_id < 0) {
240    LOG_ERR("Unable to add rx msgq [%d]", filter_id);
241    return;
242  }
243
244  while (true) {
245    k_msgq_get(&my_can_msgq, &rx_frame, K_FOREVER);
246    ... do something with the frame ...
247  }
248
249:c:func:`can_remove_rx_filter` removes the given filter.
250
251.. code-block:: C
252
253  can_remove_rx_filter(can_dev, filter_id);
254
255Setting the bitrate
256*******************
257
258The bitrate and sampling point is initially set at runtime. To change it from
259the application, one can use the :c:func:`can_set_timing` API. The :c:func:`can_calc_timing`
260function can calculate timing from a bitrate and sampling point in permille.
261The following example sets the bitrate to 250k baud with the sampling point at
26287.5%.
263
264.. code-block:: C
265
266  struct can_timing timing;
267  const struct device *const can_dev = DEVICE_DT_GET(DT_CHOSEN(zephyr_canbus));
268  int ret;
269
270  ret = can_calc_timing(can_dev, &timing, 250000, 875);
271  if (ret > 0) {
272    LOG_INF("Sample-Point error: %d", ret);
273  }
274
275  if (ret < 0) {
276    LOG_ERR("Failed to calc a valid timing");
277    return;
278  }
279
280  ret = can_stop(can_dev);
281  if (ret != 0) {
282    LOG_ERR("Failed to stop CAN controller");
283  }
284
285  ret = can_set_timing(can_dev, &timing);
286  if (ret != 0) {
287    LOG_ERR("Failed to set timing");
288  }
289
290  ret = can_start(can_dev);
291  if (ret != 0) {
292    LOG_ERR("Failed to start CAN controller");
293  }
294
295A similar API exists for calculating and setting the timing for the data phase for CAN FD capable
296controllers. See :c:func:`can_set_timing_data` and :c:func:`can_calc_timing_data`.
297
298SocketCAN
299*********
300
301Zephyr additionally supports SocketCAN, a BSD socket implementation of the
302Zephyr CAN API.
303SocketCAN brings the convenience of the well-known BSD Socket API to
304Controller Area Networks. It is compatible with the Linux SocketCAN
305implementation, where many other high-level CAN projects build on top.
306Note that frames are routed to the network stack instead of passed directly,
307which adds some computation and memory overhead.
308
309Samples
310*******
311
312We have two ready-to-build samples demonstrating use of the Zephyr CAN API:
313:zephyr:code-sample:`Zephyr CAN counter sample <can-counter>` and
314:zephyr:code-sample:`SocketCAN sample <socket-can>`.
315
316
317CAN Controller API Reference
318****************************
319
320.. doxygengroup:: can_interface
321