Building a Mini Search Engine Using ESP32, OLED Display, and Wi-Fi


What if we could build a small search engine that fits inside our hands, using nothing more than an ESP32, a tiny OLED display, and three push buttons?

Sounds interesting, right?

Recently, I worked on a small embedded project where I used an ESP32 to create a basic search interface. The idea was simple: enter a search query using physical buttons, send it over Wi-Fi, fetch a search result from DuckDuckGo, and display the response on a 128×64 OLED screen.




This project is a good example of how embedded systems can interact with web services using HTTP requests.

Let's understand how it works.

1. Hardware and Software Requirements

Hardware:

  • ESP32 development board
  • 0.96-inch SSD1306 OLED display (128×64)
  • Three push buttons
  • Connecting wires
  • USB power supply

Software and libraries:

  • Arduino IDE
  • WiFi.h – For wireless connectivity
  • HTTPClient.h – For making HTTP requests
  • Wire.h – For I2C communication
  • Adafruit_GFX.h – Graphics library
  • Adafruit_SSD1306.h – OLED display driver

2. Understanding the System Architecture

Before looking at the code, let's understand the overall working principle.

The project follows a simple sequence:

  1. ESP32 initializes the OLED display.
  2. It connects to the configured Wi-Fi network.
  3. The user enters a search query using three buttons.
  4. The ESP32 converts the query into a URL-compatible format.
  5. An HTTPS GET request is sent to DuckDuckGo.
  6. The ESP32 receives the HTML response.
  7. It extracts a search-result snippet from the received HTML.
  8. The result is displayed on the OLED.

The user can scroll through the result using the buttons.

The ESP32 essentially acts as a small web client.

3. Initializing the OLED Display

The first important part is configuring the OLED display.

#define SCREEN_WIDTH 128
#define SCREEN_HEIGHT 64
#define OLED_RESET -1

Adafruit_SSD1306 display(
    SCREEN_WIDTH,
    SCREEN_HEIGHT,
    &Wire,
    OLED_RESET
);

Here:

  • SCREEN_WIDTH defines the horizontal resolution.
  • SCREEN_HEIGHT defines the vertical resolution.
  • Wire initializes the I2C communication interface.
  • OLED_RESET is set to -1 because the display does not use a separate reset pin.

The display is initialized inside setup():

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

The address 0x3C is a commonly used I2C address for SSD1306 displays.

If initialization fails, the ESP32 stops execution.

4. Using Three Buttons as a Keyboard

One interesting part of this project is that we don't use a conventional keyboard.

Instead, three physical buttons are used to navigate through a character set.

#define BTN_UP       2
#define BTN_SELECT   0
#define BTN_DOWN     15

The character set is defined as:

const char charSet[] =
"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_ <*";

Each button has a specific purpose:

  • UP: Moves forward through the available characters.
  • DOWN: Moves backward through the characters.
  • SELECT: Adds the selected character to the query.

There are also three special characters:

  • _ represents a space.
  • < represents backspace.
  • * represents search/submit.

For example, to enter ESP32, we navigate through the characters and select them one by one.

The selected character is stored using an index:

int selectedCharIdx = 0;

The index is updated using modular arithmetic:

selectedCharIdx =
    (selectedCharIdx + 1) % totalChars;

This ensures that once we reach the last character, navigation starts again from the beginning.

Similarly, the DOWN button moves backward.

The buttons are configured using INPUT_PULLUP, meaning a pressed button reads LOW and a released button reads HIGH.

5. Implementing Two Different Operating Modes

Instead of handling all operations in one place, the program uses a simple state machine.

enum AppState {
    TYPING_MODE,
    SCROLL_MODE
};

AppState currentState = TYPING_MODE;

There are two operating modes:

Typing Mode

The user enters a search query and navigates through the character selection interface.

Scroll Mode

After submitting a query, the search result is displayed. The user can scroll through the text.

The main loop decides which function should execute:

void loop() {
    if (currentState == TYPING_MODE) {
        handleTypingControls();
    }
    else if (currentState == SCROLL_MODE) {
        handleScrollControls();
    }
}

This approach keeps the input-handling logic separated and makes the program easier to understand and maintain.

6. Handling User Input

The handleTypingControls() function manages all three buttons.

