Skip to content

[GPIO-Design] Undetermined behavior on gpio_set(...) API #6

Description

@pavly-gerges

Just navigating the content, and I am bit curious about this piece of code:
https://github.com/arm-university/Efficient-Embedded-Systems-Design-Education-Kit/blob/cadb6880c8a416f00c974cdb549781e04ea834c1/NUCLEO-F401RE/contents/Module07_GeneralPurposeDigitalInterfacing/Lab04_GeneralPurposeDigitalInterfacing/Code/GPIOBasicUI_lab/drivers/gpio.c#L22-L29

The problem will arise in case the user has inserted something else, other than the boolean zero or one. To disable the user from doing so, a preprocessing automaton must include a way to clamp the values to either zero or 1.

I did this trick before on my SDK, here:

void gpio_write(const gpio_port port, const uint8_t pin, uint8_t state) {
    *(port.DDRx) |= (1 << pin);
    /* Recall, PORTx = 0b01100000
       And, we want to change PINx4 to one
       Then, 1) Disable PORTxn first, through [(*(port.PORTx) & (~(1 << pin))].
             2) Add a state to PINxn, through [state << pin].
             3) Apply the PINxn_STATE to the PORT via [PORTxn_DISABLED | PINxn_STATE].
             4) Add the pin state to the PORT via [PORTxn_DISABLED | PINxn_STATE].
       So, PORTx = (0b01100000 & 0b11101111) | ((0b00010000) & (0b11111111)) 
                 = 0b01100000 | 0b00010000 = 0b01110000 */
    const volatile uint8_t PORTxn_DISABLED = (*(port.PORTx) & ~(1 << pin));
    const volatile uint8_t PINxn_STATE = (state && 0xFF) << pin; // this line here!
    *(port.PORTx) = PORTxn_DISABLED | PINxn_STATE;
} 

https://github.com/Electrostat-Lab/Electrostatic-Sandbox/blob/412fb970493d889992ae56ebfa0a3a4bebdbb12a/electrostatic-sandbox-framework/electrostatic-core/src/libs/electrostatic-primer/electroio/electromio/avr/libgpio/gpio_write.c#L3-L16

Just convert the value to logical value by ANDing it with 1. Or else use boolean data type for the pin value.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions