ESP8266 Yerel Ağ Üzerinden Kontrol

okangungor

Üye
Katılım
12 Şubat 2025
Mesajlar
18
Merhabalar youtubeda video izleyerek ESP8266 yerel ağ üzerinden web server html sayfası ile uzaktan kontrol yapmak istiyorum videoyu izledim hazır kod paylaşılmış bu kodu kullandım fakat kodda buton var butonu push buton yapmak istiyorum yani bas çek kodlama bilmediğim için sizden ricam kodu benim için düzenlerseniz sevinirim sadece buton push buton olacak. kodu alta yazıyorum.



Kod:
#include <ESP8266WiFi.h>
#include <ESPAsyncTCP.h>
#include <ESPAsyncWebServer.h>

const char* ssid = "kullanıcı adı";
const char* password = "şifre";

bool ledState = 2;
const int ledPin = 0;

AsyncWebServer server(80);
AsyncWebSocket ws("/ws");

const char index_html[] PROGMEM = R"rawliteral(
<!DOCTYPE HTML><html>
<head>
  <title>Web Server</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <style>
  html {
    font-family: Arial, Helvetica, sans-serif;
    text-align: center;
  }
  h1 {
    font-size: 1.8rem;
    color: white;
  }
  h2{
    font-size: 1.5rem;
    font-weight: bold;
    color: #143642;
  }
  .topnav {
    overflow: hidden;
    background-color: #143642;
  }
  body {
    margin: 0;
  }
  .content {
    padding: 30px;
    max-width: 600px;
    margin: 0 auto;
  }
  .card {
    background-color: #F8F7F9;;
    box-shadow: 2px 2px 12px 1px rgba(140,140,140,.5);
    padding-top:10px;
    padding-bottom:20px;
  }
  .button {
    padding: 15px 50px;
    font-size: 24px;
    text-align: center;
    outline: none;
    color: #fff;
    background-color: #0f8b8d;
    border: none;
    border-radius: 5px;
    -webkit-touch-callout: none;
    -webkit-user-select: none;
    -khtml-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
    -webkit-tap-highlight-color: rgba(0,0,0,0);
   }
   /*.button:hover {background-color: #0f8b8d}*/
   .button:active {
     background-color: #0f8b8d;
     box-shadow: 2 2px #CDCDCD;
     transform: translateY(2px);
   }
   .state {
     font-size: 1.5rem;
     color:#8c8c8c;
     font-weight: bold;
   }
  </style>
<title>Web Server</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" href="data:,">
</head>
<body>
  <div class="topnav">
    <h1>WebSocket Server</h1>
  </div>
  <div class="content">
    <div class="card">
      <h2>Cikis - GPIO 0</h2>
      <p class="state">Durum: <span id="state">%STATE%</span></p>
      <p><button id="button" class="button">BuToN</button></p>
     <div class="topnav">
    <h1>Uzaktan Kontrol</h1>
    </div>
  </div>
<script>
  var gateway = `ws://${window.location.hostname}/ws`;
  var websocket;
  window.addEventListener('load', onLoad);
  function initWebSocket() {
    console.log('Trying to open a WebSocket connection...');
    websocket = new WebSocket(gateway);
    websocket.onopen    = onOpen;
    websocket.onclose   = onClose;
    websocket.onmessage = onMessage; // <-- add this line
  }
  function onOpen(event) {
    console.log('Connection opened');
  }
  function onClose(event) {
    console.log('Connection closed');
    setTimeout(initWebSocket, 2000);
  }
  function onMessage(event) {
    var state;
    if (event.data == "0"){
      state = "Acik";          //DONANIMSAL TASARIM TERS OLDUĞU İÇİN GND VERİYORUZ
    }
    else{
      state = "Kapali";
    }
    document.getElementById('state').innerHTML = state;
  }
  function onLoad(event) {
    initWebSocket();
    initButton();
  }
  function initButton() {
    document.getElementById('button').addEventListener('click', toggle);
  }
  function toggle(){
    websocket.send('toggle');
  }
