Search code examples
cstm32cubeide

C array struct initialisation and call


what is the right way to initialise and call the struct in C language STM32typedef

struct motor_struct {
    uint32_t yellow_clicks;
    uint32_t green_clicks;
    uint8_t pin;
    GPIO_TypeDef port;
    _Bool green_hall;
    _Bool yellow_hall;

} motors[4];



//motors(yellow_clicks) = {0,0,0,0}; - *compile without error but what is gone inside?*
motors[0].yellow_clicks  = 0; *- get an error*

Solution

  • You can only do something like:

    motors[0].yellow_clicks  = 0;
    

    inside a function. If you want to initialise your array of structures at compile-time, you'll need something like:

    struct motor_struct {
        uint32_t yellow_clicks;
        uint32_t green_clicks;
        uint8_t pin;
        GPIO_TypeDef port;
        _Bool green_hall;
        _Bool yellow_hall;
    
    } motors[4] = {
        {0, 0, 1, GPIOA, false, false}, // motors[0]
        {1, 1, 2, GPIOB, true, false},  // motors[1]
        {0, 1, 1, GPIOC, true, true},   // motors[2]
        {1, 2, 3, GPIOA, true, true}    // motors[3]
    };
    

    Of course using values that make sense for you.