How to fix ESP32 PlatformIO error: ‘LED_BUILTIN’ was not declared in this scope

Problem:

When trying to compile your ESP32 firmware using PlatformIO, you see this error message:

src/main.cpp: In function 'void setup()':
src/main.cpp:22:13: error: 'LED_BUILTIN' was not declared in this scope
     pinMode(LED_BUILTIN, OUTPUT);

Solution:

Important: Some ESP32 boards such as the ESP32-DevKitC have no builtin LED at all ! Either connect an external LED or find another method of doing whatever you are intending to do.

On most ESP32 boards that do have a builtin LED, the LED is connected to pin 2 – however, PlatformIO does not define LED_BUILTIN p. In order to fix the issue, define LED_BUILTIN yourself by using

#define LED_BUILTIN 2

at the top of every file where you see this error.