27 Nisan 2026 Pazartesi

ESP8266 buttonfi firmware example

#include <ESP8266WiFi.h>

#include <ESP8266WebServer.h>


// Create web server object on port 80

ESP8266WebServer server(80);


// ===== Pin Definitions =====

// NodeMCU pins

const int PWM_PIN = 5; // PWM output (D1)

const int LED_PIN = 16; // LED output (D0)


// ===== WiFi Credentials =====

const char* ssid = "yy";

const char* password = "yasin739314";


// ===== Network Configuration (Static IP) =====

IPAddress local_IP(192, 168, 0, 184);

IPAddress gateway(192, 168, 0, 1);

IPAddress subnet(255, 255, 255, 0);


// ===== Function Prototypes =====

void handleRoot();

void handleON();

void handleOFF();


void setup() {

  Serial.begin(115200);



/*

  // Configure static IP

  if (WiFi.config(local_IP, gateway, subnet)) {

    Serial.println("Static IP configured successfully");

  } else {

    Serial.println("Failed to configure Static IP");

  }


*/

  // Set pin modes

  pinMode(LED_PIN, OUTPUT);

  pinMode(PWM_PIN, OUTPUT);


  // Initialize PWM with 0 (off)

  analogWrite(PWM_PIN, 0);


  // Connect to WiFi

  WiFi.mode(WIFI_STA);

  WiFi.begin(ssid, password);


  Serial.print("Connecting to WiFi");

  while (WiFi.status() != WL_CONNECTED) {

    Serial.print(".");

    delay(500);

  }


  Serial.println("\nConnected!");

  Serial.print("IP Address: ");

  Serial.println(WiFi.localIP());


  // ===== Web Server Routes =====

  server.on("/", HTTP_GET, handleRoot); // Main endpoint

  server.on("/ON", handleON); // Turn LED ON

  server.on("/OFF", handleOFF); // Turn LED OFF


  // Start server

  server.begin();

  Serial.println("HTTP server started");

}


// ===== Root Handler =====

// Example: http://192.168.0.184/?data=5

void handleRoot() {

  String message = "Hello from ESP8266";


  // Check if URL contains "data" parameter

  if (server.hasArg("data")) {

    String data = server.arg("data");


    message = "Received value: " + data;


    // Convert received value to integer

    int value = data.toInt();


    // Scale value for PWM (0–1023 range for ESP8266)

    int pwmValue = value * 100;


    // Apply PWM to main pin

    analogWrite(PWM_PIN, pwmValue);


    // Debug output

    Serial.print("PWM Value: ");

    Serial.println(pwmValue);


    // Optional: apply to other pins (be careful with valid pins)

    analogWrite(0, pwmValue * 2);

    analogWrite(2, pwmValue * 5);

    analogWrite(3, pwmValue * 10);

  }


  // Send HTTP response

  server.send(200, "text/plain", message);

}


// ===== LED ON =====

void handleON() {

  digitalWrite(LED_PIN, HIGH);

  Serial.println("LED ON");

  server.send(200, "text/plain", "LED is ON");

}


// ===== LED OFF =====

void handleOFF() {

  digitalWrite(LED_PIN, LOW);

  Serial.println("LED OFF");

  server.send(200, "text/plain", "LED is OFF");

}


// ===== Main Loop =====

void loop() {

  // Handle incoming client requests

  server.handleClient();

}

Hiç yorum yok:

Yorum Gönder