|
|
# CAN bus
|
|
|
|
|
|
The CAN bus (Control Area Network) is a message-based protocol designed to allow microcontrollers and devices to communicate with each other's applications without a host computer.
|
|
|
For each device, the data in a frame is transmitted sequentially but in such a way that if more than one device transmits at the same time, the highest priority device can continue while the others back off. Frames are received by all devices, including by the transmitting device.
|
|
|
|
|
|
All nodes are connected to each other through two wires. Two signals, CAN high (CANH) and CAN low (CANL) are either driven to a "dominant" state with CANH > CANL, or not driven and pulled by passive resistors to a "recessive" state with CANH ≤ CANL. A 0 data bit encodes a dominant state, while a 1 data bit encodes a recessive state, supporting a wired-AND convention, which gives **nodes with lower ID numbers priority** on the bus.
|
|
|
|
|
|
## Data Frames
|
|
|
[](https://en.wikipedia.org/wiki/File:CAN-bus-frame-with-stuff-bit-and-correct-CRC.png)
|
|
|
|
|
|
Here are the important part of the frame.
|
|
|
- Identifier: 11 bit (29 in extended mode)
|
|
|
- stuff bit: see below
|
|
|
- Data Length Code (dlc): 4 bit (number of bytes of data)
|
|
|
- Data field: 0-64 bit
|
|
|
|
|
|
## Bit Stuffing
|
|
|
|
|
|
To ensure enough transitions to maintain synchronization, a bit of opposite polarity is inserted after five consecutive bits of the same polarity. This practice is called bit stuffing. The stuffed data frames are destuffed by the receiver.
|
|
|
|
|
|
All fields in the frame are stuffed with the exception of the CRC delimiter, ACK field and end of frame which are a fixed size and are not stuffed.
|
|
|
|
|
|
so
|
|
|
11111000011110000...
|
|
|
|
|
|
becomes:
|
|
|
|
|
|
11111**0**0000**1**1111**0**0000**1**...
|
|
|
# Low-level driver
|
|
|
## Basic example
|
|
|
```cpp
|
... | ... | @@ -84,6 +112,10 @@ Filter banks are implemented in software with the classes in the `Filters.h` fil |
|
|
|
|
|
|
|
|
## Bit timing register calculation appendix
|
|
|
All nodes on the CAN network must operate at the same nominal bit rate.
|
|
|
|
|
|
Synchronization starts with a hard synchronization on the first recessive to dominant transition after a period of bus idle (the start bit). Resynchronization occurs on every recessive to dominant transition during the frame. The CAN controller expects the transition to occur at a multiple of the nominal bit time. If the transition does not occur at the exact time the controller expects it, the controller adjusts the nominal bit time accordingly.
|
|
|
|
|
|
The objective is, given the desired bus baud rate and position of the sample point, to find the optimal configuration of the `CAN_BTR` register that minimizes the difference between the actual baud rate and sample point vs the target ones.
|
|
|
|
|
|
|
... | ... | |