Whenever UP or DOWN is pressed, the selected character index changes.

When SELECT is pressed, the program checks which character is currently selected.

char chosen = charSet[selectedCharIdx];

Then it performs one of four operations:

  • If the character is *, it starts the search.
  • If the character is <, it removes the last character.
  • If the character is _, it inserts a space.
  • Otherwise, it appends the selected character to the query.

The query length is limited to 18 characters:

if (customQuery.length() < 18) {
    customQuery += chosen;
}

This restriction helps keep the input manageable on the small display.

7. Connecting ESP32 to Wi-Fi

The Wi-Fi connection is established inside setup():

WiFi.begin(ssid, password);

while (WiFi.status() != WL_CONNECTED) {
    delay(400);
}

The ESP32 continuously checks whether it has successfully connected to the network.

Once connected, it can communicate with external web servers.

For an actual deployment, it is better to add a connection timeout and display an error message if Wi-Fi is unavailable.

8. Sending an HTTP Request to DuckDuckGo

This is where the project becomes interesting.

The main search functionality is implemented inside:

void performPublicSearch(String query)

First, the program checks whether Wi-Fi is connected.

Then it prepares the search query:

String encodedQuery = query;
encodedQuery.replace(" ", "+");

For example:

ESP32 embedded programming

becomes:

ESP32+embedded+programming

The search URL is constructed:

String url =
"https://html.duckduckgo.com/html/?q=" + encodedQuery;

Next, the HTTP client is initialized:

HTTPClient http;

http.begin(url);
http.setUserAgent(
    "Mozilla/5.0 (Windows NT 10.0; Win64; x64)"
);

int httpCode = http.GET();

Here:

  • HTTPClient handles the HTTP communication.
  • begin() initializes the request URL.
  • setUserAgent() sets the user-agent header.
  • GET() sends an HTTPS GET request.

The ESP32 then receives the server's response.

9. Extracting Search Results from HTML

A search engine does not directly return plain text in this implementation.

Instead, DuckDuckGo returns an HTML page.

The program retrieves the complete response:

String payload = http.getString();

It then searches for the HTML element containing the result snippet:

int snippetStart =
    payload.indexOf("class=\"result__snippet\"");

If the element is found, the code locates its starting and ending positions:

int textStart =
    payload.indexOf(">", snippetStart) + 1;

int textEnd =
    payload.indexOf("</a>", textStart);

The extracted content is stored:

searchResult =
    payload.substring(textStart, textEnd);

Some basic HTML entities and tags are removed:

searchResult.replace("<b>", "");
searchResult.replace("</b>", "");
searchResult.replace("&quot;", "\"");
searchResult.replace("&amp;", "&");
searchResult.replace("&#x27;", "'");

This gives us readable text that can be displayed on the OLED.

An important limitation: This is a basic HTML-parsing approach. Search engine HTML structures can change, and the first matching snippet may not always represent the complete result. A proper HTML parser or a supported search API would be more reliable for a production application.

Also, replacing spaces with + is only basic query encoding. A robust implementation should URL-encode all special characters.

10. Creating a Scrolling Text Interface

A 128×64 OLED cannot display a large amount of text at once.

To overcome this limitation, the project implements vertical scrolling.

int scrollOffset = 0;
const int lineSpacing = 12;
int maxScroll = 0;

The search result is divided into lines:

int charsPerLine = 19;

Each line is displayed at a different vertical position:

int startY = 16 + scrollOffset;

Whenever the user presses UP or DOWN, the scroll offset changes.

For example:

scrollOffset -= lineSpacing;

moves the displayed content upward, revealing the next lines.

The maximum scrolling distance is calculated based on the estimated number of lines:

int totalLines =
    (searchResult.length() / 19) + 2;

int visibleLines = 4;

maxScroll = max(
    0,
    (totalLines - visibleLines) * lineSpacing
);

A small scrollbar is also drawn on the right side of the display.

This gives the user a visual indication of their position within the result.

11. Designing the OLED User Interface

The project uses the Adafruit GFX library to create a simple graphical interface.

Instead of displaying plain text, it uses:

  • Rounded rectangles
  • Inverted header bars
  • Horizontal separator lines
  • Character selection indicators
  • Search progress animation
  • Scrollbar indicators

