Page 1 of 1

Length of time to compile code

Posted: Fri Jan 02, 2026 3:56 pm
by dandanattack
Hi all,

New to this forum and ESP32's but I had a question about compiling. This code takes forever and a day to compile. Anyone have any idea how to speed it up? It might be too complicated...?

Code: Select all

#include <Arduino.h>
#include <WiFi.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_BME280.h>
#include "time.h"
#include <ESP_Google_Sheet_Client.h>
#include "ESP32_NOW.h"

// For SD/SD_MMC mounting helper
#include <GS_SDHelper.h>

// ---------- Pins ----------
#define GREEN_LED_PIN 2
#define BATTERY_PIN 33
#define SDA_PIN 26
#define SCL_PIN 27

// ---------- ESP-NOW ----------
#define ESPNOW_WIFI_CHANNEL 6

// ---------- ADC / Voltage Divider ----------
#define ADC_MAX 4095.0
#define ADC_REF_VOLTAGE 3.3
#define R_TOP 27000.0
#define R_BOTTOM 100000.0

// ---------- WiFi ----------
const char* ssid = "xxxxxx";
const char* password = "xxxxxx";

// --------- Google Project ID ---------
#define PROJECT_ID "xxxxxx"

// --------- Service Account's client email ---------
#define CLIENT_EMAIL "xxxxxxx"

// --------- Service Account's private key ---------
const char PRIVATE_KEY[] PROGMEM = "-----BEGIN PRIVATE KEY-----\nxxxxxx=\n-----END PRIVATE KEY-----\n";

// -------- The ID of the spreadsheet where you'll publish the data --------
const char spreadsheetId[] = "xxxxxxxx";

// Timer variables
unsigned long lastTime = 0;  
unsigned long timerDelay = 30000;

// Token Callback function
void tokenStatusCallback(TokenInfo info);

// ---------- Google Apps Script ----------
//const char* serverName =
//"https://script.google.com/macros/s/xxxxxxxx/exec";

// ---------- Deep Sleep ----------
#define uS_TO_S_FACTOR 1000000ULL
#define TIME_TO_SLEEP 300  // 5 minutes

Adafruit_BME280 bme;

// ---------- ESP-NOW Data ----------
typedef struct {
  float temperature;
  float humidity;
  float pressure;
  float battery;
} WeatherPacket;

WeatherPacket packet;

// -------- NTP server to request epoch time --------
const char* ntpServer = "pool.ntp.org";

// -------- Variable to save current epoch time --------
unsigned long epochTime; 

// -------- Function that gets current epoch time --------
unsigned long getTime() {
  time_t now;
  struct tm timeinfo;
  if (!getLocalTime(&timeinfo)) {
    //Serial.println("Failed to obtain time");
    return(0);
  }
  time(&now);
  return now;
}

// ---------- Battery Voltage ----------
float readBatteryVoltage() {
  int raw = analogRead(BATTERY_PIN);
  float v_adc = (raw / ADC_MAX) * ADC_REF_VOLTAGE;
  float v_batt = v_adc * ((R_TOP + R_BOTTOM) / R_BOTTOM);
  return v_batt;
}

// ---------- ESP-NOW ----------
void initEspNow() {
  WiFi.mode(WIFI_STA);
  WiFi.setChannel(ESPNOW_WIFI_CHANNEL);
  WiFi.setSleep(false);

  if (!ESP_NOW.begin()) {
    Serial.println("ESP-NOW init failed");
    return;
  }

  esp_now_peer_info_t peer{};
  memcpy(peer.peer_addr, ESP_NOW.BROADCAST_ADDR, 6);
  peer.channel = ESPNOW_WIFI_CHANNEL;
  peer.ifidx = WIFI_IF_STA;
  peer.encrypt = false;

  if (!esp_now_is_peer_exist(peer.peer_addr)) {
    esp_now_add_peer(&peer);
  }

  Serial.println("ESP-NOW ready");
}

void sendEspNow() {
  esp_err_t result = esp_now_send(
    ESP_NOW.BROADCAST_ADDR,
    (uint8_t*)&packet,
    sizeof(packet)
  );

  Serial.print("ESP-NOW send: ");
  Serial.println(result == ESP_OK ? "OK" : "FAIL");
}

