ESP32_Coding_Cheatsheet_Full
ESP32_Coding_Cheatsheet_Full
void setup() {
// Code runs once when the ESP32 starts
}
void loop() {
// Code runs continuously in a loop
}
2. Understanding delay(ms)
The delay(ms) function pauses the program for a specified time in milliseconds.
void setup() {
pinMode(LED_PIN, OUTPUT); // Set LED pin as output
}
void loop() {
digitalWrite(LED_PIN, HIGH); // Turn LED on
delay(1000); // Wait for 1 second
digitalWrite(LED_PIN, LOW); // Turn LED off
delay(1000); // Wait for 1 second
}
void setup() {
pinMode(LED_PIN, OUTPUT); // LED as output
pinMode(BUTTON_PIN, INPUT); // Button as input
}
void loop() {
if (digitalRead(BUTTON_PIN) == HIGH) { // Check if button is pressed
digitalWrite(LED_PIN, HIGH); // Turn LED on
} else {
digitalWrite(LED_PIN, LOW); // Turn LED off
}
}
void setup() {
pinMode(BUTTON_PIN, INPUT_PULLUP); // Enable internal pull-up resistor
pinMode(LED_PIN, OUTPUT);
}
void loop() {
if (digitalRead(BUTTON_PIN) == LOW) { // Button pressed (pull-up active)
digitalWrite(LED_PIN, HIGH);
} else {
digitalWrite(LED_PIN, LOW);
}
}
void setup() {
Serial.begin(115200); // Start serial communication
}
void loop() {
int value = analogRead(POT_PIN); // Read analog value (0-4095)
Serial.println(value); // Print value to Serial Monitor
delay(500);
}
void setup() {
ledcSetup(PWM_CHANNEL, PWM_FREQUENCY, PWM_RESOLUTION);
ledcAttachPin(LED_PIN, PWM_CHANNEL);
}
void loop() {
for (int brightness = 0; brightness <= 255; brightness++) {
ledcWrite(PWM_CHANNEL, brightness); // Adjust brightness
delay(10);
}
for (int brightness = 255; brightness >= 0; brightness--) {
ledcWrite(PWM_CHANNEL, brightness);
delay(10);
}
}
7. Serial Communication
void setup() {
Serial.begin(115200); // Start serial communication
}
void loop() {
Serial.println("Hello ESP32!"); // Print message to Serial Monitor
delay(1000);
}
8. Connecting to Wi-Fi
#include <WiFi.h>
void setup() {
Serial.begin(115200);
WiFi.begin(ssid, password);
Serial.println("Connected to Wi-Fi");
}
void loop() {}
#include <WiFi.h>
#include <WebServer.h>
WebServer server(80);
const int LED = 2;
void handleRoot() {
digitalWrite(LED, !digitalRead(LED)); // Toggle LED state
server.send(200, "text/plain", "LED Toggled");
}
void setup() {
Serial.begin(115200);
WiFi.begin(ssid, password);
pinMode(LED, OUTPUT);
server.on("/", handleRoot);
server.begin();
}
void loop() {
server.handleClient(); // Handle web requests
}
void setup() {
esp_sleep_enable_timer_wakeup(SLEEP_TIME * 1000000); // Set wakeup timer
esp_deep_sleep_start(); // Enter deep sleep mode
}
void loop() {}