Three major display functions are implemented.

drawSplashScreen()

Displays the initial welcome screen while the ESP32 connects to Wi-Fi.

drawSearchAnimation()

Displays a simple loading animation when a search request is initiated.

updateDisplay()

Refreshes the OLED interface according to the current operating mode.

One useful technique is using:

display.fillRoundRect();

to highlight the currently selected character.

The interface is completely drawn using software, without requiring any additional graphical hardware.

12. What Happens When We Press the Search Button?

Let's put everything together.

Suppose the user enters:

ESP32

After selecting *, the following sequence takes place:

  1. The program checks whether the query is empty.
  2. A search animation is displayed.
  3. The ESP32 sends the query to DuckDuckGo.
  4. The server returns an HTML response.
  5. The program extracts the first matching result snippet.
  6. The result is stored in searchResult.
  7. The scrolling offset is reset.
  8. The application switches to SCROLL_MODE.
  9. The OLED displays the extracted result.

Pressing UP and DOWN scrolls through the result, while SELECT returns to the typing interface.

That's the complete working principle of this mini search engine.

13. Possible Improvements

Although this project is relatively simple, there are several ways to improve it.

Some ideas for the next version:

  • Use an HTML parser instead of manually searching for HTML tags.
  • Implement proper URL encoding.
  • Display multiple search results.
  • Add automatic text wrapping instead of splitting text after a fixed number of characters.
  • Replace blocking delays with non-blocking button debouncing.
  • Add a Wi-Fi connection timeout and reconnection mechanism.
  • Use a JSON-based search API instead of scraping HTML.
  • Add a battery indicator and low-power sleep mode.
  • Store Wi-Fi credentials securely instead of hardcoding them.
  • Use dynamic memory carefully to avoid heap fragmentation caused by repeated String operations.

One more important point: the current implementation extracts HTML content using string searching. It does not validate the complete HTML structure, handle every possible HTML entity, or guarantee that the result will always fit the display.

These are good areas to explore when moving from a prototype to a more reliable embedded product.

14. What I Learned from This Project

This project demonstrates that an embedded device does not have to be limited to reading sensors, controlling motors, or switching GPIO pins.

With an ESP32 and a Wi-Fi connection, we can build interactive devices that communicate with web services and present useful information through a very small interface.

It also brings together several important embedded concepts:

  • GPIO input handling
  • I2C communication
  • State machine implementation
  • Wi-Fi connectivity
  • HTTPS communication
  • String manipulation
  • Basic HTML parsing
  • OLED graphics and UI development
  • Memory and resource management

The interesting part is not just making a search request. It's bringing together hardware, firmware, networking, and user interaction into one small embedded system.

That's what makes embedded development exciting!

#ESP32 #EmbeddedSystems #EmbeddedC #Arduino #IoT #Microcontrollers #FirmwareDevelopment #Electronics #OLEDDisplay #WiFi #HardwareDevelopment #EngineeringProjects



Full Code:

//-------------------------------------------------------------------


#include <WiFi.h>
#include <HTTPClient.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>

#define SCREEN_WIDTH 128
#define SCREEN_HEIGHT 64
#define OLED_RESET    -1
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);

// Button Pin Definitions
#define BTN_UP       2
#define BTN_SELECT   0
#define BTN_DOWN     15

// WiFi Credentials
const char* ssid     = "YOUR_SSID";
const char* password = "YOUR_PASSWORD";

// Character Set: Letters, Numbers, Space ('_'), Backspace ('<'), Search ('*')
const char charSet[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_ <*";
const int totalChars = sizeof(charSet) - 1;

int selectedCharIdx = 0;
String customQuery = "";
String searchResult = "Type & select [*]";

// UI Modes
enum AppState { TYPING_MODE, SCROLL_MODE };
AppState currentState = TYPING_MODE;

int scrollOffset = 0;         
const int lineSpacing = 12;   // Increased line spacing for better readability
int maxScroll = 0;            

void setup() {
  Serial.begin(115200);

  pinMode(BTN_UP, INPUT_PULLUP);
  pinMode(BTN_SELECT, INPUT_PULLUP);
  pinMode(BTN_DOWN, INPUT_PULLUP);

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

  // Draw Initial Splash Screen
  drawSplashScreen();

  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(400);
  }

  updateDisplay();
}