</script>
</body>
</html>
)rawliteral";

void notifyClients() {
  ws.textAll(String(ledState));
}

void handleWebSocketMessage(void *arg, uint8_t *data, size_t len) {
  AwsFrameInfo *info = (AwsFrameInfo*)arg;
  if (info->final && info->index == 0 && info->len == len && info->opcode == WS_TEXT) {
    data[len] = 0;
    if (strcmp((char*)data, "toggle") == 0) {
      ledState = !ledState;
      notifyClients();
    }
  }
}

void onEvent(AsyncWebSocket *server, AsyncWebSocketClient *client, AwsEventType type,
             void *arg, uint8_t *data, size_t len) {
    switch (type) {
      case WS_EVT_CONNECT:
        Serial.printf("WebSocket client #%u connected from %s\n", client->id(), client->remoteIP().toString().c_str());
        break;
      case WS_EVT_DISCONNECT:
        Serial.printf("WebSocket client #%u disconnected\n", client->id());
        break;
      case WS_EVT_DATA:
        handleWebSocketMessage(arg, data, len);
        break;
      case WS_EVT_PONG:
      case WS_EVT_ERROR:
        break;
  }
}

void initWebSocket() {
  ws.onEvent(onEvent);
  server.addHandler(&ws);
}

String processor(const String& var){
  Serial.println(var);
  if(var == "STATE"){
    if (ledState){
      return "Kapali";
    }
    else{
      return "Acik";
    }
  }
  return String();
}

void setup(){
  // Serial port for debugging purposes
  Serial.begin(115200);

  pinMode(ledPin, OUTPUT);
  digitalWrite(ledPin, HIGH);
 
  // Connect to Wi-Fi
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.println("Connecting to WiFi..");
  }

  // Print ESP Local IP Address
  Serial.println(WiFi.localIP());

  initWebSocket();

  // Route for root / web page
  server.on("/", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send_P(200, "text/html", index_html, processor);
  });

  // Start server
  server.begin();
}

void loop() {
  ws.cleanupClients();
  digitalWrite(ledPin, ledState);
}

adasdasd.jpg
 
chat gpt veya claude.ai'dan yardım alarak çok kolay halledebilirsin. sana neyi neden yaptığını adım adım anlatabilir.
 
handleWebSocketMessage fonksiyonunun içine gelen mesajı yazdıracak bir Serial.println(...) ekleyin ve ESP8266 yı Serial Monitor ile gözleyin.

Düğmeye bastığınızda "toggle" mesajı karta ulaşıyor mu onu tespit etmiş olursunuz.
 
Kodun tamamını incelemedim. Çalıştığını varsayıp, istediğin gibi nasıl düzenleyebileceğinle ilgili birçok yol olduğunu söyleyebilirim. Bence sadece JavaScript ile de bu sorunu çözmek mümkün.

Aşağıdaki fonksiyonları silip:
JavaScript:
 function initButton() {
    document.getElementById('button').addEventListener('click', toggle);
  }
  function toggle(){
    websocket.send('toggle');
  }


Yerine bu şeklide düzenleyebilirsin:
JavaScript:
function initButton() {
  var button = document.getElementById('button');
  button.addEventListener('mousedown', function () {
    websocket.send('toggle');
  });
  button.addEventListener('mouseup', function () {
    websocket.send('toggle');
  });
  button.addEventListener('mouseleave', function () {
    websocket.send('toggle');
  });
}

Ya da süslü parantez yerine kısa yazmak istersen:

JavaScript:
function initButton() {
  var button = document.getElementById('button');
  button.addEventListener('mousedown', () => websocket.send('Acik'));     // Basıldığında
  button.addEventListener('mouseup', () => websocket.send('Kapali'));     // Bırakıldığında
  button.addEventListener('mouseleave', () => websocket.send('Kapali'));  // Uzaklaşıldığında
}
 
