1.. _can_api:
2
3Controller Area Network (CAN)
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
19A CAN transceiver is an external device that converts the logic level signals
20from the CAN controller to the bus-levels. The bus lines are called
21CAN High (CAN H) and CAN Low (CAN L).
22The transmit wire from the controller to the transceiver is called CAN TX,
23and the receive wire is called CAN RX.
24These wires use the logic levels whereas the bus-level is interpreted
25differentially between CAN H and CAN L.
26The bus can be either in the recessive (logical one) or dominant (logical zero)
27state. The recessive state is when both lines, CAN H and CAN L, at roughly at
28the same voltage level. This state is also the idle state.
29To write a dominant bit to the bus, open-drain transistors tie CAN H to Vdd
30and CAN L to ground.
31The first and last node use a 120-ohm resistor between CAN H and CAN L to
32terminate the bus. The dominant state always overrides the recessive state.
33This structure is called a wired-AND.
34
35.. warning::
36
37   CAN controllers can only initialize when the bus is in the idle (recessive)
38   state for at least 11 recessive bits. Therefore you have to make sure that
39   CAN RX is high, at least for a short time. This is also necessary for
40   loopback mode.
41
42.. image:: can_transceiver.svg
43   :width: 70%
44   :align: center
45   :alt: CAN Transceiver
46
47
48The bit-timing as defined in ISO 11898-1:2003 looks as following:
49
50.. image:: can_timing.svg
51   :width: 40%
52   :align: center
53   :alt: CAN Timing
54
55A single bit is split into four segments.
56
57* Sync_Seg: The nodes synchronize at the edge of the Sync_Seg. It is always one time quantum in length.
58
59* Prop_Seg: The signal propagation delay of the bus and other delays of the transceiver and node.
60
61* Phase_Seg1 and Phase_Seg2 :Define the sampling point. The bit is sampled at the end of Phase_Seg1.
62
63The bit-rate is calculated from the time of a time quantum and the values
64defined above.
65A bit has the length of Sync_Seg plus Prop_Seg plus Phase_Seg1 plus Phase_Seg2
66multiplied by the time of single time quantum.
67The bit-rate is the inverse of the length of a single bit.
68
69A bit is sampled at the sampling point.
70The sample point is between Phase_Seg1 and PhaseSeg2 and therefore is a
71parameter that the user needs to choose.
72The CiA recommends setting the sample point to 87.5% of the bit.
73
74The resynchronization jump width (SJW) defines the amount of time quantum the
75sample point can be moved.
76The sample point is moved when resynchronization is needed.
77
78The timing parameters (SJW, bitrate and sampling point, or bitrate, Prop_Seg,
79Phase_Seg1and Phase_Seg2) are initially set from the device-tree and can be
80changed at run-time from the timing-API.
81
82CAN uses so-called identifiers to identify the frame instead of addresses to
83identify a node.
84This identifier can either have 11-bit width (Standard or Basic Frame) or
8529-bit in case of an Extended Frame. The Zephyr CAN API supports both Standard
86and Extended identifiers concurrently. A CAN frame starts with a dominant
87Start Of Frame bit. After that, the identifiers follow. This phase is called the
88arbitration phase. During the arbitration phase, write collisions are allowed.
89They resolve by the fact that dominant bits override recessive bits.
90Nodes monitor the bus and notice when their transmission is being overridden and
91in case, abort their transmission.
92This effectively gives lower number identifiers priority over higher number
93identifiers.
94
95Filters are used to whitelist identifiers that are of interest for the specific
96node. An identifier that doesn't match any filter is ignored.
97Filters can either match exactly or a specified part of the identifier.
98This method is called masking.
99As an example, a mask with 11 bits set for standard or 29 bits set for extended
100identifiers must match perfectly.
101Bits that are set to zero in the mask are ignored when matching an identifier.
102Most CAN controllers implement a limited number of filters in hardware.
103The number of filters is also limited in Kconfig to save memory.
104
105Errors may occur during transmission. In case a node detects an erroneous frame,
106it partially overrides the current frame with an error-frame.
107Error-frames can either be error passive or error active, depending on the state
108of the controller.
109In case the controller is in error active state, it sends six consecutive
110dominant bits, which is a violation of the stuffing rule that all nodes can
111detect. The sender may resend the frame right after.
112
113An initialized node can be in one of the following states:
114
115* Error-active
116* Error-passive
117* Bus-off
118
119After initialization, the node is in the error-active state. In this state, the
120node is allowed to send active error frames, ACK, and overload frames.
121Every node has a receive- and transmit-error counter.
122If either the receive- or the transmit-error counter exceeds 127,
123the node changes to error-passive state.
124In this state, the node is not allowed to send error-active frames anymore.
125If the transmit-error counter increases further to 255, the node changes to the
126bus-off state. In this state, the node is not allowed to send any dominant bits
127to the bus. Nodes in the bus-off state may recover after receiving 128
128occurrences of 11 concurrent recessive bits.
129
130You can read more about CAN bus in this
131`CAN Wikipedia article <https://en.wikipedia.org/wiki/CAN_bus>`_.
132
133Zephyr supports following CAN features:
134
135* Standard and Extended Identifers
136* Filters with Masking
137* Loopback and Silent mode
138* Remote Request
139
140Sending
141*******
142
143The following code snippets show how to send data.
144
145
146This basic sample sends a CAN frame with standard identifier 0x123 and eight
147bytes of data. When passing NULL as the callback, as shown in this example,
148the send function blocks until the frame is sent and acknowledged by at least
149one other node or an error occurred. The timeout only takes effect on acquiring
150a mailbox. When a transmitting mailbox is assigned, sending cannot be canceled.
151
152.. code-block:: C
153
154  struct zcan_frame frame = {
155          .id_type = CAN_STANDARD_IDENTIFIER,
156          .rtr = CAN_DATAFRAME,
157          .id = 0x123,
158          .dlc = 8,
159          .data = {1,2,3,4,5,6,7,8}
160  };
161  const struct device *can_dev;
162  int ret;
163
164  can_dev = device_get_binding("CAN_0");
165
166  ret = can_send(can_dev, &frame, K_MSEC(100), NULL, NULL);
167  if (ret != CAN_TX_OK) {
168          LOG_ERR("Sending failed [%d]", ret);
169  }
170
171
172This example shows how to send a frame with extended identifier 0x1234567 and
173two bytes of data. The provided callback is called when the message is sent, or
174an error occurred. Passing :c:macro:`K_FOREVER` to the timeout causes the
175function to block until a transfer mailbox is assigned to the frame or an error
176occurred. It does not block until the message is sent like the example above.
177
178.. code-block:: C
179
180  void tx_irq_callback(int error, void *arg)
181  {
182          char *sender = (char *)arg;
183
184          if (error != 0) {
185                  LOG_ERR("Sendig failed [%d]\nSender: %s\n", error, sender);
186          }
187  }
188
189  int send_function(const struct device *can_dev)
190  {
191          struct zcan_frame frame = {
192                  .id_type = CAN_EXTENDED_IDENTIFIER,
193                  .rtr = CAN_DATAFRAME,
194                  .id = 0x1234567,
195                  .dlc = 2
196          };
197
198          frame.data[0] = 1;
199          frame.data[1] = 2;
200
201          return can_send(can_dev, &frame, K_FOREVER, tx_irq_callback, "Sender 1");
202  }
203
204Receiving
205*********
206
207Frames are only received when they match a filter.
208The following code snippets show how to receive frames by attaching filters.
209
210Here we have an example for a receiving callback.
211It is used for `can_attach_isr` or `can_attach_workq`.
212The argument arg is passed when the filter is attached.
213
214.. code-block:: C
215
216  void rx_callback_function(struct zcan_frame *frame, void *arg)
217  {
218          ... do something with the frame ...
219  }
220
221The following snippet shows how to attach a filter with an interrupt callback.
222It is the most efficient but also the most critical way to receive messages.
223The callback function is called from an interrupt context, which means that the
224callback function should be as short as possible and must not block.
225Attaching ISRs is not allowed from userspace context.
226
227The filter for this example is configured to match the identifier 0x123 exactly.
228
229.. code-block:: C
230
231  const struct zcan_filter my_filter = {
232          .id_type = CAN_STANDARD_IDENTIFIER,
233          .rtr = CAN_DATAFRAME,
234          .id = 0x123,
235          .rtr_mask = 1,
236          .id_mask = CAN_STD_ID_MASK
237  };
238  int filter_id;
239  const struct device *can_dev;
240
241  can_dev = device_get_binding("CAN_0");
242
243  filter_id = can_attach_isr(can_dev, rx_callback_function, callback_arg, &my_filter);
244  if (filter_id < 0) {
245    LOG_ERR("Unable to attach isr [%d]", filter_id);
246  }
247
248This example shows how to attach a callback from a work-queue.
249In contrast to the `can_attach_isr` function, here the callback is called from the
250work-queue provided. In this case, it is the system work queue. Blocking is
251generally allowed in the callback but could result in a frame backlog when it is
252not limited. For the reason of a backlog, a ring-buffer is applied for every
253attached filter. The size of this buffer can be adjusted in Kconfig.
254This function is not yet callable from userspace context but will be in the
255future.
256
257The filter for this example is configured to match a filter range from
2580x120 to x12f.
259
260.. code-block:: C
261
262  const struct zcan_filter my_filter = {
263          .id_type = CAN_STANDARD_IDENTIFIER,
264          .rtr = CAN_DATAFRAME,
265          .id = 0x120,
266          .rtr_mask = 1,
267          .id_mask = 0x7F0
268  };
269  struct zcan_work rx_work;
270  int filter_id;
271  const struct device *can_dev;
272
273  can_dev = device_get_binding("CAN_0");
274
275  filter_id = can_attach_workq(can_dev, &k_sys_work_q, &rx_work, callback_arg, callback_arg, &my_filter);
276  if (filter_id < 0) {
277    LOG_ERR("Unable to attach isr [%d]", filter_id);
278  }
279
280Here an example for `can_attach_msgq` is shown. With this function, it is
281possible to receive frames synchronously. This function can be called from
282userspace context.
283The size of the message queue should be as big as the expected backlog.
284
285The filter for this example is configured to match the extended identifier
2860x1234567 exactly.
287
288.. code-block:: C
289
290  const struct zcan_filter my_filter = {
291          .id_type = CAN_EXTENDED_IDENTIFIER,
292          .rtr = CAN_DATAFRAME,
293          .id = 0x1234567,
294          .rtr_mask = 1,
295          .id_mask = CAN_EXT_ID_MASK
296  };
297  CAN_DEFINE_MSGQ(my_can_msgq, 2);
298  struct zcan_frame rx_frame;
299  int filter_id;
300  const struct device *can_dev;
301
302  can_dev = device_get_binding("CAN_0");
303
304  filter_id = can_attach_msgq(can_dev, &my_can_msgq, &my_filter);
305  if (filter_id < 0) {
306    LOG_ERR("Unable to attach isr [%d]", filter_id);
307    return;
308  }
309
310  while (true) {
311    k_msgq_get(&my_can_msgq, &rx_frame, K_FOREVER);
312    ... do something with the frame ...
313  }
314
315`can_detach` removes the given filter.
316
317.. code-block:: C
318
319  can_detach(can_dev, filter_id);
320
321Setting the bitrate
322*******************
323
324The bitrate and sampling point is initially set at runtime. To change it from
325the application, one can use the `can_set_timing` API. This function takes three
326arguments. The first timing parameter sets the timing for classic CAN and
327arbitration phase for CAN-FD. The second parameter sets the timing of the data
328phase for CAN-FD. For classic CAN, you can use only the first parameter and put
329NULL to the second one. The `can_calc_timing` function can calculate timing from
330a bitrate and sampling point in permille. The following example sets the bitrate
331to 250k baud with the sampling point at 87.5%.
332
333.. code-block:: C
334
335  struct can_timing timing;
336  const struct device *can_dev;
337  int ret;
338
339  can_dev = device_get_binding("CAN_0");
340
341  ret = can_calc_timing(can_dev, &timing, 250000, 875);
342  if (ret > 0) {
343    LOG_INF("Sample-Point error: %d", ret);
344  }
345
346  if (ret < 0) {
347    LOG_ERR("Failed to calc a valid timing");
348    return;
349  }
350
351  ret = can_set_timing(can_dev, &timing, NULL);
352  if (ret != 0) {
353    LOG_ERR("Failed to set timing");
354  }
355
356SocketCAN
357*********
358
359Zephyr additionally supports SocketCAN, a BSD socket implementation of the
360Zephyr CAN API.
361SocketCAN brings the convenience of the well-known BSD Socket API to
362Controller Area Networks. It is compatible with the Linux SocketCAN
363implementation, where many other high-level CAN projects build on top.
364Note that frames are routed to the network stack instead of passed directly,
365which adds some computation and memory overhead.
366
367Samples
368*******
369
370We have two ready-to-build samples demonstrating use of the Zephyr CAN API
371:ref:`Zephyr CAN sample <can-sample>` and
372:ref:`SocketCAN sample <socket-can-sample>`.
373
374
375API Reference
376*************
377
378.. doxygengroup:: can_interface
379