can.rst 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604
  1. Controller Area Network (CAN)
  2. =============================
  3. .. _CAN Protocol License Conditions: http://www.bosch-semiconductors.com/media/ip_modules/pdf_2/can_protocol/bosch_can_protocol_license_conditions.pdf
  4. .. warning::
  5. Please note that the ESP32 includes a CAN peripheral. The CAN Protocol is
  6. protected by the intellectual property rights of Robert Bosch GmbH. Therefore
  7. a license is required for any implementation of the CAN Protocol
  8. (see `CAN Protocol License Conditions`_). **Since the selling price of the
  9. ESP32 includes no such royalty fee, Espressif hereby disclaims any liability or
  10. obligation regarding the CAN Protocol license. Users of the CAN Protocol via
  11. the ESP32's CAN peripheral should contact Robert Bosch GmbH directly for the
  12. necessary license.**
  13. .. -------------------------------- Overview -----------------------------------
  14. Overview
  15. --------
  16. The ESP32's peripherals contains a CAN Controller that supports Standard Frame
  17. Format (16-bit ID) and Extended Frame Format (29-bit ID) of the CAN2.0B specification.
  18. .. warning::
  19. The ESP32 CAN controller is not compatible with CAN FD frames and will interpret
  20. such frames as errors.
  21. This programming guide is split into the following sections:
  22. 1. :ref:`basic-can-concepts`
  23. 2. :ref:`signals-lines-and-transceiver`
  24. 3. :ref:`configuration`
  25. 4. :ref:`driver-operation`
  26. 5. :ref:`examples`
  27. .. --------------------------- Basic CAN Concepts ------------------------------
  28. .. _basic-can-concepts:
  29. Basic CAN Concepts
  30. ------------------
  31. .. note::
  32. The following section only covers the basic aspects of CAN. For full details,
  33. see the CAN2.0B specification
  34. The CAN protocol is a multi-master, multi-cast communication protocol with error
  35. detection/signalling and inbuilt message prioritization. The CAN protocol is
  36. commonly used as a communication bus in automotive applications.
  37. **Multi-master:** Any node in a CAN bus is allowed initiate the transfer of data.
  38. **Multi-cast:** When a node transmits a message, all nodes are able to receive
  39. the message (broadcast). However some nodes can selective choose which messages
  40. to accept via the use of acceptance filtering (multi-cast).
  41. **Error Detection and Signalling:** Every CAN node will constantly monitor the
  42. CAN bus. When any node detects an error, it will signal the error by transmitting an error
  43. frame. Other nodes will receive the error frame and transmit their own error frames
  44. in response. This will result in an error detection being propagated to all nodes on
  45. the bus.
  46. **Message Priorities:** If two nodes attempt to transmit simultaneously, the
  47. node transmitting the message with the lower ID will win arbitration. All other
  48. nodes will become receivers ensuring there is at most one transmitter at any time.
  49. CAN Message Frames
  50. ^^^^^^^^^^^^^^^^^^
  51. The CAN2.0B specification contains two frame formats known as **Extended Frame**
  52. and **Standard Frame** which contain 29-bit IDs and 11-bit IDs respectively.
  53. A CAN message consists of the following components
  54. - 29-bit or 11-bit ID
  55. - Data Length Code (DLC) between 0 to 8
  56. - Up to 8 bytes of data (should match DLC)
  57. Error States and Counters
  58. ^^^^^^^^^^^^^^^^^^^^^^^^^
  59. The CAN2.0B specification implements fault confinement by requiring every CAN node
  60. to maintain two internal error counters known as the **Transmit Error Counter (TEC)**
  61. and the **Receive Error Counter (REC)**. The two error counters are used to determine
  62. a CAN node's **error state**, and the counters are incremented and decremented
  63. following a set of rules (see CAN2.0B specification). These error states are known
  64. as **Error Active**, **Error Passive**, and **Bus-Off**.
  65. **Error Active:** A CAN node is Error Active when **both TEC and REC are less
  66. than 128** and indicates a CAN node is operating normally. Error Active nodes are
  67. allowed to participate in CAN bus activities, and will actively signal any error
  68. conditions it detects by transmitting an **Active Error Flag** over the CAN bus.
  69. **Error Passive:** A CAN node is Error Passive when **either the TEC or REC becomes
  70. greater than or equal to 128**. Error Passive nodes are still able to take part in
  71. CAN bus activities, but will instead transmit a **Passive Error Flag** upon
  72. detection of an error.
  73. **Bus-Off:** A CAN node becomes Bus-Off when the **TEC becomes greater than or equal
  74. to 256**. A Bus-Off node is unable take part in CAN bus activity and will remain so
  75. until it undergoes bus recovery.
  76. .. ---------------------- Signal Lines and Transceiver -------------------------
  77. .. _signals-lines-and-transceiver:
  78. Signals Lines and Transceiver
  79. -----------------------------
  80. The CAN controller does not contain a internal transceiver and therefore
  81. **requires an external transceiver** to operate. The type of external transceiver will
  82. depend on the application's physical layer specification (e.g. using SN65HVD23X
  83. transceivers for ISO 11898-2 compatibility).
  84. The CAN controller's interface consists of 4 signal lines known as **TX, RX, BUS-OFF,
  85. and CLKOUT**. These four signal lines can be routed through the GPIO Matrix to GPIOs.
  86. .. blockdiag:: ../../../_static/diagrams/can/can_controller_signals.diag
  87. :caption: Signal lines of the CAN controller
  88. :align: center
  89. **TX and RX:** The TX and RX signal lines are required to interface with an
  90. external CAN transceiver. Both signal lines represent/interpret a dominant bit
  91. as a low logic level (0V), and a recessive bit as a high logic level (3.3V).
  92. **BUS-OFF:** The BUS-OFF signal line is **optional** and is set to a low logic level
  93. (0V) whenever the CAN controller reaches a bus-off state. The BUS-OFF signal line
  94. is set to a high logic level (3.3V) otherwise.
  95. **CLKOUT:** The CLKOUT signal line is **optional** and outputs a prescaled version
  96. of the CAN controller's source clock (APB Clock).
  97. .. note::
  98. An external transceiver **must internally tie the TX input and the RX output**
  99. such that a change in logic level to the TX signal line can be observed on the
  100. RX line. Failing to do so will cause the CAN controller to interpret differences
  101. in logic levels between the two signal lines as a lost in arbitration or a
  102. bit error.
  103. .. ------------------------------ Configuration --------------------------------
  104. .. _configuration:
  105. Configuration
  106. -------------
  107. Operating Modes
  108. ^^^^^^^^^^^^^^^
  109. The CAN driver supports the following modes of operations:
  110. **Normal Mode:** The normal operating mode allows the CAN controller to take part
  111. in bus activities such as transmitting and receiving messages/error frames.
  112. Acknowledgement from another CAN node is required when transmitting message frames.
  113. **No Ack Mode:** The No Acknowledgement mode is similar to normal mode, however
  114. acknowledgements are not required when transmitting message frames. This mode is
  115. useful when self testing the CAN controller.
  116. **Listen Only Mode:** This mode will prevent the CAN controller from taking part
  117. in bus activities. Therefore transmissions of messages/acknowledgement/error frames
  118. will be disabled. However the the CAN controller will still be able to receive
  119. messages (without acknowledging). This mode is suited for applications such as
  120. CAN bus monitoring.
  121. Alerts
  122. ^^^^^^
  123. The CAN driver contains an alert feature which is used to notify the application
  124. level of certain CAN driver events. Alerts are selectively enabled when the
  125. CAN driver is installed, but can be reconfigured during runtime by calling
  126. :cpp:func:`can_reconfigure_alerts`. The application can then wait for any enabled
  127. alerts to occur by calling :cpp:func:`can_read_alerts`. The CAN driver supports
  128. the following alerts:
  129. +------------------------------------+------------------------------------------------------------------------+
  130. | Alert | Description |
  131. +====================================+=============================================+==========================+
  132. | ``CAN_ALERT_TX_IDLE`` | No more messages queued for transmission |
  133. +------------------------------------+------------------------------------------------------------------------+
  134. | ``CAN_ALERT_TX_SUCCESS`` | The previous transmission was successful |
  135. +------------------------------------+------------------------------------------------------------------------+
  136. | ``CAN_ALERT_BELOW_ERR_WARN`` | Both error counters have dropped below error warning limit |
  137. +------------------------------------+------------------------------------------------------------------------+
  138. | ``CAN_ALERT_ERR_ACTIVE`` | CAN controller has become error active |
  139. +------------------------------------+------------------------------------------------------------------------+
  140. | ``CAN_ALERT_RECOVERY_IN_PROGRESS`` | CAN controller is undergoing bus recovery |
  141. +------------------------------------+------------------------------------------------------------------------+
  142. | ``CAN_ALERT_BUS_RECOVERED`` | CAN controller has successfully completed bus recovery |
  143. +------------------------------------+------------------------------------------------------------------------+
  144. | ``CAN_ALERT_ARB_LOST`` | The previous transmission lost arbitration |
  145. +------------------------------------+------------------------------------------------------------------------+
  146. | ``CAN_ALERT_ABOVE_ERR_WARN`` | One of the error counters have exceeded the error warning limit |
  147. +------------------------------------+------------------------------------------------------------------------+
  148. | ``CAN_ALERT_BUS_ERROR`` | A (Bit, Stuff, CRC, Form, ACK) error has occurred on the bus |
  149. +------------------------------------+------------------------------------------------------------------------+
  150. | ``CAN_ALERT_TX_FAILED`` | The previous transmission has failed |
  151. +------------------------------------+------------------------------------------------------------------------+
  152. | ``CAN_ALERT_RX_QUEUE_FULL`` | The RX queue is full causing a received frame to be lost |
  153. +------------------------------------+------------------------------------------------------------------------+
  154. | ``CAN_ALERT_ERR_PASS`` | CAN controller has become error passive |
  155. +------------------------------------+------------------------------------------------------------------------+
  156. | ``CAN_ALERT_BUS_OFF`` | Bus-off condition occurred. CAN controller can no longer influence bus |
  157. +------------------------------------+------------------------------------------------------------------------+
  158. .. note::
  159. The **error warning limit** can be used to preemptively warn the application
  160. of bus errors before the error passive state is reached. By default the CAN
  161. driver sets the **error warning limit** to **96**. The ``CAN_ALERT_ABOVE_ERR_WARN``
  162. is raised when the TEC or REC becomes larger then or equal to the error warning
  163. limit. The ``CAN_ALERT_BELOW_ERR_WARN`` is raised when both TEC and REC return
  164. back to values below **96**.
  165. .. note::
  166. When enabling alerts, the ``CAN_ALERT_AND_LOG`` flag can be used to cause the
  167. CAN driver to log any raised alerts to UART. The ``CAN_ALERT_ALL`` and
  168. ``CAN_ALERT_NONE`` macros can also be used to enable/disable all alerts during
  169. configuration/reconfiguration.
  170. Bit Timing
  171. ^^^^^^^^^^
  172. The operating bit rate of the CAN controller is configured using the
  173. :cpp:type:`can_timing_config_t` structure. The period of each bit is made up of
  174. multiple **time quanta**, and the period of a **time quanta** is determined by a
  175. prescaled version of the CAN controller's source clock. A single bit contains the
  176. following segments in the following order:
  177. 1. The **Synchronization Segment** consists of a single time quanta
  178. 2. **Timing Segment 1** consists of 1 to 16 time quanta before sample point
  179. 3. **Timing Segment 2** consists of 1 to 8 time quanta after sample point
  180. The **Baudrate Prescaler** is used to determine the period of each time quanta by
  181. dividing the CAN controller's source clock (80 MHz APB clock). The ``brp`` can be
  182. **any even number from 2 to 128**.
  183. .. packetdiag:: ../../../_static/diagrams/can/can_bit_timing.diag
  184. :caption: Bit timing configuration for 500kbit/s given BRP = 8
  185. :align: center
  186. The sample point of a bit is located on the intersection of Timing Segment 1 and
  187. 2. Enabling **Triple Sampling** will cause 3 time quanta to be sampled per bit
  188. instead of 1 (extra samples are located at the tail end of Timing Segment 1).
  189. The **Synchronization Jump Width** is used to determined the maximum number of
  190. time quanta a single bit time can be lengthened/shortened for synchronization
  191. purposes. ``sjw`` can **range from 1 to 4**.
  192. .. note::
  193. Multiple combinations of ``brp``, ``tseg_1``, ``tseg_2``, and ``sjw`` can
  194. achieve the same bit rate. Users should tune these values to the physical
  195. characteristics of their CAN bus by taking into account factors such as
  196. **propagation delay, node information processing time, and phase errors**.
  197. Bit timing **macro initializers** are also available for commonly used CAN bus bit rates.
  198. The following macro initiliazers are provided by the CAN driver.
  199. - ``CAN_TIMING_CONFIG_25KBITS()``
  200. - ``CAN_TIMING_CONFIG_50KBITS()``
  201. - ``CAN_TIMING_CONFIG_100KBITS()``
  202. - ``CAN_TIMING_CONFIG_125KBITS()``
  203. - ``CAN_TIMING_CONFIG_250KBITS()``
  204. - ``CAN_TIMING_CONFIG_500KBITS()``
  205. - ``CAN_TIMING_CONFIG_800KBITS()``
  206. - ``CAN_TIMING_CONFIG_1MBITS()``
  207. Acceptance Filter
  208. ^^^^^^^^^^^^^^^^^
  209. The CAN controller contains a hardware acceptance filter which can be used to
  210. filter CAN messages of a particular ID. A node that filters out a message
  211. **will not receive the message, but will still acknowledge it**. Acceptances
  212. filters can make a node more efficient by filtering out messages sent over the
  213. CAN bus that are irrelevant to the CAN node in question. The CAN controller's
  214. acceptance filter is configured using two 32-bit values within :cpp:type:`can_filter_config_t`
  215. known as the **acceptance code** and the **acceptance mask**.
  216. The **acceptance code** specifies the bit sequence which a message's ID, RTR, and
  217. data bytes must match in order for the message to be received by the CAN
  218. controller. The **acceptance mask** is a bit sequence specifying which bits of
  219. the acceptance code can be ignored. This allows for a messages of different IDs
  220. to be accepted by a single acceptance code.
  221. The acceptance filter can be used under **Single or Dual Filter Mode**.
  222. Single Filter Mode will use the acceptance code and mask to define a single
  223. filter. This allows for the first two data bytes of a standard frame to be filtered,
  224. or the entirety of an extended frame's 29-bit ID. The following diagram illustrates
  225. how the 32-bit acceptance code and mask will be interpreted under Single Filter Mode
  226. (Note: The yellow and blue fields represent standard and extended CAN frames respectively).
  227. .. packetdiag:: ../../../_static/diagrams/can/can_acceptance_filter_single.diag
  228. :caption: Bit layout of single filter mode (Right side MSBit)
  229. :align: center
  230. **Dual Filter Mode** will use the acceptance code and mask to define two separate
  231. filters allowing for increased flexibility of ID's to accept, but does not allow
  232. for all 29-bits of an extended ID to be filtered. The following diagram illustrates
  233. how the 32-bit acceptance code and mask will be interpreted under **Dual Filter Mode**
  234. (Note: The yellow and blue fields represent standard and extended CAN frames respectively).
  235. .. packetdiag:: ../../../_static/diagrams/can/can_acceptance_filter_dual.diag
  236. :caption: Bit layout of dual filter mode (Right side MSBit)
  237. :align: center
  238. Disabling TX Queue
  239. ^^^^^^^^^^^^^^^^^^
  240. The TX queue can be disabled during configuration by setting the ``tx_queue_len``
  241. member of :cpp:type:`can_general_config_t` to ``0``. This will allow applications
  242. that do not require message transmission to save a small amount of memory when
  243. using the CAN driver.
  244. .. -------------------------------- CAN Driver ---------------------------------
  245. .. _driver-operation:
  246. Driver Operation
  247. ----------------
  248. The CAN driver is designed with distinct states and strict rules regarding the
  249. functions or conditions that trigger a state transition. The following diagram
  250. illustrates the various states and their transitions.
  251. .. blockdiag:: ../../../_static/diagrams/can/can_state_transition.diag
  252. :caption: State transition diagram of the CAN driver (see table below)
  253. :align: center
  254. +-------+------------------------+------------------------------------+
  255. | Label | Transition | Action/Condition |
  256. +=======+========================+====================================+
  257. | A | Uninstalled -> Stopped | :cpp:func:`can_driver_install` |
  258. +-------+------------------------+------------------------------------+
  259. | B | Stopped -> Uninstalled | :cpp:func:`can_driver_uninstall` |
  260. +-------+------------------------+------------------------------------+
  261. | C | Stopped -> Running | :cpp:func:`can_start` |
  262. +-------+------------------------+------------------------------------+
  263. | D | Running -> Stopped | :cpp:func:`can_stop` |
  264. +-------+------------------------+------------------------------------+
  265. | E | Running -> Bus-Off | Transmit Error Counter >= 256 |
  266. +-------+------------------------+------------------------------------+
  267. | F | Bus-Off -> Uninstalled | :cpp:func:`can_driver_uninstall` |
  268. +-------+------------------------+------------------------------------+
  269. | G | Bus-Off -> Recovering | :cpp:func:`can_initiate_recovery` |
  270. +-------+------------------------+------------------------------------+
  271. | H | Recovering -> Stopped | 128 occurrences of bus-free signal |
  272. +-------+------------------------+------------------------------------+
  273. Driver States
  274. ^^^^^^^^^^^^^
  275. **Uninstalled**: In the uninstalled state, no memory is allocated for the driver
  276. and the CAN controller is powered OFF.
  277. **Stopped**: In this state, the CAN controller is powered ON and the CAN driver
  278. has been installed. However the CAN controller will be unable to take part in
  279. any CAN bus activities such as transmitting, receiving, or acknowledging messages.
  280. **Running**: In the running state, the CAN controller is able to take part in
  281. bus activities. Therefore messages can be transmitted/received/acknowledged.
  282. Furthermore the CAN controller will be able to transmit error frames upon detection
  283. of errors on the CAN bus.
  284. **Bus-Off**: The bus-off state is automatically entered when the CAN controller's
  285. Transmit Error Counter becomes greater than or equal to 256 (see CAN2.0B specification
  286. regarding error counter rules). The bus-off state indicates the occurrence of severe
  287. errors on the CAN bus or in the CAN controller. Whilst in the bus-off state, the
  288. CAN controller will be unable to take part in any CAN bus activities. To exit
  289. the bus-off state, the CAN controller must undergo the bus recovery process.
  290. **Recovering**: The recovering state is entered when the CAN driver undergoes
  291. bus recovery. The CAN driver/controller will remain in the recovering state until
  292. the 128 occurrences of the bus-free signal (see CAN2.0B specification) is observed
  293. on the CAN bus.
  294. Message Flags
  295. ^^^^^^^^^^^^^
  296. The CAN driver distinguishes different types of CAN messages by using the message
  297. flags in the ``flags`` field of :cpp:type:`can_message_t`. These flags help
  298. distinguish whether a message is in standard or extended format, an RTR, and the
  299. type of transmission to use when transmitting such a message. The CAN driver
  300. supports the following flags:
  301. +-------------------------------+---------------------------------------------------------------+
  302. | Flag | Description |
  303. +===============================+===============================================================+
  304. | ``CAN_MSG_FLAG_EXTD`` | Message is in Extended Frame Format (29bit ID) |
  305. +-------------------------------+---------------------------------------------------------------+
  306. | ``CAN_MSG_FLAG_RTR`` | Message is a Remote Transmit Request |
  307. +-------------------------------+---------------------------------------------------------------+
  308. | ``CAN_MSG_FLAG_SS`` | Transmit message using Single Shot Transmission (Message will |
  309. | | note be retransmitted upon error or loss of arbitration) |
  310. +-------------------------------+---------------------------------------------------------------+
  311. | ``CAN_MSG_FLAG_SELF`` | Transmit message using Self Reception Request (Transmitted |
  312. | | message will also received by the same node) |
  313. +-------------------------------+---------------------------------------------------------------+
  314. | ``CAN_MSG_FLAG_DLC_NON_COMP`` | Message's Data length code is larger than 8. This |
  315. | | will break compliance with CAN2.0B |
  316. +-------------------------------+---------------------------------------------------------------+
  317. .. note::
  318. The ``CAN_MSG_FLAG_NONE`` flag can be used for Standard Frame Format messages
  319. .. -------------------------------- Examples -----------------------------------
  320. .. _examples:
  321. Examples
  322. --------
  323. Configuration & Installation
  324. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  325. The following code snippet demonstrates how to configure, install, and start the
  326. CAN driver via the use of the various configuration structures, macro initializers,
  327. the :cpp:func:`can_driver_install` function, and the :cpp:func:`can_start` function.
  328. .. code-block:: c
  329. #include "driver/gpio.h"
  330. #include "driver/can.h"
  331. void app_main()
  332. {
  333. //Initialize configuration structures using macro initializers
  334. can_general_config_t g_config = CAN_GENERAL_CONFIG_DEFAULT(GPIO_NUM_21, GPIO_NUM_22, CAN_MODE_NORMAL);
  335. can_timing_config_t t_config = CAN_TIMING_CONFIG_500KBITS();
  336. can_filter_config_t f_config = CAN_FILTER_CONFIG_ACCEPT_ALL();
  337. //Install CAN driver
  338. if (can_driver_install(&g_config, &t_config, &f_config) == ESP_OK) {
  339. printf("Driver installed\n");
  340. } else {
  341. printf("Failed to install driver\n");
  342. return;
  343. }
  344. //Start CAN driver
  345. if (can_start() == ESP_OK) {
  346. printf("Driver started\n");
  347. } else {
  348. printf("Failed to start driver\n");
  349. return;
  350. }
  351. ...
  352. }
  353. The usage of macro initializers are not mandatory and each of the configuration
  354. structures can be manually.
  355. Message Transmission
  356. ^^^^^^^^^^^^^^^^^^^^
  357. The following code snippet demonstrates how to transmit a message via the usage
  358. of the :cpp:type:`can_message_t` type and :cpp:func:`can_transmit` function.
  359. .. code-block:: c
  360. #include "driver/can.h"
  361. ...
  362. //Configure message to transmit
  363. can_message_t message;
  364. message.identifier = 0xAAAA;
  365. message.flags = CAN_MSG_FLAG_EXTD;
  366. message.data_length_code = 4;
  367. for (int i = 0; i < 4; i++) {
  368. message.data[i] = 0;
  369. }
  370. //Queue message for transmission
  371. if (can_transmit(&message, pdMS_TO_TICKS(1000)) == ESP_OK) {
  372. printf("Message queued for transmission\n");
  373. } else {
  374. printf("Failed to queue message for transmission\n");
  375. }
  376. Message Reception
  377. ^^^^^^^^^^^^^^^^^
  378. The following code snippet demonstrates how to receive a message via the usage
  379. of the :cpp:type:`can_message_t` type and :cpp:func:`can_receive` function.
  380. .. code-block:: c
  381. #include "driver/can.h"
  382. ...
  383. //Wait for message to be received
  384. can_message_t message;
  385. if (can_receive(&message, pdMS_TO_TICKS(10000)) == ESP_OK) {
  386. printf("Message received\n");
  387. } else {
  388. printf("Failed to receive message\n");
  389. return;
  390. }
  391. //Process received message
  392. if (message.flags & CAN_MSG_FLAG_EXTD) {
  393. printf("Message is in Extended Format\n");
  394. } else {
  395. printf("Message is in Standard Format\n");
  396. }
  397. printf("ID is %d\n", message.identifier);
  398. if (!(message.flags & CAN_MSG_FLAG_RTR)) {
  399. for (int i = 0; i < message.data_length_code; i++) {
  400. printf("Data byte %d = %d\n", i, message.data[i]);
  401. }
  402. }
  403. Reconfiguring and Reading Alerts
  404. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  405. The following code snippet demonstrates how to reconfigure and read CAN driver
  406. alerts via the use of the :cpp:func:`can_reconfigure_alerts` and
  407. :cpp:func:`can_read_alerts` functions.
  408. .. code-block:: c
  409. #include "driver/can.h"
  410. ...
  411. //Reconfigure alerts to detect Error Passive and Bus-Off error states
  412. uint32_t alerts_to_enable = CAN_ALERT_ERR_PASS | CAN_ALERT_BUS_OFF;
  413. if (can_reconfigure_alerts(alerts_to_enable, NULL) == ESP_OK) {
  414. printf("Alerts reconfigured\n");
  415. } else {
  416. printf("Failed to reconfigure alerts");
  417. }
  418. //Block indefinitely until an alert occurs
  419. uint32_t alerts_triggered;
  420. can_read_alerts(&alerts_triggered, portMAX_DELAY);
  421. Stop and Uninstall
  422. ^^^^^^^^^^^^^^^^^^
  423. The following code demonstrates how to stop and uninstall the CAN driver via the
  424. use of the :cpp:func:`can_stop` and :cpp:func:`can_driver_uninstall` functions.
  425. .. code-block:: c
  426. #include "driver/can.h"
  427. ...
  428. //Stop the CAN driver
  429. if (can_stop() == ESP_OK) {
  430. printf("Driver stopped\n");
  431. } else {
  432. printf("Failed to stop driver\n");
  433. return;
  434. }
  435. //Uninstall the CAN driver
  436. if (can_driver_uninstall() == ESP_OK) {
  437. printf("Driver uninstalled\n");
  438. } else {
  439. printf("Failed to uninstall driver\n");
  440. return;
  441. }
  442. Application Examples
  443. ^^^^^^^^^^^^^^^^^^^^
  444. **Network Example:** The CAN Network example demonstrates communication between
  445. two ESP32s using the CAN driver API. One CAN node acts as a network master initiate
  446. and ceasing the transfer of a data from another CAN node acting as a network slave.
  447. The example can be found via :example:`examples/peripheral/can/can_network`.
  448. **Alert and Recovery Example:** This example demonstrates how to use the CAN driver's
  449. alert and bus recovery API. The example purposely introduces errors on the CAN
  450. bus to put the CAN controller into the Bus-Off state. An alert is used to detect
  451. the Bus-Off state and trigger the bus recovery process. The example can be found
  452. via :example:`examples/peripheral/can/can_alert_and_recovery`.
  453. **Self Test Example:** This example uses the No Acknowledge Mode and Self Reception
  454. Request to cause the CAN controller to send and simultaneously receive a series
  455. of messages. This example can be used to verify if the connections between the CAN
  456. controller and the external transceiver are working correctly. The example can be
  457. found via :example:`examples/peripheral/can/can_self_test`.
  458. .. ---------------------------- API Reference ----------------------------------
  459. API Reference
  460. -------------
  461. .. include:: /_build/inc/can.inc