Become a Maker – Materials

Thank you for choosing my book!

On this page, you’ll find the sketches that were too long to include in print. You’ll also have access to the LED Matrix Tool here. In addition, this page will feature updates to the book — such as corrections and additional notes.

I wish you lots of fun and success with the projects!

Complete Sketches

Here you’ll find the complete sketches that go with the projects in the book. You can copy them directly, modify them, and upload them to your Arduino or ESP32.

10 A Music Box with Loops
				
					// Simple melody player using a piezo buzzer
// Plays a sequence of tones on pin 10

const int piezoPin = 10;

void setup() {
  pinMode(piezoPin, OUTPUT);

  for (int i = 0; i < 3; i++) {
    // play E4
    tone(piezoPin, 329.63, 300);
    delay(350);
    // play D#4
    tone(piezoPin, 311.13, 300);
    delay(350);
    // play E4
    tone(piezoPin, 329.63, 300);
    delay(350);
    // play D#4
    tone(piezoPin, 311.13, 300);
    delay(350);
    // play E4
    tone(piezoPin, 329.63, 300);
    delay(350);
    // play B3
    tone(piezoPin, 246.94, 300);
    delay(400);
    // play D4
    tone(piezoPin, 293.66, 300);
    delay(400);
    // play C4
    tone(piezoPin, 261.63, 300);
    delay(400);
    // play A3
    tone(piezoPin, 220, 900);
    delay(1000);
    // play D3
    tone(piezoPin, 146.83, 300);
    delay(350);
    // play F3
    tone(piezoPin, 174.61, 300);
    delay(400);
    // play A3
    tone(piezoPin, 220, 300);
    delay(400);
    // play B3
    tone(piezoPin, 246.94, 900);
    delay(1000);
    // play F3
    tone(piezoPin, 174.61, 300);
    delay(400);
    // play A#3
    tone(piezoPin, 233.08, 300);
    delay(400);
    // play B3
    tone(piezoPin, 246.94, 300);
    delay(400);
    // play C4
    tone(piezoPin, 261.63, 900);
    delay(1000);
    
  }
}

void loop() {
  // nothing to do here
}

				
			
				
					const int trigger = 7;
const int echo = 6;
const int piezo = 10;
int distance = 0;
int distanceHigh = 0;
int lengthOfScale = 0;
int note = 0;

// A minor pentatonic scale
int scale[] = {
  147, 165, 196, 220, 262, 294, 330, 392, 440,
  523, 587, 659, 784, 880, 1047, 1175, 1319, 1568,
  1760, 2093, 2349
};

// C major scale
// int scale[] = {
//   131, 147, 165, 175, 196, 220, 247, 262, 294,
//   330, 349, 392, 440, 494, 523, 587, 659, 698,
//   784, 880, 988, 1047
// };

void setup() {
  Serial.begin(9600);
  pinMode(trigger, OUTPUT);
  pinMode(echo, INPUT);
  while (millis() < 3000) {
    digitalWrite(trigger, HIGH);
    digitalWrite(trigger, LOW);
    distance = pulseIn(echo, HIGH);
    if (distance > distanceHigh) {
      distanceHigh = distance;
    }
  }
  lengthOfScale = sizeof(scale) / sizeof(scale[0]);
  Serial.println(lengthOfScale);
}

void loop() {
  digitalWrite(trigger, HIGH);
  delay(10);
  digitalWrite(trigger, LOW);
  distance = pulseIn(echo, HIGH);
  Serial.println(distance);
  note = map(distance, 100, distanceHigh, scale[0], scale[lengthOfScale - 1]);
  for (byte j = 0; j < (lengthOfScale); j++) {
    if (note == scale[j]) {
      tone(piezo, note);
      break;
    } else if (note > scale[j] && note < scale[j + 1]) {
      note = scale[j];
      Serial.println(note);
      tone(piezo, note);
      break;
    }
  }
  delay(30);
}

				
			
				
					const int ledRed = 11;
const int ledGreen = 10;
const int ledBlue = 9;

int brightnessRed = 150;
int brightnessGreen = 150;
int brightnessBlue = 150;

const int noise = 0;

const int sensor = A1;

int piezo = 4;

void setup() {
  pinMode(ledRed, OUTPUT);
  pinMode(ledGreen, OUTPUT);
  pinMode(ledRed, OUTPUT);
  pinMode(piezo, OUTPUT);
  Serial.begin(9600);
}

void loop() {
  noise = analogRead(sensor);
  Serial.println(noise);
  if(noise <= 200){
    analogWrite(ledGreen, brightnessGreen);
    analogWrite(ledRed, 0);
    analogWrite(ledBlue, 0);
    digitalWrite(piezo, LOW);
    }
    else if(noise > 200 && noise <= 350){
      analogWrite(ledRed, brightnessRed);
      analogWrite(ledGreen, brightnessGreen);
      analogWrite(ledBlue, 0);
      digitalWrite(piezo, LOW);
      }
      else if(noise > 350){
        analogWrite(ledRed, brightnessRed);
        analogWrite(ledGreen, 0);
        analogWrite(ledBlue, 0);
        digitalWrite(piezo, HIGH);
        delay(10000);
        }
}
				
			
				
					#include <LiquidCrystal.h>

LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

#include "DHT.h"
#define DHTPIN 7
#define DHTTYPE DHT11

DHT dht(DHTPIN, DHTTYPE);

float temp;
float humidity;

void setup() {
  Serial.begin(9600);
  lcd.begin(16, 2);
  dht.begin();
}

void loop() {
  temp = dht.readTemperature();
  humidity = dht.readHumidity();
  Serial.print("Temperature: ");
  Serial.print(temp);
  Serial.println(" *C");
  Serial.print("Humidity: ");
  Serial.print(humidity);
  Serial.println(" %");
  Serial.println();
  
  //Display temperature
  lcd.setCursor(0, 0);
  lcd.print(temp + String(" C"));
  
  //Display humidity
  lcd.setCursor(0, 1);
  lcd.print(humidity + String(" %"));
  delay(10000);
}
				
			
				
					#include "DHT.h"
#define DHTPIN 7
#define DHTTYPE DHT11
#define ENABLE 5
#define DIRA 3
#define DIRB 4

float temp;

DHT dht(DHTPIN, DHTTYPE);

void setup() {
  pinMode(ENABLE, OUTPUT);
  pinMode(DIRA, OUTPUT);
  pinMode(DIRB, OUTPUT);
  Serial.begin(9600);
  dht.begin();
}

void loop() {
  temp = dht.readTemperature();
  Serial.print("Temperature: ");
  Serial.print(temp);
  Serial.println(" *C");
  
  if (temp > 22) {
    digitalWrite(ENABLE, HIGH);
    digitalWrite(DIRA, HIGH);
    digitalWrite(DIRB, LOW);
  }
  else {
    digitalWrite(ENABLE, LOW);
  }
  delay(1000);
}
				
			
				
					#include <Adafruit_Keypad.h>
#include <Servo.h>

// Constants for the keypad matrix
const byte ROWS = 4;
const byte COLS = 4;

// Key layout
char keys[ROWS][COLS] = {
  { '1', '2', '3', 'A' },
  { '4', '5', '6', 'B' },
  { '7', '8', '9', 'C' },
  { '*', '0', '#', 'D' }
};

// Pin assignment for the keypad matrix
byte rowPins[ROWS] = { 9, 8, 7, 6 };
byte colPins[COLS] = { 5, 4, 3, 2 };

// Initialize the keypad
Adafruit_Keypad customKeypad = Adafruit_Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);

// Variables and constants
char key;
String inputCode;
const String code = "1103A";  // The code you have set

Servo servo;
const int redLED = 12;
const int greenLED = 13;

void setup() {
  Serial.begin(9600);
  pinMode(redLED, OUTPUT);
  pinMode(greenLED, OUTPUT);
  servo.attach(11);
  customKeypad.begin();
}

void loop() {
  customKeypad.tick();

  while (customKeypad.available()) {
    keypadEvent e = customKeypad.read();
    key = e.bit.KEY;

   if (e.bit.EVENT == KEY_JUST_PRESSED) {
      if (key == '*') {
        inputCode = "";
        Serial.println("Lock engaged.");
        delay(1000);
        servo.write(90);
        digitalWrite(greenLED, LOW);
        digitalWrite(redLED, HIGH);
      } else if (key == '#') {
        if (inputCode == code) {
          Serial.println("The code is correct.");
          digitalWrite(greenLED, HIGH);
          digitalWrite(redLED, LOW);
          servo.write(0);
        } else {
          Serial.println("The code is incorrect!");
          digitalWrite(greenLED, LOW);
          digitalWrite(redLED, HIGH);
        }
        inputCode = "";
        
      } else {
        inputCode += key;
        Serial.println(inputCode);
      }
    }
  }
  delay(10);
}

				
			
				
					#include "Arduino_LED_Matrix.h"
ArduinoLEDMatrix matrix;
byte heart[8][12] = {
  { 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0 },
  { 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0 },
  { 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0 },
  { 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0 },
  { 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0 },
  { 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0 },
  { 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0 },
  { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }
};
void setup() {
  matrix.begin();
  matrix.renderBitmap(heart, 8, 12);
}
void loop() {
}
				
			
				
					#include "WiFiS3.h"

char ssid[] = "YOUR WIFI NETWORK";
char pass[] = "YOUR PASSWORD";  

void setup() {
  Serial.begin(9600);
  delay(1000);

  Serial.println("Connecting to WiFi...");
  Serial.print("Network: ");
  Serial.println(ssid);

  WiFi.begin(ssid, pass);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  Serial.println("");
  Serial.println("Connection established!");

  delay(500);

  Serial.print("My IP address is: ");
  Serial.println(WiFi.localIP());
}

