Okay, my bad, sorry, before I list the full code, what I want to achieve is: send a string, with the button state, from nodemcu to unity and print it in the console. But I want to send a string to the web server only when the button state changes, and also when I request the string from the server in the Unity Game, I want to request only when there's a change. Like now I get the Curl Error with to many request or something, and I want to bypass that.. Thank you for your time, it really means a lot ![]()
Here's the full code of both:
NodeMCU:
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
/*Put your SSID & Password*/
const char* ssid = "xxx"; // Enter SSID here
const char* password = "xxx"; //Enter Password here
ESP8266WebServer server(80);
uint8_t ledPin = D1;
uint8_t buttonPin = D2;
uint8_t buttonStatus = 0, buttonLastStatus = 0;
uint8_t buttonState = 0;
void setup()
{
Serial.begin(9600);
delay(100);
pinMode(ledPin, OUTPUT);
pinMode(buttonPin, INPUT);
Serial.println("Connecting to ");
Serial.println(ssid);
//connect to your local wi-fi network
WiFi.begin(ssid, password);
//check wi-fi is connected to wi-fi network
while (WiFi.status() != WL_CONNECTED)
{
delay(1000);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected..!");
Serial.print("Got IP: ");
Serial.println(WiFi.localIP());
server.on("/", serverHandler);
server.begin();
Serial.println("HTTP server started");
}
void loop()
{
server.handleClient();
buttonStatus = digitalRead(buttonPin);
if (buttonStatus && !buttonLastStatus)
{
digitalWrite(ledPin, HIGH);
Serial.println("Button Status: ON");
buttonState = 1;
}
else if (!buttonStatus && buttonLastStatus)
{
digitalWrite(ledPin, LOW);
Serial.println("Button Status: OFF");
buttonState = 0;
}
buttonLastStatus = buttonStatus;
delay(250);
}
void serverHandler()
{
server.send(200, "text/html", SendHTML(buttonState));
}
String SendHTML(uint8_t buttonCurrentState)
{
String ptr;
if(buttonCurrentState) ptr = "1";
else ptr = "0";
return ptr;
}
Unity Game code:
using UnityEngine;
using UnityEngine.Networking;
using System.Collections;
using System;
// UnityWebRequest.Get example
// Access a website and use UnityWebRequest.Get to download a page.
// Also try to download a non-existing page. Display the error.
public class web : MonoBehaviour
{
string webString;
void Start()
{
StartCoroutine(GetRequest("http://192.168.100.58/"));
}
IEnumerator GetRequest(string uri)
{
UnityWebRequest uwr = UnityWebRequest.Get(uri);
yield return uwr.SendWebRequest();
if (uwr.isNetworkError)
{
Debug.Log("Error While Sending: " + uwr.error);
}
else
{
webString = uwr.downloadHandler.text;
Debug.Log("Received: " + webString);
}
}
void Update()
{
StartCoroutine(GetRequest("http://192.168.100.58/"));
}
}