bit-banding

STM32f103 (cortex)
anyone seen any advantage from bit-banding. I have employed it a few places and always found it to be no savings in time or space.

Erik

Parents
  • One advantage of bit banding is that it allows code to write to a single bit in a register without regard for whether an interrupt or some other task might attempt to write other bits.

    Suppose, for example, that some code wanted to set an I/O pin high. The code:

      MY_PORT_REG |= MY_PIN_MASK;
    


    would be translated into a three-instruction sequence similar to:

      ldr r0,[r1,#MY_PORT_REG_displacement] ; Assumes R1 points somewhere close to MY_PORT_REG
      orr r0,#MY_PIN_MASK
      str r0,[r1,#MY_PORT_REG_displacement]
    


    If an interrupt routine writes to MY_PORT_REG (intending to change OTHER bits) between the first and third instruction, the value written to MY_PORT_REG would not reflect that change, and so those bits would be set back to the value they held before the interrupt.

    One could avoid this problem by using load-exclusive and store-exclusive, e.g.

      while(__strex(&MY_PORT_REG, __ldrex(&MY_PORT_REG) | MY_PIN_MASK)) {}  // Repeat until it works
    


    This code will execute like three instructions like the above, except that it uses special versions of the LDR and STR instructions which say that the store should be skipped if something else touches the register between the load and the store, and should return a flag indicating whether it was executed or skipped. The while() loop will cause the read-modify-write sequence to be repeated until it succeeds.

    That approach is workable for many applications, but it's little clunky. Bit banding allows the code to be greatly simplified in the common case where the objective is simply to set or clear a single bit.

Reply Children
No data
More questions in this forum