Dynamic Wi-Fi transmit power control for M5StickC Plus 2.
Is your feature request related to a problem? Please describe. I'm often frustrated when using M5StickC Plus 2 on battery power because the Wi-Fi range is limited. The device sometimes struggles to maintain a stable connection when far from the router, reducing usability for portable projects.
Describe the solution you'd like I would like the device to automatically adjust its Wi-Fi transmit power depending on the power source: USB power: use maximum transmit power (19.5 dBm) for best range. Battery power: reduce transmit power (e.g., 15 dBm) to save energy and extend battery life. The device should detect the power source automatically using the built-in AXP power management IC.
Describe alternatives you've considered Manually changing Wi-Fi transmit power in the code each time the device switches between USB and battery. Using external Wi-Fi repeaters to increase range. Both alternatives are less convenient or require extra hardware.
Additional context This feature will make portable M5StickC Plus 2 projects more reliable without significantly affecting battery life. It is compatible with existing _wifiConnect and _connectToWifiNetwork functions.
CODE
1. Include M5 library only on ESP32:
#ifdef ESP32
#include <M5StickC.h> // Only for ESP32 / M5StickC
#endif
2. Function to detect power source (USB or battery):
bool isUSBPowered() {
#ifdef ESP32
float vbat = M5.Axp.GetBatVoltage(); // Read battery voltage
return vbat > 4.0; // >4.0V means USB powered
#else
return true; // On other platforms, assume USB to avoid errors
#endif
}
3. Set Wi-Fi transmit power based on power source:
WiFi.mode(WIFI_MODE_STA); // Enable Wi-Fi in station mode
// Dynamic transmit power
WiFi.setTxPower(isUSBPowered() ? WIFI_POWER_19_5dBm : WIFI_POWER_15dBm)
USB: maximum power 19.5 dBm
Battery: reduced power 15 dBm to save energy
4. Using it inside the Wi-Fi connect function:
bool _connectToWifiNetwork(const String &ssid, const String &pwd) {
WiFi.mode(WIFI_MODE_STA);
// Apply dynamic power before connecting
WiFi.setTxPower(isUSBPowered() ? WIFI_POWER_19_5dBm : WIFI_POWER_15dBm);
...
}