Search code examples
embeddedstm32

how to lock a GPIO pin configuration in stm32f4?


I am implementing my own version for stm32f407 drivers. so I came to that section mentioning how to lock a GPIO pin configuration and that's what they said on the reference manual page 285:

LOCK key write sequence:
WR LCKR[16] = ‘1’ + LCKR[15:0]
WR LCKR[16] = ‘0’ + LCKR[15:0]
WR LCKR[16] = ‘1’ + LCKR[15:0]
RD LCKR
RD LCKR[16] = ‘1’ (this read operation is optional but it confirms that the lock is active)  

The problem is that I don't understand what LCKR[16] = ‘1’ + LCKR[15:0] means. As LCKR[16] is only 1-bit while ‘1’ + LCKR[15:0] is 16 bits, how shall I assign a 16-bit value to a 1-bit value? and why ‘0’ + LCKR[15:0] is even written like that? isn't ‘0’ + LCKR[15:0] same as LCKR[15:0] ?


Solution

  • The problem is that I don't understand what LCKR[16] = ‘1’ + LCKR[15:0] means.

    It is a bit confusing notation. It should be:

    WR LCKR = (LCKR[16] = ‘1’) + LCKR[15:0].
    WR LCKR = (LCKR[16] = ‘0’) + LCKR[15:0]
    WR LCKR = (LCKR[16] = ‘1’) + LCKR[15:0]
    RD LCKR
    RD (LCKR[16] = ‘1’) 
    

    In C language it will be:

    /**
     * @fn int lockPins(GPIO_TypeDef*, uint16_t)
     * @brief locks / unlocks the pins
     * 
    
     * @param gpio - gpio to be locked
     * @param pins pins. Bits from 0 to 15 represents pins
     * @return 1 if lock was successful 
     */
    int lockPins(GPIO_TypeDef *gpio, uint16_t pins)
    {
        gpio -> LCKR = (1 << 16) | pins;
        gpio -> LCKR = pins;
        gpio -> LCKR = (1 << 16) | pins;    
        (void)gpio -> LCKR;
        return !!(gpio -> LCKR & (1 << 16));
    }