||

Wysyłanie danych przez WiFi ESP i Python

//Arduino
#include <ESP8266WiFi.h>
const char* ssid=" "; // podaj swoje ssid
const char* password=" "; // podaj swoje haslo wifi
const int led= 2;
WiFiServer server(80);

void setup() {
  pinMode(led,OUTPUT);
  Serial.begin(115200);
  Serial.print("Connecting to.");
  Serial.println(ssid);
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid,password);

  while (WiFi.status() != WL_CONNECTED){
    delay(500);
    Serial.print("..");
  }
  Serial.println("Nodemcu(esp8266) is connected to the ssid");
  Serial.println(WiFi.localIP());
  server.begin();
  delay(1000);
}

void loop() {
  WiFiClient client;
  client=server.available();
  if (client ==1){
    String request=client.readStringUntil('\n');
    client.flush();
    Serial.println(request);
    if (request.indexOf("ledon") != -1){
      digitalWrite(led,HIGH);
      Serial.println("LED IS ON NOW");}
    else if (request.indexOf("ledoff") != -1){
      digitalWrite(led,LOW);
      client.println("HTTP/1.1 200 OK");
      Serial.println("LED IS OFF NOW");}
      Serial.print("Client Disconnected");
      Serial.println("===========================");
      Serial.println("                              ");
  }
}
#Python
import tkinter
import urllib.request # funkcje I klasy pomagajace w obsłudze adresow url
root_url = http://192.168.0.24 # wpisz adres ip ESP8266, który sprawdzisz w Serial monitorze po wgraniu programu

window=tkinter.Tk()
window.title("Python with ESP8266 wifi")

def sendRequest(url):
    n = urllib.request.urlopen(url)

def set_button_on():
    btn_state_label['text'] = "LED ON"
    sendRequest(root_url+"/ledon")

def set_button_off():
    btn_state_label['text'] = "LED OFF"
    sendRequest(root_url+"/ledoff")

window.geometry('300x300')
btn_state_label = tkinter.Label(text = "___")
btn_state_label.pack()

button1state = tkinter.Button(window,
    text="ON",
    command=set_button_on,
    height = 4,
    fg = "black",
    width = 8,
    bd = 5,
    background = "green"
)
button1state.pack(side='top', ipadx=10, padx=10, pady=15)

button2state = tkinter.Button(window,
    text="OFF",
    command=set_button_off,
    height = 4,
    fg = "black",
    width = 8,
    bd = 5,
    background='red'
)
button2state.pack(side='top', ipadx=10, padx=10, pady=15)

window.mainloop()

Podobne wpisy

Dodaj komentarz

Twój adres e-mail nie zostanie opublikowany. Wymagane pola są oznaczone *