Search code examples
cesp32freertos

construct union dynamically in C


I'm trying to set configuration of WIFI with ESP32 dynamically.

Depends on UUID of device ID, I would like to set SSID.

I was trying to put character variable. However, I failed



 // Original code
   wifi_config_t ap_config =
       {
           .ap = {
               .ssid = 'WIFI_SSID', // I would like to change .ssid as variable
               .ssid_len = strlen(WIFI_AP_SSID),
               .password = WIFI_AP_PASSWORD,
               .channel = WIFI_AP_CHANNEL,
               .ssid_hidden = WIFI_AP_SSID_HIDDEN,
               .authmode = WIFI_AUTH_WPA2_PSK,
               .max_connection = WIFI_AP_MAX_CONNECTIONS,
               .beacon_interval = WIFI_AP_BEACON_INTERVAL,
           },
       };


// For example, I would like to set SSID name by using another variable
char ssid[10] = "anoter_ssid_name";

wifi_config_t ap_config =
       {
           .ap = {
               .ssid = ssid, // I would like to change .ssid as variable
               .ssid_len = strlen(WIFI_AP_SSID),
           },
       };



Solution

  • This is definitely wrong:

    .ssid = 'WIFI_SSID', 
    

    Next: Basically, you can't use not const expressions in static storage duration initializers. You need to do it in the function.

    wifi_config_t ap_config =
    {
        .ap = {
            .ssid = "WIFI_SSID", // I would like to change .ssid as variable
            .ssid_len = sizeof("WIFI_SSID") - 1,
            .password = WIFI_AP_PASSWORD,
            .channel = WIFI_AP_CHANNEL,
            .ssid_hidden = WIFI_AP_SSID_HIDDEN,
            .authmode = WIFI_AUTH_WPA2_PSK,
            .max_connection = WIFI_AP_MAX_CONNECTIONS,
            .beacon_interval = WIFI_AP_BEACON_INTERVAL,
        },
    };
    
    wifi_config_t *setSSID(wifi_config_t *cfg, const char *ssid)
    {
        strcpy(cfg -> ssid, ssid);
        cfg -> ssid_len = strlen(ssid);
        rerutn cfg;
    }