void loop() {
  if (currentState == TYPING_MODE) {
    handleTypingControls();
  } else if (currentState == SCROLL_MODE) {
    handleScrollControls();
  }
}

void handleTypingControls() {
  if (digitalRead(BTN_UP) == LOW) {
    selectedCharIdx = (selectedCharIdx + 1) % totalChars;
    updateDisplay();
    delay(140);
  }

  if (digitalRead(BTN_DOWN) == LOW) {
    selectedCharIdx = (selectedCharIdx - 1 + totalChars) % totalChars;
    updateDisplay();
    delay(140);
  }

  if (digitalRead(BTN_SELECT) == LOW) {
    char chosen = charSet[selectedCharIdx];

    if (chosen == '*') {
      if (customQuery.length() > 0) {
        drawSearchAnimation();
        performPublicSearch(customQuery);
        scrollOffset = 0;
        currentState = SCROLL_MODE;
      } else {
        searchResult = "Query is empty!";
      }
    }
    else if (chosen == '<') {
      if (customQuery.length() > 0) {
        customQuery.remove(customQuery.length() - 1);
      }
    }
    else if (chosen == '_') {
      if (customQuery.length() < 18) {
        customQuery += " ";
      }
    }
    else {
      if (customQuery.length() < 18) {
        customQuery += chosen;
      }
    }

    updateDisplay();
    delay(200);
  }
}

void handleScrollControls() {
  if (digitalRead(BTN_UP) == LOW) {
    if (scrollOffset < 0) {
      scrollOffset += lineSpacing;
      updateDisplay();
    }
    delay(120);
  }

  if (digitalRead(BTN_DOWN) == LOW) {
    if (abs(scrollOffset) < maxScroll) {
      scrollOffset -= lineSpacing;
      updateDisplay();
    }
    delay(120);
  }

  if (digitalRead(BTN_SELECT) == LOW) {
    currentState = TYPING_MODE;
    updateDisplay();
    delay(200);
  }
}

void performPublicSearch(String query) {
  if (WiFi.status() == WL_CONNECTED) {
    HTTPClient http;
    String encodedQuery = query;
    encodedQuery.replace(" ", "+");

    String url = "https://html.duckduckgo.com/html/?q=" + encodedQuery;
    http.begin(url);
    http.setUserAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64)");

    int httpCode = http.GET();
    if (httpCode > 0) {
      String payload = http.getString();
      int snippetStart = payload.indexOf("class=\"result__snippet\"");
      
      if (snippetStart != -1) {
        int textStart = payload.indexOf(">", snippetStart) + 1;
        int textEnd = payload.indexOf("</a>", textStart);

        searchResult = payload.substring(textStart, textEnd);
        searchResult.replace("<b>", "");
        searchResult.replace("</b>", "");
        searchResult.replace("&quot;", "\"");
        searchResult.replace("&amp;", "&");
        searchResult.replace("&#x27;", "'");
      } else {
        searchResult = "No search results found.";
      }
    } else {
      searchResult = "Connection Error: " + String(httpCode);
    }
    http.end();
  } else {
    searchResult = "WiFi Disconnected!";
  }

  // Calculate dynamic max scroll based on new line spacing (approx 19 chars per line)
  int totalLines = (searchResult.length() / 19) + 2; 
  int visibleLines = 4;
  maxScroll = max(0, (totalLines - visibleLines) * lineSpacing);
}

// Visual Screen Elements
void drawSplashScreen() {
  display.clearDisplay();
  display.setTextSize(1);
  display.setTextColor(SSD1306_WHITE);
  
  display.drawRoundRect(0, 0, 128, 64, 4, SSD1306_WHITE);
  display.fillRect(10, 8, 108, 18, SSD1306_WHITE);
  display.setTextColor(SSD1306_BLACK, SSD1306_WHITE);
  display.setCursor(20, 13);
  display.print("ESP32 SEARCH");

  display.setTextColor(SSD1306_WHITE);
  display.setCursor(18, 38);
  display.print("Connecting WiFi");
  display.setCursor(54, 48);
  display.print("...");
  display.display();
}

