1Two-Wire Automotive Interface (TWAI)
2====================================
3
4.. -------------------------------- Overview -----------------------------------
5
6Overview
7--------
8
9The Two-Wire Automotive Interface (TWAI) is a real-time serial communication protocol suited for automotive and industrial applications. It is compatible with ISO11898-1 Classical frames, thus can support Standard Frame Format (11-bit ID) and Extended Frame Format (29-bit ID). The {IDF_TARGET_NAME}'s peripherals contains a TWAI controller that can be configured to communicate on a TWAI bus via an external transceiver.
10
11.. warning::
12    The TWAI controller is not compatible with ISO11898-1 FD Format frames, and will interpret such frames as errors.
13
14This programming guide is split into the following sections:
15
16    1. :ref:`twai-protocol-summary`
17
18    2. :ref:`signals-lines-and-transceiver`
19
20    3. :ref:`configuration`
21
22    4. :ref:`driver-operation`
23
24    5. :ref:`examples`
25
26
27.. --------------------------- Basic TWAI Concepts -----------------------------
28
29.. _twai-protocol-summary:
30
31TWAI Protocol Summary
32---------------------
33
34The TWAI is a multi-master, multi-cast, asynchronous, serial communication protocol. TWAI also supports error detection and signalling, and inbuilt message prioritization.
35
36**Multi-master:** Any node on the bus can initiate the transfer of a message.
37
38**Multi-cast:** When a node transmits a message, all nodes on the bus will receive the message (i.e., broadcast) thus ensuring data consistency across all nodes. However, some nodes can selectively choose which messages to accept via the use of acceptance filtering (multi-cast).
39
40**Asynchronous:** The bus does not contain a clock signal. All nodes on the bus operate at the same bit rate and synchronize using the edges of the bits transmitted on the bus.
41
42**Error Detection and Signalling:** Every node will constantly monitor the bus. When any node detects an error, it will signal the detection by transmitting an error frame. Other nodes will receive the error frame and transmit their own error frames in response. This will result in an error detection being propagated to all nodes on the bus.
43
44**Message Priorities:** Messages contain an ID field. If two or more nodes attempt to transmit simultaneously, the node transmitting the message with the lower ID value will win arbitration of the bus. All other nodes will become receivers ensuring that there is at most one transmitter at any time.
45
46TWAI Messages
47^^^^^^^^^^^^^
48
49TWAI Messages are split into Data Frames and Remote Frames. Data Frames are used to deliver a data payload to other nodes, whereas a Remote Frame is used to request a Data Frame from other nodes (other nodes can optionally respond with a Data Frame). Data and Remote Frames have two frame formats known as **Extended Frame** and **Standard Frame** which contain a 29-bit ID and an 11-bit ID respectively. A TWAI message consists of the following fields:
50
51    - 29-bit or 11-bit ID: Determines the priority of the message (lower value has higher priority).
52    - Data Length Code (DLC) between 0 to 8: Indicates the size (in bytes) of the data payload for a Data Frame, or the amount of data to request for a Remote Frame.
53    - Up to 8 bytes of data for a Data Frame (should match DLC).
54
55Error States and Counters
56^^^^^^^^^^^^^^^^^^^^^^^^^
57
58The TWAI protocol implements a feature known as "fault confinement" where a persistently erroneous node will eventually eliminate itself form the bus. This is implemented by requiring every node to maintain two internal error counters known as the **Transmit Error Counter (TEC)** and the **Receive Error Counter (REC)**. The two error counters are incremented and decremented according to a set of rules (where the counters increase on an error, and decrease on a successful message transmission/reception). The values of the counters are used to determine a node's **error state**, namely **Error Active**, **Error Passive**, and **Bus-Off**.
59
60**Error Active:** A node is Error Active when **both TEC and REC are less than 128** and indicates that the node is operating normally. Error Active nodes are allowed to participate in bus communications, and will actively signal the detection of any errors by automatically transmitting an **Active Error Flag** over the bus.
61
62**Error Passive:** A node is Error Passive when **either the TEC or REC becomes greater than or equal to 128**. Error Passive nodes are still able to take part in bus communications, but will instead transmit a **Passive Error Flag** upon detection of an error.
63
64**Bus-Off:** A node becomes Bus-Off when the **TEC becomes greater than or equal to 256**. A Bus-Off node is unable influence the bus in any manner (essentially disconnected from the bus) thus eliminating itself from the bus. A node will remain in the Bus-Off state until it undergoes bus-off recovery.
65
66
67.. ---------------------- Signal Lines and Transceiver -------------------------
68
69.. _signals-lines-and-transceiver:
70
71Signals Lines and Transceiver
72-----------------------------
73
74The TWAI controller does not contain a integrated transceiver. Therefore, to connect the TWAI controller to a TWAI bus, **an external transceiver is required**. The type of external transceiver used should depend on the application's physical layer specification (e.g. using SN65HVD23x transceivers for ISO 11898-2 compatibility).
75
76The TWAI controller's interface consists of 4 signal lines known as **TX, RX, BUS-OFF, and CLKOUT**. These four signal lines can be routed through the GPIO Matrix to the {IDF_TARGET_NAME}'s GPIO pads.
77
78.. blockdiag:: ../../../_static/diagrams/twai/controller_signals.diag
79    :caption: Signal lines of the TWAI controller
80    :align: center
81
82**TX and RX:** The TX and RX signal lines are required to interface with an external transceiver. Both signal lines represent/interpret a dominant bit as a low logic level (0V), and a recessive bit as a high logic level (3.3V).
83
84**BUS-OFF:** The BUS-OFF signal line is **optional** and is set to a low logic level (0V) whenever the TWAI controller reaches a bus-off state. The BUS-OFF signal line is set to a high logic level (3.3V) otherwise.
85
86**CLKOUT:** The CLKOUT signal line is **optional** and outputs a prescaled version of the controller's source clock (APB Clock).
87
88.. note::
89    An external transceiver **must internally loopback the TX to RX** such that a change in logic level to the TX signal line can be observed on the RX line. Failing to do so will cause the TWAI controller to interpret differences in logic levels between the two signal lines as a loss in arbitration or a bit error.
90
91
92.. ------------------------------ Configuration --------------------------------
93
94.. _configuration:
95
96Driver Configuration
97--------------------
98
99This section covers how to configure the TWAI driver.
100
101Operating Modes
102^^^^^^^^^^^^^^^
103
104The TWAI driver supports the following modes of operations:
105
106**Normal Mode:** The normal operating mode allows the TWAI controller to take part in bus activities such as transmitting and receiving messages/error frames. Acknowledgement from another node is required when transmitting a message.
107
108**No Ack Mode:** The No Acknowledgement mode is similar to normal mode, however acknowledgements are not required for a message transmission to be considered successful. This mode is useful when self testing the TWAI controller (loopback of transmissions).
109
110**Listen Only Mode:** This mode will prevent the TWAI controller from influencing the bus. Therefore, transmission of messages/acknowledgement/error frames will be disabled. However the TWAI controller will still be able to receive messages but will not acknowledge the message. This mode is suited for bus monitor applications.
111
112Alerts
113^^^^^^
114
115The TWAI driver contains an alert feature that is used to notify the application layer of certain TWAI controller or TWAI bus events. Alerts are selectively enabled when the TWAI driver is installed, but can be reconfigured during runtime by calling :cpp:func:`twai_reconfigure_alerts`. The application can then wait for any enabled alerts to occur by calling :cpp:func:`twai_read_alerts`. The TWAI driver supports the following alerts:
116
117.. list-table:: TWAI Driver Alerts
118    :widths: 40 60
119    :header-rows: 1
120
121    * - Alert Flag
122      - Description
123    * - ``TWAI_ALERT_TX_IDLE``
124      - No more messages queued for transmission
125    * - ``TWAI_ALERT_TX_SUCCESS``
126      - The previous transmission was successful
127    * - ``TWAI_ALERT_RX_DATA``
128      - A frame has been received and added to the RX queue
129    * - ``TWAI_ALERT_BELOW_ERR_WARN``
130      - Both error counters have dropped below error warning limit
131    * - ``TWAI_ALERT_ERR_ACTIVE``
132      - TWAI controller has become error active
133    * - ``TWAI_ALERT_RECOVERY_IN_PROGRESS``
134      - TWAI controller is undergoing bus recovery
135    * - ``TWAI_ALERT_BUS_RECOVERED``
136      - TWAI controller has successfully completed bus recovery
137    * - ``TWAI_ALERT_ARB_LOST``
138      - The previous transmission lost arbitration
139    * - ``TWAI_ALERT_ABOVE_ERR_WARN``
140      - One of the error counters have exceeded the error warning limit
141    * - ``TWAI_ALERT_BUS_ERROR``
142      - A (Bit, Stuff, CRC, Form, ACK) error has occurred on the bus
143    * - ``TWAI_ALERT_TX_FAILED``
144      - The previous transmission has failed
145    * - ``TWAI_ALERT_RX_QUEUE_FULL``
146      - The RX queue is full causing a received frame to be lost
147    * - ``TWAI_ALERT_ERR_PASS``
148      - TWAI controller has become error passive
149    * - ``TWAI_ALERT_BUS_OFF``
150      - Bus-off condition occurred. TWAI controller can no longer influence bus
151
152.. note::
153    The TWAI controller's **error warning limit** is used to preemptively warn the application of bus errors before the error passive state is reached. By default, the TWAI driver sets the **error warning limit** to **96**. The ``TWAI_ALERT_ABOVE_ERR_WARN`` is raised when the TEC or REC becomes larger then or equal to the error warning limit. The ``TWAI_ALERT_BELOW_ERR_WARN`` is raised when both TEC and REC return back to values below **96**.
154
155.. note::
156    When enabling alerts, the ``TWAI_ALERT_AND_LOG`` flag can be used to cause the TWAI driver to log any raised alerts to UART. However, alert logging is disabled and ``TWAI_ALERT_AND_LOG`` if the :ref:`CONFIG_TWAI_ISR_IN_IRAM` option is enabled (see :ref:`placing-isr-into-iram`).
157
158.. note::
159    The ``TWAI_ALERT_ALL`` and ``TWAI_ALERT_NONE`` macros can also be used to enable/disable all alerts during configuration/reconfiguration.
160
161Bit Timing
162^^^^^^^^^^
163
164The operating bit rate of the TWAI driver is configured using the :cpp:type:`twai_timing_config_t` structure. The period of each bit is made up of multiple **time quanta**, and the period of a **time quantum** is determined by a prescaled version of the TWAI controller's source clock. A single bit contains the following segments in the following order:
165
166    1. The **Synchronization Segment** consists of a single time quantum
167    2. **Timing Segment 1** consists of 1 to 16 time quanta before sample point
168    3. **Timing Segment 2** consists of 1 to 8 time quanta after sample point
169
170{IDF_TARGET_MAX_BRP:default="128", esp32="128", esp32s2="32768", esp32c3="16384"}
171
172The **Baudrate Prescaler** is used to determine the period of each time quantum by dividing the TWAI controller's source clock (80 MHz APB clock). On the {IDF_TARGET_NAME}, the ``brp`` can be **any even number from 2 to {IDF_TARGET_MAX_BRP}**.
173
174.. only:: esp32
175
176    If the ESP32 is a revision 2 or later chip, the ``brp`` will **also support any multiple of 4 from 132 to 256**, and can be enabled by setting the :ref:`CONFIG_ESP32_REV_MIN` to revision 2 or higher.
177
178.. packetdiag:: ../../../_static/diagrams/twai/bit_timing.diag
179    :caption: Bit timing configuration for 500kbit/s given BRP = 8
180    :align: center
181
182The sample point of a bit is located on the intersection of Timing Segment 1 and 2. Enabling **Triple Sampling** will cause 3 time quanta to be sampled per bit instead of 1 (extra samples are located at the tail end of Timing Segment 1).
183
184The **Synchronization Jump Width** is used to determine the maximum number of time quanta a single bit time can be lengthened/shortened for synchronization purposes. ``sjw`` can **range from 1 to 4**.
185
186.. note::
187    Multiple combinations of ``brp``, ``tseg_1``, ``tseg_2``, and ``sjw`` can achieve the same bit rate. Users should tune these values to the physical characteristics of their bus by taking into account factors such as **propagation delay, node information processing time, and phase errors**.
188
189Bit timing **macro initializers** are also available for commonly used bit rates. The following macro initializers are provided by the TWAI driver.
190
191.. list::
192
193    - ``TWAI_TIMING_CONFIG_1MBITS()``
194    - ``TWAI_TIMING_CONFIG_800KBITS()``
195    - ``TWAI_TIMING_CONFIG_500KBITS()``
196    - ``TWAI_TIMING_CONFIG_250KBITS()``
197    - ``TWAI_TIMING_CONFIG_125KBITS()``
198    - ``TWAI_TIMING_CONFIG_100KBITS()``
199    - ``TWAI_TIMING_CONFIG_50KBITS()``
200    - ``TWAI_TIMING_CONFIG_25KBITS()``
201    :esp32s2: - ``TWAI_TIMING_CONFIG_20KBITS()``
202    :esp32s2: - ``TWAI_TIMING_CONFIG_16KBITS()``
203    :esp32s2: - ``TWAI_TIMING_CONFIG_12_5KBITS()``
204    :esp32s2: - ``TWAI_TIMING_CONFIG_10KBITS()``
205    :esp32s2: - ``TWAI_TIMING_CONFIG_5KBITS()``
206    :esp32s2: - ``TWAI_TIMING_CONFIG_1KBITS()``
207    :esp32s3: - ``TWAI_TIMING_CONFIG_20KBITS()``
208    :esp32s3: - ``TWAI_TIMING_CONFIG_16KBITS()``
209    :esp32s3: - ``TWAI_TIMING_CONFIG_12_5KBITS()``
210    :esp32s3: - ``TWAI_TIMING_CONFIG_10KBITS()``
211    :esp32s3: - ``TWAI_TIMING_CONFIG_5KBITS()``
212    :esp32s3: - ``TWAI_TIMING_CONFIG_1KBITS()``
213    :esp32c3: - ``TWAI_TIMING_CONFIG_20KBITS()``
214    :esp32c3: - ``TWAI_TIMING_CONFIG_16KBITS()``
215    :esp32c3: - ``TWAI_TIMING_CONFIG_12_5KBITS()``
216    :esp32c3: - ``TWAI_TIMING_CONFIG_10KBITS()``
217    :esp32c3: - ``TWAI_TIMING_CONFIG_5KBITS()``
218    :esp32c3: - ``TWAI_TIMING_CONFIG_1KBITS()``
219
220.. only:: esp32
221
222    Revision 2 or later of the ESP32 also supports the following bit rates:
223
224    - ``TWAI_TIMING_CONFIG_20KBITS()``
225    - ``TWAI_TIMING_CONFIG_16KBITS()``
226    - ``TWAI_TIMING_CONFIG_12_5KBITS()``
227
228Acceptance Filter
229^^^^^^^^^^^^^^^^^
230
231The TWAI controller contains a hardware acceptance filter which can be used to filter messages of a particular ID. A node that filters out a message **will not receive the message, but will still acknowledge it**. Acceptance filters can make a node more efficient by filtering out messages sent over the bus that are irrelevant to the node. The acceptance filter is configured using two 32-bit values within :cpp:type:`twai_filter_config_t` known as the **acceptance code** and the **acceptance mask**.
232
233The **acceptance code** specifies the bit sequence which a message's ID, RTR, and data bytes must match in order for the message to be received by the TWAI controller. The **acceptance mask** is a bit sequence specifying which bits of the acceptance code can be ignored. This allows for a messages of different IDs to be accepted by a single acceptance code.
234
235The acceptance filter can be used under **Single or Dual Filter Mode**. Single Filter Mode will use the acceptance code and mask to define a single filter. This allows for the first two data bytes of a standard frame to be filtered, or the entirety of an extended frame's 29-bit ID. The following diagram illustrates how the 32-bit acceptance code and mask will be interpreted under Single Filter Mode (Note: The yellow and blue fields represent standard and extended frame formats respectively).
236
237.. packetdiag:: ../../../_static/diagrams/twai/acceptance_filter_single.diag
238    :caption: Bit layout of single filter mode (Right side MSBit)
239    :align: center
240
241**Dual Filter Mode** will use the acceptance code and mask to define two separate filters allowing for increased flexibility of ID's to accept, but does not allow for all 29-bits of an extended ID to be filtered. The following diagram illustrates how the 32-bit acceptance code and mask will be interpreted under **Dual Filter Mode** (Note: The yellow and blue fields represent standard and extended frame formats respectively).
242
243.. packetdiag:: ../../../_static/diagrams/twai/acceptance_filter_dual.diag
244    :caption: Bit layout of dual filter mode (Right side MSBit)
245    :align: center
246
247Disabling TX Queue
248^^^^^^^^^^^^^^^^^^
249
250The TX queue can be disabled during configuration by setting the ``tx_queue_len`` member of :cpp:type:`twai_general_config_t` to ``0``. This will allow applications that do not require message transmission to save a small amount of memory when using the TWAI driver.
251
252.. _placing-isr-into-iram:
253
254Placing ISR into IRAM
255^^^^^^^^^^^^^^^^^^^^^
256
257The TWAI driver's ISR (Interrupt Service Routine) can be placed into IRAM so that the ISR can still run whilst the cache is disabled. Placing the ISR into IRAM may be necessary to maintain the TWAI driver's functionality during lengthy cache disabling operations (such as SPI Flash writes, OTA updates etc). Whilst the cache is disabled, the ISR will continue to:
258
259- Read received messages from the RX buffer and place them into the driver's RX queue.
260- Load messages pending transmission from the driver's TX queue and write them into the TX buffer.
261
262To place the TWAI driver's ISR, users must do the following:
263
264- Enable the :ref:`CONFIG_TWAI_ISR_IN_IRAM` option using ``idf.py menuconfig``.
265- When calling :cpp:func:`twai_driver_install`, the `intr_flags` member of :cpp:type:`twai_general_config_t` should set the :c:macro:`ESP_INTR_FLAG_IRAM` set.
266
267.. note::
268    When the :ref:`CONFIG_TWAI_ISR_IN_IRAM` option is enabled, the TWAI driver will no longer log any alerts (i.e., the ``TWAI_ALERT_AND_LOG`` flag will not have any effect).
269
270.. ------------------------------- TWAI Driver ---------------------------------
271
272.. _driver-operation:
273
274Driver Operation
275----------------
276
277The TWAI driver is designed with distinct states and strict rules regarding the functions or conditions that trigger a state transition. The following diagram illustrates the various states and their transitions.
278
279.. blockdiag:: ../../../_static/diagrams/twai/state_transition.diag
280    :caption: State transition diagram of the TWAI driver (see table below)
281    :align: center
282
283.. list-table::
284    :widths: 20 40 40
285    :header-rows: 1
286
287    * - Label
288      - Transition
289      - Action/Condition
290    * - A
291      - Uninstalled -> Stopped
292      - :cpp:func:`twai_driver_install`
293    * - B
294      - Stopped -> Uninstalled
295      - :cpp:func:`twai_driver_uninstall`
296    * - C
297      - Stopped -> Running
298      - :cpp:func:`twai_start`
299    * - D
300      - Running -> Stopped
301      - :cpp:func:`twai_stop`
302    * - E
303      - Running -> Bus-Off
304      - Transmit Error Counter >= 256
305    * - F
306      - Bus-Off -> Uninstalled
307      - :cpp:func:`twai_driver_uninstall`
308    * - G
309      - Bus-Off -> Recovering
310      - :cpp:func:`twai_initiate_recovery`
311    * - H
312      - Recovering -> Stopped
313      - 128 occurrences of 11 consecutive recessive bits.
314
315
316Driver States
317^^^^^^^^^^^^^
318
319**Uninstalled**: In the uninstalled state, no memory is allocated for the driver and the TWAI controller is powered OFF.
320
321**Stopped**: In this state, the TWAI controller is powered ON and the TWAI driver has been installed. However the TWAI controller will be unable to take part in any bus activities such as transmitting, receiving, or acknowledging messages.
322
323**Running**: In the running state, the TWAI controller is able to take part in bus activities. Therefore messages can be transmitted/received/acknowledged. Furthermore the TWAI controller will be able to transmit error frames upon detection of errors on the bus.
324
325**Bus-Off**: The bus-off state is automatically entered when the TWAI controller's Transmit Error Counter becomes greater than or equal to 256. The bus-off state indicates the occurrence of severe errors on the bus or in the TWAI controller. Whilst in the bus-off state, the TWAI controller will be unable to take part in any bus activities. To exit the bus-off state, the TWAI controller must undergo the bus recovery process.
326
327**Recovering**: The recovering state is entered when the TWAI controller undergoes bus recovery. The TWAI controller/TWAI driver will remain in the recovering state until the 128 occurrences of 11 consecutive recessive bits is observed on the bus.
328
329Message Fields and Flags
330^^^^^^^^^^^^^^^^^^^^^^^^
331
332The TWAI driver distinguishes different types of messages by using the various bit field members of the :cpp:type:`twai_message_t` structure. These bit field members determine whether a message is in standard or extended format, a remote frame, and the type of transmission to use when transmitting such a message.
333
334These bit field members can also be toggled using the the `flags` member of :cpp:type:`twai_message_t` and the following message flags:
335
336.. list-table::
337    :widths: 30 70
338    :header-rows: 1
339
340    * - Message Flag
341      - Description
342    * - ``TWAI_MSG_FLAG_EXTD``
343      - Message is in Extended Frame Format (29bit ID)
344    * - ``TWAI_MSG_FLAG_RTR``
345      - Message is a Remote Frame (Remote Transmission Request)
346    * - ``TWAI_MSG_FLAG_SS``
347      - Transmit message using Single Shot Transmission (Message will not be retransmitted upon error or loss of arbitration). Unused for received message.
348    * - ``TWAI_MSG_FLAG_SELF``
349      - Transmit message using Self Reception Request (Transmitted message will also received by the same node). Unused for received message.
350    * - ``TWAI_MSG_FLAG_DLC_NON_COMP``
351      - Message's Data length code is larger than 8. This will break compliance with TWAI
352    * - ``TWAI_MSG_FLAG_NONE``
353      - Clears all bit fields. Equivalent to a Standard Frame Format (11bit ID) Data Frame.
354
355.. -------------------------------- Examples -----------------------------------
356
357.. _examples:
358
359Examples
360--------
361
362Configuration & Installation
363^^^^^^^^^^^^^^^^^^^^^^^^^^^^
364
365The following code snippet demonstrates how to configure, install, and start the TWAI driver via the use of the various configuration structures, macro initializers, the :cpp:func:`twai_driver_install` function, and the :cpp:func:`twai_start` function.
366
367.. code-block:: c
368
369    #include "driver/gpio.h"
370    #include "driver/twai.h"
371
372    void app_main()
373    {
374        //Initialize configuration structures using macro initializers
375        twai_general_config_t g_config = TWAI_GENERAL_CONFIG_DEFAULT(GPIO_NUM_21, GPIO_NUM_22, TWAI_MODE_NORMAL);
376        twai_timing_config_t t_config = TWAI_TIMING_CONFIG_500KBITS();
377        twai_filter_config_t f_config = TWAI_FILTER_CONFIG_ACCEPT_ALL();
378
379        //Install TWAI driver
380        if (twai_driver_install(&g_config, &t_config, &f_config) == ESP_OK) {
381            printf("Driver installed\n");
382        } else {
383            printf("Failed to install driver\n");
384            return;
385        }
386
387        //Start TWAI driver
388        if (twai_start() == ESP_OK) {
389            printf("Driver started\n");
390        } else {
391            printf("Failed to start driver\n");
392            return;
393        }
394
395        ...
396
397    }
398
399The usage of macro initializers is not mandatory and each of the configuration structures can be manually.
400
401Message Transmission
402^^^^^^^^^^^^^^^^^^^^
403
404The following code snippet demonstrates how to transmit a message via the usage of the :cpp:type:`twai_message_t` type and :cpp:func:`twai_transmit` function.
405
406.. code-block:: c
407
408    #include "driver/twai.h"
409
410    ...
411
412    //Configure message to transmit
413    twai_message_t message;
414    message.identifier = 0xAAAA;
415    message.extd = 1;
416    message.data_length_code = 4;
417    for (int i = 0; i < 4; i++) {
418        message.data[i] = 0;
419    }
420
421    //Queue message for transmission
422    if (twai_transmit(&message, pdMS_TO_TICKS(1000)) == ESP_OK) {
423        printf("Message queued for transmission\n");
424    } else {
425        printf("Failed to queue message for transmission\n");
426    }
427
428Message Reception
429^^^^^^^^^^^^^^^^^
430
431The following code snippet demonstrates how to receive a message via the usage of the :cpp:type:`twai_message_t` type and :cpp:func:`twai_receive` function.
432
433.. code-block:: c
434
435    #include "driver/twai.h"
436
437    ...
438
439    //Wait for message to be received
440    twai_message_t message;
441    if (twai_receive(&message, pdMS_TO_TICKS(10000)) == ESP_OK) {
442        printf("Message received\n");
443    } else {
444        printf("Failed to receive message\n");
445        return;
446    }
447
448    //Process received message
449    if (message.extd) {
450        printf("Message is in Extended Format\n");
451    } else {
452        printf("Message is in Standard Format\n");
453    }
454    printf("ID is %d\n", message.identifier);
455    if (!(message.rtr)) {
456        for (int i = 0; i < message.data_length_code; i++) {
457            printf("Data byte %d = %d\n", i, message.data[i]);
458        }
459    }
460
461Reconfiguring and Reading Alerts
462^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
463
464The following code snippet demonstrates how to reconfigure and read TWAI driver alerts via the use of the :cpp:func:`twai_reconfigure_alerts` and :cpp:func:`twai_read_alerts` functions.
465
466.. code-block:: c
467
468    #include "driver/twai.h"
469
470    ...
471
472    //Reconfigure alerts to detect Error Passive and Bus-Off error states
473    uint32_t alerts_to_enable = TWAI_ALERT_ERR_PASS | TWAI_ALERT_BUS_OFF;
474    if (twai_reconfigure_alerts(alerts_to_enable, NULL) == ESP_OK) {
475        printf("Alerts reconfigured\n");
476    } else {
477        printf("Failed to reconfigure alerts");
478    }
479
480    //Block indefinitely until an alert occurs
481    uint32_t alerts_triggered;
482    twai_read_alerts(&alerts_triggered, portMAX_DELAY);
483
484Stop and Uninstall
485^^^^^^^^^^^^^^^^^^
486
487The following code demonstrates how to stop and uninstall the TWAI driver via the use of the :cpp:func:`twai_stop` and :cpp:func:`twai_driver_uninstall` functions.
488
489.. code-block:: c
490
491    #include "driver/twai.h"
492
493    ...
494
495    //Stop the TWAI driver
496    if (twai_stop() == ESP_OK) {
497        printf("Driver stopped\n");
498    } else {
499        printf("Failed to stop driver\n");
500        return;
501    }
502
503    //Uninstall the TWAI driver
504    if (twai_driver_uninstall() == ESP_OK) {
505        printf("Driver uninstalled\n");
506    } else {
507        printf("Failed to uninstall driver\n");
508        return;
509    }
510
511Multiple ID Filter Configuration
512^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
513
514The acceptance mask in :cpp:type:`twai_filter_config_t` can be configured such that two or more IDs will be accepted for a single filter. For a particular filter to accept multiple IDs, the conflicting bit positions amongst the IDs must be set in the acceptance mask. The acceptance code can be set to any one of the IDs.
515
516The following example shows how the calculate the acceptance mask given multiple IDs::
517
518    ID1 =  11'b101 1010 0000
519    ID2 =  11'b101 1010 0001
520    ID3 =  11'b101 1010 0100
521    ID4 =  11'b101 1010 1000
522    //Acceptance Mask
523    MASK = 11'b000 0000 1101
524
525Application Examples
526^^^^^^^^^^^^^^^^^^^^
527
528**Network Example:** The TWAI Network example demonstrates communication between two {IDF_TARGET_NAME}s using the TWAI driver API. One TWAI node acts as a network master that initiates and ceases the transfer of a data from another  node acting as a network slave. The example can be found via :example:`peripherals/twai/twai_network`.
529
530**Alert and Recovery Example:** This example demonstrates how to use the TWAI driver's alert and bus-off recovery API. The example purposely introduces errors on the bus to put the TWAI controller into the Bus-Off state. An alert is used to detect the Bus-Off state and trigger the bus recovery process. The example can be found via :example:`peripherals/twai/twai_alert_and_recovery`.
531
532**Self Test Example:** This example uses the No Acknowledge Mode and Self Reception Request to cause the TWAI controller to send and simultaneously receive a series of messages. This example can be used to verify if the connections between the TWAI controller and the external transceiver are working correctly. The example can be found via :example:`peripherals/twai/twai_self_test`.
533
534
535.. ---------------------------- API Reference ----------------------------------
536
537API Reference
538-------------
539
540.. include-build-file:: inc/twai_types.inc
541.. include-build-file:: inc/twai.inc
542