// ---------- Send to Google ----------
//void sendToGoogle(float t, float h, float p, float b) {
  //if (WiFi.status() != WL_CONNECTED) return;

  //Serial.println("Posting JSON:");
  //Serial.print("Temp: "); Serial.println(t);
  //Serial.print("Humidity: "); Serial.println(h);
  //Serial.print("Pressure: "); Serial.println(p);
  //Serial.print("Battery: "); Serial.println(b);

  //HTTPClient http;
  //http.setFollowRedirects(HTTPC_STRICT_FOLLOW_REDIRECTS);
  //http.begin(serverName);
  //http.addHeader("Content-Type", "application/json");

  //String payload = "{";
  //payload += "\"temperature\":" + String(t, 2) + ",";
  //payload += "\"humidity\":" + String(h, 2) + ",";
  //payload += "\"pressure\":" + String(p, 2) + ",";
  //payload += "\"battery\":" + String(b, 2);
  //payload += "}";

  //int code = http.POST(payload);
  //Serial.print("HTTP response: ");
  //Serial.println(code);

  //http.end();
//}


// ---------- Sleep ----------
void goToSleep() {
  digitalWrite(GREEN_LED_PIN, LOW);
  Serial.println("Going to deep sleep...");
  esp_sleep_enable_timer_wakeup(TIME_TO_SLEEP * uS_TO_S_FACTOR);
  delay(100);
  esp_deep_sleep_start();
}

// ---------- Setup ----------
void setup() {
  Serial.begin(115200);
  delay(1000);
  
  //Configure time
  configTime(0, 0, ntpServer);
  
  pinMode(GREEN_LED_PIN, OUTPUT);
  digitalWrite(GREEN_LED_PIN, HIGH);

  analogReadResolution(12);
  Wire.begin(SDA_PIN, SCL_PIN);

  // Initialize BME280 sensor
  if (!bme.begin(0x76)) {
    Serial.println("BME280 not found!");
    goToSleep();
  }

  Serial.println("BME280 OK");

  // ---- Read sensors ----
  packet.temperature = bme.readTemperature() * 9.0 / 5.0 + 32.0;
  packet.humidity = bme.readHumidity();
  packet.pressure = bme.readPressure() / 100.0;
  packet.battery = readBatteryVoltage();

  Serial.println("Readings:");
  Serial.print("Temp F: "); Serial.println(packet.temperature);
  Serial.print("Humidity: "); Serial.println(packet.humidity);
  Serial.print("Pressure: "); Serial.println(packet.pressure);
  Serial.print("Battery V: "); Serial.println(packet.battery);

  // ---- ESP-NOW broadcast ----
  initEspNow();
  sendEspNow();

  GSheet.printf("ESP Google Sheet Client v%s\n\n", ESP_GOOGLE_SHEET_CLIENT_VERSION);
  
  // ---- Switch back to normal Wi-fi ----
  WiFi.disconnect(true);
  delay(100); // brief radio settle

  // ---- WiFi + Google ----
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);
  Serial.print("Connecting WiFi");

  Serial.print("Connecting to Wi-Fi");
    while (WiFi.status() != WL_CONNECTED) {
      Serial.print(".");
      delay(1000);
    }
    Serial.println();
    Serial.print("Connected with IP: ");
    Serial.println(WiFi.localIP());
    Serial.println();

    // Set the callback for Google API access token generation status (for debug only)
    GSheet.setTokenCallback(tokenStatusCallback);

    // Set the seconds to refresh the auth token before expire (60 to 3540, default is 300 seconds)
    GSheet.setPrerefreshSeconds(10 * 60);

    // Begin the access token generation for Google API authentication
    GSheet.begin(CLIENT_EMAIL, PROJECT_ID, PRIVATE_KEY);
}

  //sendToGoogle(
    //packet.temperature,
    //packet.humidity,
    //packet.pressure,
    //packet.battery
  //);

  //goToSleep();
//}