void loop() {
  // Nothing to do here yet.
}
				
			
				
					#include <WiFiS3.h>
#include <ArduinoHttpClient.h>
#include <ArduinoJson.h>

const char ssid[] = "YOUR WIFI NETWORK";
const char pass[] = "YOUR PASSWORD";

WiFiClient wifi;
HttpClient client = HttpClient(wifi, "api.open-notify.org", 80);

void setup() {
  Serial.begin(9600);
  while (!Serial) {
    ;
  }

  client.setTimeout(15000);

  Serial.print("Connecting to WiFi...");
  Serial.print("Network: ");
  Serial.println(ssid);

  WiFi.begin(ssid, pass);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  Serial.println("");
  Serial.println("Connection established!");
  delay(500);
  Serial.print("My IP address is: ");
  Serial.println(WiFi.localIP());
}

void loop() {
  if (WiFi.status() == WL_CONNECTED) {
    Serial.println("Sending request to the API server...");
    client.get("/astros.json");

    int httpCode = client.responseStatusCode();
    String responseBody = client.responseBody();

    if (httpCode == 200) {
      Serial.println("Response received successfully.");
      JsonDocument doc;
      DeserializationError error = deserializeJson(doc, responseBody);

      if (error) {
        Serial.print("deserializeJson() failed: ");
        Serial.println(error.c_str());
        return;
      }

      int number = doc["number"];
      Serial.print("Current number of astronauts in space: ");
      Serial.println(number);
    } else {
      Serial.print("HTTP request failed. Status code: ");
      Serial.println(httpCode);
    }

    // Close the connection after each request to free resources.
    client.stop();
  } else {
    Serial.println("Wi-Fi connection lost. Will check again in the next cycle.");
  }

  Serial.println("\nNext request in one hour.");
  delay(3600000);
}

				
			
				
					#include <WiFiS3.h>
#include <ArduinoHttpClient.h>
#include <ArduinoJson.h>
#include "Arduino_LED_Matrix.h"

// Global objects
WiFiClient wifi;
HttpClient client = HttpClient(wifi, "api.open-notify.org", 80);
ArduinoLEDMatrix matrix;

// Wi-Fi credentials
const char ssid[] = "YOUR WIFI NETWORK";
const char pass[] = "YOUR PASSWORD";

// --- Bitmaps for numbers 1–15 ---
byte one[8][12] = {
  { 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0 }
};
byte two[8][12] = {
  { 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }
};
byte three[8][12] = {
  { 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0 }, { 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 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 0, 1, 1, 1, 1, 0, 0 }, { 0, 0, 1, 1, 0, 0, 1, 0, 0, 1, 0, 0 }, { 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0 }, { 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0 }, { 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 0, 0 }, { 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0 }, { 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0 }, { 0, 0, 1, 1, 1, 0, 1, 1, 1, 1, 0, 0 }
};
byte fourteen[8][12] = {
  { 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0 }, { 0, 0, 1, 1, 0, 0, 1, 0, 1, 0, 0, 0 }, { 0, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 0 }, { 0, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 0 }, { 0, 0, 0, 1, 0, 0, 1, 1, 1, 1, 0, 0 }, { 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0 }, { 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0 }, { 0, 0, 1, 1, 1, 0, 0, 1, 1, 1, 0, 0 }
};
byte fifteen[8][12] = {
  { 0, 0, 0, 1, 0, 0, 1, 1, 1, 1, 0, 0 }, { 0, 0, 1, 1, 0, 0, 1, 0, 0, 1, 0, 0 }, { 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0 }, { 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0 }, { 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0 }, { 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0 }, { 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0 }, { 0, 0, 1, 1, 1, 0, 1, 1, 1, 1, 0, 0 }
};

void setup() {
  Serial.begin(9600);
  while (!Serial) {
    ;
  }

  matrix.begin();
  client.setTimeout(15000);

  Serial.print("Connecting to Wi-Fi...");
  Serial.print("Network: ");
  Serial.println(ssid);

  WiFi.begin(ssid, pass);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  Serial.println("");
  Serial.println("Cnnection established!");
  delay(500);
  Serial.print("My IP address is: ");
  Serial.println(WiFi.localIP());
}

