It has come to my attention that some ARM programmers set some CPU registers with values that are the same default values of the register on microcontroller reset.

For example: the default value of IOCON_PIO2_9, parameter MODE on LCP1114 is 0x02 (pull-up resistor enabled). In Olimex's example code this value is set to 0x02 in software initialization but this is already the default value.

This behavior occurs with many other registers.

Why would someone do that? In my opinion, this extra code just pollutes everything and make code readability worse. Is this a good programming practice?

  • 2
    \$\begingroup\$ I'm not a person to be talking about "best practice", but especially on a platform like ARM, where all peripheral functionality is on the manufacturer and you might find yourself jumping between manufacturers, it seems like this practice would enhance portability. \$\endgroup\$ Commented Jan 20, 2014 at 14:11
  • \$\begingroup\$ You ever heard the quote "Assumption is the mother of all f***kups"? Never assume anything, even the default values can change if there is a brownout or somesuch so never rely on anything to be in any state unless you set it yourself. \$\endgroup\$
    – John U
    Commented Jan 20, 2014 at 19:07

1 Answer 1

  1. To make code modular. If your A/D routine, for example, always sets up the A/D completely for whatever mode it uses it in, then that routine can be called at any time whether immediately after powerup or after the A/D was used in some other way.
  2. Code may jump back to the startup location to do a software reset. In that case, the settings may not be at the powerup default values.
  3. The powerup defaults may be different on different processors, so setting them in code makes the code more portable.
  4. It documents what the settings are. If these registers are explicitly set on startup, then someone looking at the code doesn't have to go digging in the datasheet to see what they are set to.
  5. It documents that you care. Let the hardware default the settings you aren't using, but explicitly set the ones you rely on. This may alert some future maintainer to the importance of these particular settings.
  • \$\begingroup\$ It may be worth noting that if FOO->CTL has a default value of 0x12345678, and one only cares about having the lower bits set to 8, there's a clarity/code-space/performance trade-off between writing the entire register to 0x12345678, versus using something like maskedwrite32(&(FOO->CTL), BLAH_MASK, BLAH_MODE8);. If the masked-write routine includes code to make it atomic in case of interrupts, that may make it slower than it needs to be, but improve the code's generality. \$\endgroup\$
    – supercat
    Commented Jan 20, 2014 at 17:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.