void loop(){
    // Call ready() repeatedly in loop for authentication checking and processing
    bool ready = GSheet.ready();

    if (ready && millis() - lastTime > timerDelay){
        lastTime = millis();

        FirebaseJson response;

        Serial.println("\nAppend spreadsheet values...");
        Serial.println("----------------------------");

        FirebaseJson valueRange;

        // New BME280 sensor readings
        temp = bme.readTemperature();
        //temp = 1.8*bme.readTemperature() + 32;
        hum = bme.readHumidity();
        pres = bme.readPressure()/100.0F;
        // Get timestamp
        epochTime = getTime();

        valueRange.add("majorDimension", "COLUMNS");
        valueRange.set("values/[0]/[0]", epochTime);
        valueRange.set("values/[1]/[0]", temperature);
        valueRange.set("values/[2]/[0]", humidity);
        valueRange.set("values/[3]/[0]", pressure);
        valueRange.set("values/[4]/[0]", battery);

        // For Google Sheet API ref doc, go to https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/append
        // Append values to the spreadsheet
        bool success = GSheet.values.append(&response /* returned response */, spreadsheetId /* spreadsheet Id to append */, "Sheet1!A1" /* range to append */, &valueRange /* data range to append */);
        if (success){
            response.toString(Serial, true);
            valueRange.clear();
        }
        else{
            Serial.println(GSheet.errorReason());
        }
        Serial.println();
        Serial.println(ESP.getFreeHeap());
    }
}

void tokenStatusCallback(TokenInfo info){
    if (info.status == token_status_error){
        GSheet.printf("Token info: type = %s, status = %s\n", GSheet.getTokenType(info).c_str(), GSheet.getTokenStatus(info).c_str());
        GSheet.printf("Token error: %s\n", GSheet.getTokenError(info).c_str());
    }
    else{
        GSheet.printf("Token info: type = %s, status = %s\n", GSheet.getTokenType(info).c_str(), GSheet.getTokenStatus(info).c_str());
    }
}

Re: Length of time to compile code

Posted: Sun Jan 04, 2026 9:35 am
by summat
It would be useful to include details of the compiler tool-chain that you're using for this question.

For example,
* Arduino IDE Version xyz
* Visual Studio Code + PlatformIO Version xyz
* Espressif IDF Version xyz
* Espressif IDE Version xyz with IDF Version xyz

Also, your host computer basics - e.g. Linux, Mac, or Windows?

For what it's worth - I've experienced sluggish compile times with earlier Arduino IDEs, seems much better on my Mac M1 Studio with Arduino IDE Version 2.3.7 - takes about 20 seconds for a clean build of Blink, and about 12 seconds thereafter. Earlier versions of the Arduino IDE could take several minutes. Remember, in building for the ESP you're building the RTOS as well as your application (and any other partitions that you have) - so these can/will take longer than any experience that you have on simpler bare-metal targets (e.g. the AT-Mega based target processors - Arduino Nano/Mega etc).

Build times were, particularly with earlier Arduino IDEs, one of the main reasons I've migrated "elsewhere" - I'm currently favouring the Visual Studio Code (v1.107.1) with the PlatformIO extension (Core V6.1.19a2), again on Mac silicon, which significantly out-performs the Arduino IDE in terms of speed and capability. This isn't a recommendation, but perhaps a nudge that there are a number of different environments that may suit your needs better.

Re: Length of time to compile code

Posted: Mon Jan 05, 2026 7:49 pm
by Didier99
In my experience, even the current Arduino IDE takes a long time to compile, even after small incremental code changes. It seems that it needs to check that the libraries have not changed to make sure it does not need to recompile, so even though it eventually finds that the libraries have not changed, on a complex project that checking can take a while. I suppose it is because libraries can be updated asynchronously in the background so it needs to check each and every single time you recompile, even for a trivial code change.

PlatformIO works very effectively around that by copying the libraries in the project so they do not get updated unless you want them to so incremental compilation is very fast. The difference is even greater if you just want to reflash the same code. On a relatively simple project with WiFi, the difference in flashing time on my ~5 year old machine is between 3 minutes on Arduino IDE and 20 seconds on PlatformIO. This is also a great benefit for configuration control in a professional environment, or even serious hobbyist. You know the libraries are not being updated unless you affirmatively decide to.

The issue with library updates is even more frustrating with Arduino IDE because the nagging when libraries need to be updated is considerable, and when you update libraries you sometimes break old projects in ways that are not always easy to fix, even though whatever problem was fixed with the new library did not affect you.

In balance, I prefer the way PlatformIO works considerably better. Not only it is much faster but you can keep a copy of an old project and rebuild it 2 years later and there will be zero problems. With Arduino IDE, it's a crap shoot.