void loop() {
  if (WiFi.status() == WL_CONNECTED) {
    Serial.println("Sending request to the API server...");
    client.get("/astros.json");

    int httpCode = client.responseStatusCode();
    String responseBody = client.responseBody();

    if (httpCode == 200) {
      Serial.println("Response received successfully.");
      JsonDocument doc;
      DeserializationError error = deserializeJson(doc, responseBody);

      if (error) {
        Serial.print("deserializeJson() failed: ");
        Serial.println(error.c_str());
        return;
      }

      int number = doc["number"];
      Serial.print("Current number of astronauts in space: ");
      Serial.println(number);

      // Display the matching number bitmap on the LED matrix
      switch (number) {
        case 1: matrix.renderBitmap(one, 8, 12); break;
        case 2: matrix.renderBitmap(two, 8, 12); break;
        case 3: matrix.renderBitmap(three, 8, 12); break;
        case 4: matrix.renderBitmap(four, 8, 12); break;
        case 5: matrix.renderBitmap(five, 8, 12); break;
        case 6: matrix.renderBitmap(six, 8, 12); break;
        case 7: matrix.renderBitmap(seven, 8, 12); break;
        case 8: matrix.renderBitmap(eight, 8, 12); break;
        case 9: matrix.renderBitmap(nine, 8, 12); break;
        case 10: matrix.renderBitmap(ten, 8, 12); break;
        case 11: matrix.renderBitmap(eleven, 8, 12); break;
        case 12: matrix.renderBitmap(twelve, 8, 12); break;
        case 13: matrix.renderBitmap(thirteen, 8, 12); break;
        case 14: matrix.renderBitmap(fourteen, 8, 12); break;
        case 15: matrix.renderBitmap(fifteen, 8, 12); break;
        default:
          matrix.clear(); // Clear display if number is out of range
          break;
      }
    } else {
      Serial.print("HTTP request failed. Status code: ");
      Serial.println(httpCode);
    }

    // Close connection after each request
    client.stop();
  } else {
    Serial.println("Wi-Fi connection lost. Will check again in the next cycle.");
  }

  Serial.println("\nNext request in one hour.");
  delay(3600000);
}

				
			
				
					// Required libraries for the ESP32
#include <WiFi.h>          // Standard ESP32 library for Wi-Fi
#include <HTTPClient.h>    // Standard ESP32 library for HTTP requests
#include <ArduinoJson.h>   // Platform-independent JSON library

// --- Enter your Wi-Fi credentials here ---
const char ssid[] = "YOUR WIFI NETWORK";
const char pass[] = "YOUR PASSWORD";

void setup() {
  Serial.begin(115200); // The ESP32 can easily handle higher baud rates
  while (!Serial) {
    ; // Wait for the serial connection to be established
  }

  Serial.println("Starting sketch...");
  Serial.print("Connecting to Wi-Fi: ");
  Serial.println(ssid);

  // Start Wi-Fi connection
  WiFi.begin(ssid, pass);

  // Wait until the connection is established
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  Serial.println("\nWi-Fi connection established!");
  Serial.print("My IP address is: ");
  Serial.println(WiFi.localIP());
}

void loop() {
  // Check if the Wi-Fi connection is still active
  if (WiFi.status() == WL_CONNECTED) {
    HTTPClient http; // Create an HTTPClient object

    // Target URL for the API request
    String apiUrl = "http://api.open-notify.org/astros.json";
    Serial.println("Sending request to: " + apiUrl);

    http.begin(apiUrl); // Start the connection

    // Send the GET request and get the HTTP status code
    int httpCode = http.GET();

    if (httpCode > 0) { // HTTP code > 0 means a response was received
      Serial.printf("Response received, HTTP code: %d\n", httpCode);

      if (httpCode == HTTP_CODE_OK) { // Check if the request was successful (code 200)
        String responseBody = http.getString(); // Read the response as a string

        JsonDocument doc;
        DeserializationError error = deserializeJson(doc, responseBody);

        if (error) {
          Serial.print("deserializeJson() failed: ");
          Serial.println(error.c_str());
          return;
        }

        // Extract the number of astronauts from the JSON object
        int number = doc["number"];
        Serial.print("Current number of astronauts in space: ");
        Serial.println(number);
      }
    } else {
      Serial.printf("HTTP request failed: %s\n", http.errorToString(httpCode).c_str());
    }

    // Close the connection to free up resources
    http.end();

  } else {
    Serial.println("Wi-Fi connection lost. Will retry in the next cycle.");
  }

  Serial.println("\nNext request in one hour.");
  delay(3600000); // Wait for one hour (3,600,000 milliseconds)
}

				
			
				
					// Required library for the ESP32
#include <WiFi.h>

// --- Enter your Wi-Fi credentials here ---
const char ssid[] = "YOUR WIFI NETWORK";
const char pass[] = "YOUR PASSWORD";
// Create a server object on port 80 (standard for HTTP)
WiFiServer server(80);

void setup() {
  Serial.begin(115200);
  while (!Serial) {
    ;
  }

  Serial.println("\nStarting sketch...");
  Serial.print("Connecting to Wi-Fi: ");
  Serial.println(ssid);

  // Start the Wi-Fi connection
  WiFi.begin(ssid, pass);

  // Wait in a loop until the connection is established
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  Serial.println("\nWi-Fi connection established!");
  Serial.print("Server started! Open this address in your browser: http://");
  Serial.println(WiFi.localIP());
  Serial.println("---------------------------------");

  // Start the web server
  server.begin();
}

