Best practice for setting registers

Comments

3 comments

  • Avatar
    Paul Curtis

    > What's the advantage of using one or the other?  Is there a "best practice" for setting the bits in registers?

    Who knows?  I mean, the function call obscures what the code does by abstracting it out.  Hence, you have to read documentation to see what it does.  Writing to the register directly means you need to break out the user manual for the device.  It really depends what you're comfortable with, how much you trust documentation, and how familiar you are with the device.  I don't see an argument for one over the other, they are equally valid or invalid.

    0
    Comment actions Permalink
  • Avatar
    Richard Webb

    One ARM7 vendor had an error in the CAN peripheral initialization in their library code.[*] This particular chip has two CAN peripherals and the code for the second was very obviously a copy-paste from the first, to the point that some comments for the second still referred to the first. A bit was missed in one register when the pasted code was edited for the second CAN, with the result that the initialization call would appear to succeed but the peripheral wasn't actually enabled. It was fun tracking that one down.

     As Paul says, it's largely a matter of personal preference whether to bang on the registers directly or to rely on vendor's code. As for myself, it's break out the manual and do my own setup. I still end up debugging sometimes but at least it's my own code that I'm wading through. 

    [*] This was at least three years and several STL revisions ago. I haven't gone back to check but, presumably, that bug has been fixed in the vendor's distribution code.

    0
    Comment actions Permalink
  • Avatar
    Dr Danish Ali

    Using the function call might aid portability between different microcontrollers from the same vendor where the peripheral might have been upgraded.

    For example the stm32f10x has a simpler USART than the stm32f20x (it does not support 8x oversampling, only 16x) with an extra control bit in CR1.

    If you wrote your own code, do you know what would end up in that bit?

    With the manufacturer's library, I would hope that either a sensible default would be used, or (perhaps better) the compiler would complain about a missing/unset parameter. But even a run-time trap would aid debugging.

    Me? I try to understand the library call then manipulate the bits directly. But remember that you might have to mask the existing value:

    RCC->CR = (RCC->CR & ~ RCC_CR_HSITRIM_MASK) | (trim << RCC_CR_HSITRIM_BIT);

    0
    Comment actions Permalink

Please sign in to leave a comment.