pazi88 / STM32_CAN

CAN bus Library for Arduino STM32
GNU General Public License v3.0
67 stars 28 forks source link

Baudrate is calculated with SJW in the mix #40

Closed attie-argentum closed 2 weeks ago

attie-argentum commented 1 month ago

We've been having some issues with CAN communications between a handful of devices. I started looking in to how the baudrate is calculated, and it seems to be slightly wrong.

SJW is not actually part of the bit-time calculation, I suspect this has been confused with SYNC_SEG (which is always 1). The following is from the STM32F72xxx reference manual, but applies to all bxCAN peripherals.

screenshot showing the nominal bit timing - SYNC_SEG + BS1 + BS2

I believe the calculation below should be calcBaudrate = (frequency / (prescaler * (1 + bs1 + bs2))).

https://github.com/pazi88/STM32_CAN/blob/ae6ccadd8d39d245fbddee38bec2206114c481ab/STM32_CAN.cpp#L707-L717

Separately, to improve interoperability SJW can be increased from the default value of 1 - this will allow the next transition to arrive earlier than the node expects it - up to min(BS2, 4) time quanta. In many cases, this can be safely set higher than 1 - and in other cases it's even necessary to avoid error frames and wider disruption on the bus.

Please can you let me know if you agree with this, or if you think I'm mistaken? I'd be happy to prepare a PR to adjust this accordingly.

pazi88 commented 1 month ago

You might be right. Please prepare the PR. I'll check it more in detail next week.

pazi88 commented 2 weeks ago

Fixed in #41