void drawSearchAnimation() {
  display.clearDisplay();
  display.drawRoundRect(0, 0, 128, 64, 3, SSD1306_WHITE);
  display.setTextSize(1);
  display.setTextColor(SSD1306_WHITE);
  
  display.setCursor(22, 20);
  display.print("Querying DDG");
  
  display.drawRect(14, 38, 100, 8, SSD1306_WHITE);
  for (int i = 0; i <= 96; i += 12) {
    display.fillRect(16, 40, i, 4, SSD1306_WHITE);
    display.display();
    delay(40);
  }
}

void updateDisplay() {
  display.clearDisplay();

  if (currentState == TYPING_MODE) {
    // 1. Inverted Header Bar
    display.fillRect(0, 0, 128, 12, SSD1306_WHITE);
    display.setTextColor(SSD1306_BLACK, SSD1306_WHITE);
    display.setCursor(3, 2);
    display.print("SEARCH ENGINE");
    
    // WiFi Indicator Symbol
    display.fillCircle(121, 5, 2, SSD1306_BLACK);
    display.drawPixel(121, 2, SSD1306_BLACK);

    // 2. Query Text Input Field Frame
    display.drawRoundRect(0, 14, 128, 16, 3, SSD1306_WHITE);
    display.setTextColor(SSD1306_WHITE);
    display.setCursor(4, 18);
    display.print(">");
    display.print(customQuery);
    
    // Blinking Cursor Simulation
    if ((millis() / 500) % 2 == 0) {
      display.print("_");
    }

    // 3. Multi-Character Carousel Bar
    display.drawFastHLine(0, 32, 128, SSD1306_WHITE);
    
    for (int i = -2; i <= 2; i++) {
      int idx = (selectedCharIdx + i + totalChars) % totalChars;
      char c = charSet[idx];
      int xPos = 64 + (i * 24) - 6;

      if (i == 0) {
        display.fillRoundRect(xPos - 3, 35, 18, 14, 2, SSD1306_WHITE);
        display.setTextColor(SSD1306_BLACK, SSD1306_WHITE);
      } else {
        display.setTextColor(SSD1306_WHITE);
      }

      display.setCursor(xPos, 38);
      if (c == '_') display.print("SP");
      else if (c == '<') display.print("BK");
      else if (c == '*') display.print("OK");
      else display.print(c);
    }

    display.drawFastHLine(0, 51, 128, SSD1306_WHITE);

    // 4. Bottom Hint Line
    display.setTextColor(SSD1306_WHITE);
    display.setCursor(2, 54);
    display.print("[U/D] Nav  [SEL] Enter");

  } else if (currentState == SCROLL_MODE) {
    // 1. Result Mode Header
    display.fillRect(0, 0, 128, 12, SSD1306_WHITE);
    display.setTextColor(SSD1306_BLACK, SSD1306_WHITE);
    display.setCursor(3, 2);
    display.print("RESULT");
    display.setCursor(68, 2);
    display.print("[SEL]Edit");

    // 2. Main Scroll Content Area with Clean Line Spacing & Padding
    display.setTextColor(SSD1306_WHITE);
    
    int startY = 16 + scrollOffset;
    int charsPerLine = 19;
    int totalLen = searchResult.length();
    int charIndex = 0;

    // Render lines dynamically with custom vertical spacing
    while (charIndex < totalLen && startY < 64) {
      if (startY >= -8) { // Only render lines visible on screen
        String line = searchResult.substring(charIndex, min(charIndex + charsPerLine, totalLen));
        display.setCursor(4, startY); // 4px left padding for a neat margin
        display.print(line);
      }
      charIndex += charsPerLine;
      startY += lineSpacing;
    }

    // 3. Dynamic Vertical Scrollbar (Right Edge)
    if (maxScroll > 0) {
      display.drawFastVLine(126, 13, 51, SSD1306_WHITE);
      
      int barHeight = max(6, 51 - maxScroll);
      int barPos = 13 + (map(abs(scrollOffset), 0, maxScroll, 0, 51 - barHeight));
      
      display.fillRect(125, barPos, 3, barHeight, SSD1306_WHITE);
    }
  }

  display.display();
}

//-------------------------------------------------------------------
Post a Comment (0)
Previous Post Next Post