void loop() {
  // Check if a new client (e.g., a web browser) has connected
  WiFiClient client = server.available();

  if (client) { // If a client is available...
    Serial.println("\n[A new client has connected!]");

    // As long as the client is connected...
    while (client.connected()) {
      // ...and data is available to read...
      if (client.available()) {
        // Read the first line of the request (ignore the rest for this simple example)
        String line = client.readStringUntil('\n');

        // Once we receive a request, we send a response
        // and then exit the loop.

        // Send the HTTP response header
        client.println("HTTP/1.1 200 OK");
        client.println("Content-type:text/html; charset=utf-8");
        client.println("Connection: close"); // Important: tell the browser we'll close the connection
        client.println(); // Empty line separates header from content (required by HTTP protocol)

        // Send the actual HTML content (the webpage)
        client.println("<!DOCTYPE html>");
        client.println("<html><head><title>ESP32 Server</title></head><body>");
        client.println("<h1>Hello from the ESP32 Web Server!</h1>");
        client.println("<p>This page was served directly by your ESP32.</p>");
        client.println("</body></html>");

        // End the HTTP response with another empty line
        client.println();

        // Since we've sent everything, we can exit the loop
        break;
      }
    }

    // Give the browser a short moment to receive the data
    delay(10);

    // Close the connection to the client
    client.stop();
    Serial.println("[Client connection closed]");
  }
}

				
			
				
					// Required library for the ESP32
#include <WiFi.h>

// --- Enter your Wi-Fi credentials here ---
const char ssid[] = "YOUR WIFI NETWORK";   // Your Wi-Fi name
const char pass[] = "YOUR PASSWORD";       // Your Wi-Fi password

// Create a server object on port 80
WiFiServer server(80);

// Define the pin for the LED (GPIO 2 is often labeled as D2)
const int ledPin = 2;

// Variable to store the current LED status
String ledStatus = "off";

void setup() {
  Serial.begin(115200);
  while (!Serial) {
    ; // Wait for the serial monitor to be ready
  }

  // Configure the LED pin as output and turn it off initially
  pinMode(ledPin, OUTPUT);
  digitalWrite(ledPin, LOW);

  Serial.println("\nStarting sketch...");
  Serial.print("Connecting to Wi-Fi: ");
  Serial.println(ssid);

  // Start the Wi-Fi connection
  WiFi.begin(ssid, pass);

  // Wait in a loop until the connection is established
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  Serial.println("\nWi-Fi connection established!");
  Serial.print("Server started! Open this address in your browser: http://");
  Serial.println(WiFi.localIP());
  Serial.println("---------------------------------");

  // Start the web server
  server.begin();
}

void loop() {
  // Check if a new client (e.g., a web browser) has connected
  WiFiClient client = server.available();

  if (client) { // If a client is available...
    Serial.println("\n[A new client has connected!]");

    // While the client is connected and sending data...
    while (client.connected()) {
      if (client.available()) {
        // Read the first line of the request (e.g., "GET /led/on HTTP/1.1")
        String line = client.readStringUntil('\n');
        Serial.print("Client request: ");
        Serial.println(line);

        // Check which URL was called and control the LED accordingly
        if (line.indexOf("GET /led/on") >= 0) {
          digitalWrite(ledPin, HIGH);
          ledStatus = "on";
        } else if (line.indexOf("GET /led/off") >= 0) {
          digitalWrite(ledPin, LOW);
          ledStatus = "off";
        }

        // --- Send the HTTP response ---
        // Send the header
        client.println("HTTP/1.1 200 OK");
        client.println("Content-type:text/html; charset=utf-8");
        client.println("Connection: close");
        client.println(); // Empty line separates header from content

        // Send the HTML content (the webpage)
        client.println("<!DOCTYPE html>");
        client.println("<html><head><title>ESP32 LED Control</title>");
        client.println("<style>body{font-family:sans-serif;text-align:center;}button{font-size:1.2rem;padding:10px 20px;margin:10px;cursor:pointer;}</style>");
        client.println("</head><body>");
        client.println("<h1>ESP32 LED Control</h1>");
        client.print("<p>The LED is currently: <strong>");
        client.print(ledStatus); // Insert the current LED status
        client.println("</strong></p>");
        client.println("<a href=\"/led/on\"><button>TURN ON</button></a>");
        client.println("<a href=\"/led/off\"><button>TURN OFF</button></a>");
        client.println("</body></html>");
        client.println();

        // Since we've sent everything, we can exit the loop
        break;
      }
    }

    // Give the browser a short moment to receive the data
    delay(10);

    // Close the connection to the client
    client.stop();
    Serial.println("[Client connection closed]");
  }
}

				
			
				
					// Required libraries
#include <WiFi.h>
#include <Adafruit_Sensor.h>
#include <DHT.h>

// --- Enter your Wi-Fi credentials here ---
const char ssid[] = "YOUR WIFI NETWORK";  // Your Wi-Fi name
const char pass[] = "YOUR PASSWORD";      // Your Wi-Fi password

// --- DHT sensor configuration ---
// Pin where the DHT11 is connected (GPIO 4 is often labeled as D4)
const int DHTPIN = 4;
// Define the sensor type
#define DHTTYPE DHT11

// Create the server and sensor objects
WiFiServer server(80);
DHT dht(DHTPIN, DHTTYPE);

void setup() {
  Serial.begin(115200);
  while (!Serial) {
    ; // Wait until the serial monitor is ready
  }

  // Start the DHT sensor
  dht.begin();

  Serial.println("\nSketch is starting...");
  Serial.print("Connecting to Wi-Fi: ");
  Serial.println(ssid);

  // Start the Wi-Fi connection
  WiFi.begin(ssid, pass);

  // Wait until the connection is established
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  Serial.println("\nWi-Fi connection established!");
  Serial.print("Server started! Open this IP in your browser: http://");
  Serial.println(WiFi.localIP());
  Serial.println("---------------------------------");

  // Start the web server
  server.begin();
}

void loop() {
  // Check if a new client has connected
  WiFiClient client = server.available();
  if (client) { // If a client is connected...
    Serial.println("\n[A new client has connected!]");
    while (client.connected()) {
      if (client.available()) {
        // Read the request line (ignored since we always send the same page)
        client.readStringUntil('\n');

        // --- Read sensor values ---
        float humidity = dht.readHumidity();
        float temperature = dht.readTemperature();

        // Check if reading was successful (important for DHT sensors!)
        if (isnan(humidity) || isnan(temperature)) {
          Serial.println("Error reading from DHT sensor!");
          // We’ll still send a web page, but with an error message
        }

        // --- Send the HTTP response ---
        client.println("HTTP/1.1 200 OK");
        client.println("Content-type:text/html; charset=utf-8");
        client.println("Connection: close");
        client.println();

        // Send the HTML content
        client.println("<!DOCTYPE html>");
        client.println("<html><head><title>ESP32 Weather Station</title>");
        // The page reloads automatically every 10 seconds
        client.println("<meta http-equiv='refresh' content='10'>");
        client.println("<style>body{font-family:sans-serif; text-align:center; background-color:#f0f0f0; margin-top:50px;}");
        client.println("div{background-color:white; padding:20px; border-radius:10px; display:inline-block; box-shadow:0 4px 8px rgba(0,0,0,0.1);}");
        client.println("h1{color:#333;} p{font-size:1.5rem; color:#555;} strong{color:#007BFF;}</style>");
        client.println("</head><body><div>");
        client.println("<h1>ESP32 Mini Weather Station</h1>");
        if (isnan(temperature)) {
          client.println("<p>Error reading sensor data!</p>");
        } else {
          client.print("<p>Temperature: <strong>");
          client.print(temperature);
          client.println(" &deg;C</strong></p>"); // &deg; = HTML code for degree symbol
          client.print("<p>Humidity: <strong>");
          client.print(humidity);
          client.println(" %</strong></p>");
        }
        client.println("</div></body></html>");
        client.println();

        // Exit the loop after sending the response
        break;
      }
    }
    delay(10);
    client.stop();
    Serial.println("[Client connection closed]");
  }
}

				
			
				
					// Required libraries
#include <WiFi.h>
#include <Adafruit_Sensor.h>
#include <DHT.h>

// --- Enter your Wi-Fi credentials here ---
const char ssid[] = "YOUR WIFI NETWORK"; // Your Wi-Fi name
const char pass[] = "YOUR PASSWORD";     // Your Wi-Fi password

// Create the server object
WiFiServer server(80);

// --- LED configuration ---
const int ledPin = 2; // GPIO 2 (often labeled D2)
String ledStatus = "off";

// --- DHT sensor configuration ---
const int DHTPIN = 4; // GPIO 4 (often labeled D4)
#define DHTTYPE DHT11
DHT dht(DHTPIN, DHTTYPE);

void setup() {
  Serial.begin(115200);
  while (!Serial) { ; }

  // Initialize hardware
  pinMode(ledPin, OUTPUT);
  digitalWrite(ledPin, LOW); // LED starts off
  dht.begin();

  Serial.println("\nFinal sketch is starting...");
  Serial.print("Connecting to Wi-Fi: ");
  Serial.println(ssid);
  WiFi.begin(ssid, pass);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  Serial.println("\nWi-Fi connection established!");
  Serial.print("Server started! Open this IP in your browser: http://");
  Serial.println(WiFi.localIP());
  Serial.println("---------------------------------");

  server.begin();
}

