ESP8266 server program and client program for to toggle its GPIO pins

Here is an example of a server program and client program for an ESP8266 to toggle its GPIO pins:

Server Program in C:

#include <ESP8266WiFi.h>

const char* ssid = "your_SSID";
const char* password = "your_PASSWORD";

WiFiServer server(80);

int ledPin = 2;

void setup() {
  pinMode(ledPin, OUTPUT);
  digitalWrite(ledPin, LOW);
  Serial.begin(115200);

  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.println("Connecting to WiFi...");
  }
  Serial.println("Connected to WiFi");

  server.begin();
  Serial.println("Server started");
}

void loop() {
  WiFiClient client = server.available();
  if (!client) {
    return;
  }

  String request = client.readStringUntil('\r');
  client.flush();

  if (request.indexOf("/LED=ON") != -1) {
    digitalWrite(ledPin, HIGH);
    client.println("HTTP/1.1 200 OK");
    client.println("Content-Type: text/html");
    client.println();
    client.println("<!DOCTYPE HTML>");
    client.println("<html>");
    client.println("<br><br><br>");
    client.println("LED turned ON");
    client.println("</html>");
  }
  else if (request.indexOf("/LED=OFF") != -1) {
    digitalWrite(ledPin, LOW);
    client.println("HTTP/1.1 200 OK");
    client.println("Content-Type: text/html");
    client.println();
    client.println("<!DOCTYPE HTML>");
    client.println("<html>");
    client.println("<br><br><br>");
    client.println("LED turned OFF");
    client.println("</html>");
  }
  else {
    client.println("HTTP/1.1 404 Not Found");
    client.println("

Client program in C:

The client program is a program that runs on a separate device, such as a computer or mobile phone, and is used to send requests to the ESP8266 server. Here is an example of a client program that can be used to toggle the GPIO pins of an ESP8266:

#include <WiFi.h>

const char* ssid = "your_SSID";
const char* password = "your_PASSWORD";

WiFiClient client;

void setup() {
  Serial.begin(115200);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.println("Connecting to WiFi...");
  }
  Serial.println("Connected to WiFi");
}

void loop() {
  if (client.connect("your_ESP8266_IP", 80)) {
    client.println("GET /LED=ON HTTP/1.1");
    client.println("Host: your_ESP8266_IP");
    client.println();
    delay(1000);
    client.stop();
  }
  delay(1000);
}

This client program connects to the same WiFi network as the ESP8266 server using the same SSID and password. It then sends a GET request to the ESP8266 server with the path “/LED=ON” to turn the LED on. The ESP8266 server receives the request and turns the LED on by setting the GPIO pin to high.

    Leave a Reply

    Your email address will not be published. Required fields are marked *