Kodun tamamını incelemedim. Çalıştığını varsayıp, istediğin gibi nasıl düzenleyebileceğinle ilgili birçok yol olduğunu söyleyebilirim. Bence sadece JavaScript ile de bu sorunu çözmek mümkün.

Aşağıdaki fonksiyonları silip:
JavaScript:
 function initButton() {
    document.getElementById('button').addEventListener('click', toggle);
  }
  function toggle(){
    websocket.send('toggle');
  }


Yerine bu şeklide düzenleyebilirsin:
JavaScript:
function initButton() {
  var button = document.getElementById('button');
  button.addEventListener('mousedown', function () {
    websocket.send('toggle');
  });
  button.addEventListener('mouseup', function () {
    websocket.send('toggle');
  });
  button.addEventListener('mouseleave', function () {
    websocket.send('toggle');
  });
}

Ya da süslü parantez yerine kısa yazmak istersen:

JavaScript:
function initButton() {
  var button = document.getElementById('button');
  button.addEventListener('mousedown', () => websocket.send('Acik'));     // Basıldığında
  button.addEventListener('mouseup', () => websocket.send('Kapali'));     // Bırakıldığında
  button.addEventListener('mouseleave', () => websocket.send('Kapali'));  // Uzaklaşıldığında
}
dediğiniz kısmı değiştirdiğimde bilgisayardan mause getirip üstüne basılı tuttuğumda oluyo ama telefondan girdiğimde elimi basılı tuttuğumda çalışmıyor.
 
dediğiniz kısmı değiştirdiğimde bilgisayardan mause getirip üstüne basılı tuttuğumda oluyo ama telefondan girdiğimde elimi basılı tuttuğumda çalışmıyor.
Aşağıdaki gibi touchstart, touchend, touchcancel ile genişleterek kullanabilirsin. Bu şekilde sorunuz çalışması lazım.

JavaScript:
function initButton() {
  var button = document.getElementById('button');

  button.addEventListener('mousedown', () => websocket.send('Acik'));
  button.addEventListener('mouseup', () => websocket.send('Kapali'));
  button.addEventListener('mouseleave', () => websocket.send('Kapali'));

  // Dokunmatik olaylar
  button.addEventListener('touchstart', (e) => {
    e.preventDefault();  // Gereksiz scroll, çift tıklama vb kaçınmak için
    websocket.send('Acik');
  });
  button.addEventListener('touchend', () => websocket.send('Kapali'));
  button.addEventListener('touchcancel', () => websocket.send('Kapali'));
}
 
Hatta şu şekilde daha derli toplu olacaktır:


JavaScript:
function initButton() {
  var button = document.getElementById('button');

  ['mousedown', 'touchstart'].forEach(event =>
    button.addEventListener(event, (e) => {
      e.preventDefault();
      websocket.send('Acik');
    })
  );

  ['mouseup', 'mouseleave', 'touchend', 'touchcancel'].forEach(event =>
    button.addEventListener(event, () => websocket.send('Kapali'))
  );
}
 

Benzer konular

Çevrimiçi üyeler

Forum istatistikleri

Konular
7,411
Mesajlar
125,063
Üyeler
3,012
Son üye
BenMuhsin

Son kaynaklar

Son profil mesajları

Freemont2.0 herbokolog Freemont2.0 wrote on herbokolog's profile.
nick iniz yakıyor
:D
Freemont2.0 posta Freemont2.0 wrote on posta's profile.
Merhabalar :)
az bilgili çok meraklı
Prooffy semih_s Prooffy wrote on semih_s's profile.
Merhaba, sizden DSO2C10 hakkında bilgi rica ettim. Yanıtlarsanız sevinirim...
Unal taydin Unal wrote on taydin's profile.
Timur Bey, Arduino kontrollü bir akü şarj cihazı yapmaya çalışıyorum. Aklımdaki fikri basit bir çizim olarak konu açmıştım. Özellikle sizin fikirlerinizi çok önemsiyorum.
Back
Top