void loop() {
  WiFiClient client = server.available();
  if (client) {
    Serial.println("\n[A new client has connected!]");
    while (client.connected()) {
      if (client.available()) {
        // Read the first line of the request
        String line = client.readStringUntil('\n');
        Serial.print("Client request: ");
        Serial.println(line);

        // --- 1. Parse URL and control LED ---
        if (line.indexOf("GET /led/on") >= 0) {
          digitalWrite(ledPin, HIGH);
          ledStatus = "on";
        } else if (line.indexOf("GET /led/off") >= 0) {
          digitalWrite(ledPin, LOW);
          ledStatus = "off";
        }

        // --- 2. Read sensor values ---
        float humidity = dht.readHumidity();
        float temperature = dht.readTemperature();

        // --- 3. Send complete HTML response ---
        client.println("HTTP/1.1 200 OK");
        client.println("Content-type:text/html; charset=utf-8");
        client.println("Connection: close");
        client.println();

        client.println("<!DOCTYPE html>");
        client.println("<html><head><title>ESP32 Dashboard</title>");
        // Auto-refresh every 10 seconds
        client.println("<meta http-equiv='refresh' content='10'>");
        client.println("<style>body{font-family:sans-serif; background-color:#f4f4f4; margin:0; padding:20px; text-align:center;}");
        client.println(".card{background-color:white; margin:15px auto; padding:20px; border-radius:10px; box-shadow:0 4px 8px rgba(0,0,0,0.1); max-width:400px;}");
        client.println("h1{color:#333;} h2{color:#007BFF;} p{font-size:1.2rem;} strong{color:#333;}");
        client.println("button{font-size:1rem; padding:10px 20px; margin:5px; cursor:pointer; border:none; border-radius:5px;}");
        client.println(".btn-on{background-color:#28a745; color:white;} .btn-off{background-color:#dc3545; color:white;}");
        client.println("</style></head><body>");
        client.println("<h1>ESP32 Dashboard</h1>");

        // Weather station card
        client.println("<div class='card'>");
        client.println("<h2>Mini Weather Station</h2>");
        if (isnan(temperature) || isnan(humidity)) {
          client.println("<p>Error reading sensor data!</p>");
        } else {
          client.print("<p>Temperature: <strong>");
          client.print(temperature);
          client.println(" &deg;C</strong></p>");
          client.print("<p>Humidity: <strong>");
          client.print(humidity);
          client.println(" %</strong></p>");
        }
        client.println("</div>");

        // LED control card
        client.println("<div class='card'>");
        client.println("<h2>LED Control</h2>");
        client.print("<p>Status: <strong>");
        client.print(ledStatus);
        client.println("</strong></p>");
        client.println("<a href='/led/on'><button class='btn-on'>LED ON</button></a>");
        client.println("<a href='/led/off'><button class='btn-off'>LED OFF</button></a>");
        client.println("</div>");

        client.println("</body></html>");
        client.println();

        break; // Response sent, exit loop
      }
    }
    delay(10);
    client.stop();
    Serial.println("[Client connection closed]");
  }
}

				
			
				
					// 1. Include required libraries
#include <WiFi.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include "DHT.h"
#include "Adafruit_MQTT.h"
#include "Adafruit_MQTT_Client.h"

// 2. Configuration and constants
// Wi-Fi credentials
// *** UPDATE THESE ***
const char* ssid = "YOUR WIFI NETWORK";
const char* password = "YOUR PASSWORD";

// Adafruit IO configuration
// *** UPDATE THESE ***
#define AIO_SERVER      "io.adafruit.com"
#define AIO_SERVERPORT  1883
#define AIO_USERNAME    "YOUR ADAFRUIT IO USERNAME"
#define AIO_KEY         "YOUR ADAFRUIT IO KEY"

// Pin configuration
#define DHTPIN 4      // DHT sensor connected to GPIO 4
#define LED_PIN 2     // LED connected to GPIO 2
#define DHTTYPE DHT11

// OLED display configuration
#define SCREEN_WIDTH 128
#define SCREEN_HEIGHT 64
#define OLED_RESET    -1

// 3. Create objects
DHT dht(DHTPIN, DHTTYPE);
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);
WiFiClient client;

// Adafruit IO MQTT client
Adafruit_MQTT_Client mqtt(&client, AIO_SERVER, AIO_SERVERPORT, AIO_USERNAME, AIO_KEY);

// Adafruit IO feeds
// Publish feeds (sending data to Adafruit IO)
Adafruit_MQTT_Publish temperatureFeed = Adafruit_MQTT_Publish(&mqtt, AIO_USERNAME "/feeds/temperature");
Adafruit_MQTT_Publish humidityFeed    = Adafruit_MQTT_Publish(&mqtt, AIO_USERNAME "/feeds/humidity");

// Subscribe feed (receiving data from Adafruit IO)
Adafruit_MQTT_Subscribe ledFeed = Adafruit_MQTT_Subscribe(&mqtt, AIO_USERNAME "/feeds/led");

// Timer for sending data (non-blocking)
unsigned long previousMillis = 0;
const long interval = 60000; // 1 minute

// 4. Setup function
void setup() {
  Serial.begin(115200);
  pinMode(LED_PIN, OUTPUT); // Set LED pin as output

  // Initialize OLED display
  if (!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
    Serial.println(F("SSD1306 allocation failed"));
    for(;;);
  }

  display.cp437(true); // Load extended character set for ° symbol
  display.clearDisplay();
  display.setTextSize(1);
  display.setTextColor(SSD1306_WHITE);
  display.setCursor(0,0);
  display.println("IoT Weather Logger");
  display.println("Adafruit IO Version");
  display.display();
  delay(2000);

  // Connect to Wi-Fi
  WiFi.mode(WIFI_STA);
  connectWiFi();

  // Start DHT sensor
  dht.begin();

  // Subscribe to LED feed
  mqtt.subscribe(&ledFeed);

  display.clearDisplay();
  display.setCursor(0,0);
  display.println("System ready!");
  display.display();
  delay(2000);
}

