CAN

0. Pin Map

On the STM32F446RET6 Nucleo board, the SPI1 is connected as below

PA11

CAN1_RX

PA12

CAN1_TX

1. Configure STM32

First, set the configuration from the Template Projectarrow-up-right.

Assuming system clock is configured to be 160 MHz.

In the left sidebar, select Connectivity -> CAN1.

Enable Activated checkbox.

Set Bit Timings Parameters -> Prescaler to 32. Time Quantum should be 1000 ns.

Set Bit Timings Parameters -> Time Quanta in Bit Segment 1 to 3.

Set Bit Timings Parameters -> Time Quanta in Bit Segment 2 to 1.

This way, we get a 250 kbps CAN bus with a sampling point at 75% position.

We can also change the prescaler value to 16 to get a 500 kbps bus, or 8 to get a 1 Mbps bus.

The optimal sampling point is 87.5%, and we are pretty close to it.

This is a useful website for CAN bit-timingarrow-up-right.

To debug the CAN bus, set Advanced Parameters -> Operating Mode to "Loopback".

Errata: When using loopback mode, the RX pin should still be pulled-up externally. We can do this simply by configuring the PA11 GPIO to enable the internal pull-up resistor, but please remember to do this. Otherwise, the HAL_CAN_Start() method will timeout. Detailed information can be found herearrow-up-right.

2. Code

First, add the code from the Template Projectarrow-up-right.

In main.c, add the following code

After saving, upload the code.

Detailed information on how CAN filter works can be found herearrow-up-right.

3. Result

4. Using both CAN1 and CAN2

5. Interrupt

Last updated