// 5. Main loop
void loop() {
  // Ensure MQTT connection
  MQTT_connect();

  // If not connected, skip this loop and retry later
  if (!mqtt.connected()) {
    Serial.println("MQTT connection failed. Retrying in 10 seconds...");
    delay(10000);
    return;
  }

  // Check for incoming messages (non-blocking)
  Adafruit_MQTT_Subscribe *subscription;
  while ((subscription = mqtt.readSubscription(5000))) {
    if (subscription == &ledFeed) {
      Serial.print(F("Message from 'led' feed: "));
      Serial.println((char *)ledFeed.lastread);

      // Control LED based on received message
      if (strcmp((char *)ledFeed.lastread, "1") == 0) {
        digitalWrite(LED_PIN, HIGH);
      }
      if (strcmp((char *)ledFeed.lastread, "0") == 0) {
        digitalWrite(LED_PIN, LOW);
      }
    }
  }

  // Check if it's time to send new sensor data
  unsigned long currentMillis = millis();
  if (currentMillis - previousMillis >= interval) {
    previousMillis = currentMillis; // Reset timer

    // Read sensor values
    float h = dht.readHumidity();
    float t = dht.readTemperature();

    if (isnan(h) || isnan(t)) {
      Serial.println("Error reading from DHT sensor!");
      display.clearDisplay();
      display.setCursor(0,0);
      display.println("Sensor error!");
      display.display();
      return;
    }

    // Print data to serial monitor
    Serial.print("Temperature: "); Serial.print(t);
    Serial.print(" °C, Humidity: "); Serial.print(h); Serial.println(" %");

    // --- Improved OLED layout ---
    display.clearDisplay();

    // Temperature section
    display.setTextSize(1);
    display.setCursor(0, 0);
    display.println("Temperature");
    display.setTextSize(2);
    display.setCursor(0, 12);
    display.print(t, 1);
    display.write(248); // Degree symbol °
    display.print("C");

    // Humidity section
    display.setTextSize(1);
    display.setCursor(0, 35);
    display.println("Humidity");
    display.setTextSize(2);
    display.setCursor(0, 47);
    display.print(h, 0);
    display.print(" %");

    display.display();
    // --- End of OLED layout ---

    // Send data to Adafruit IO
    Serial.print("Sending temperature to Adafruit IO... ");
    if (temperatureFeed.publish(t)) {
      Serial.println("OK!");
    } else {
      Serial.println("Failed.");
    }

    Serial.print("Sending humidity to Adafruit IO... ");
    if (humidityFeed.publish(h)) {
      Serial.println("OK!");
    } else {
      Serial.println("Failed.");
    }
  }
}

// --- Helper function: Connect to Wi-Fi ---
void connectWiFi() {
  Serial.print("Connecting to "); Serial.println(ssid);
  display.clearDisplay();
  display.setCursor(0,0);
  display.println("Connecting to Wi-Fi");
  display.display();

  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  Serial.println("\nConnected!");
  Serial.print("IP Address: "); Serial.println(WiFi.localIP());

  display.clearDisplay();
  display.setCursor(0,0);
  display.println("Connected!");
  display.println(WiFi.localIP());
  display.display();
  delay(2000);
}

// --- Helper function: Connect to Adafruit IO MQTT broker ---
void MQTT_connect() {
  int8_t ret;

  if (mqtt.connected()) {
    return;
  }

  Serial.print("Connecting to MQTT... ");
  uint8_t retries = 3;

  while ((ret = mqtt.connect()) != 0) { // connect() returns 0 on success
    Serial.println(mqtt.connectErrorString(ret));
    Serial.println("Retrying in 5 seconds...");
    mqtt.disconnect();
    delay(5000);
    retries--;
    if (retries == 0) {
      // Give up after 3 failed attempts; try again in the next loop
      return;
    }
  }

  Serial.println("MQTT connected!");
}

				
			

LED Matrix Tool

This tool helps you create images for the matrix display of the Arduino UNO R4 WiFi. Draw your image on the canvas – a click on Generate Code creates the code for your sketch. With Copy, it goes straight to your clipboard, ready to paste into the Arduino IDE.

We don't track you. No ads, no unnecessary cookies, no Facebook pixel stuff. Consider becoming a member instead to support Pollux Labs.
e-Book
Ready to start building? This hands-on e-book teaches you the essentials of C++, Arduino, and the ESP32 through simple steps and real projects. No experience needed — just curiosity. By the end, you’ll have built your own IoT device from scratch.
Become a Maker