Wemos Mini read the state of a switch

In the previous examples using theWemos Mini we controlled an led and an rgb led using pins as outputs but you can also easily monitor the state of an input, in this case we will use a switch

Basically it will be a web page which shows whether the button is on or off.

 

Schematic

Not much too this but here is a schematic and layout for you.

wemos switch_bb

wemos switch_schem

 

Code

Remember and modify the following with your Wifi details

const char* ssid = "ssid here";
const char* password = "password here";

[codesyntax lang=”cpp”]

#include <ESP8266WiFi.h>
 
const char* ssid = "ssid here";
const char* password = "password here";
 
int switchPin = D5;

WiFiServer server(80);
 
void setup() 
{
  Serial.begin(115200);
  delay(10);
 
  //set up LEDs
  pinMode(switchPin, INPUT);  // input pin for switch
  
  // Connect to WiFi network
  Serial.print("Connecting to ");
  Serial.println(ssid);
   
  WiFi.begin(ssid, password);
   
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("WiFi connected");
   
  // Start the server
  server.begin();
  Serial.println("Server started");
 
  // Print the IP address
  Serial.print("Use this URL : ");
  Serial.print("http://");
  Serial.print(WiFi.localIP());
  Serial.println("/");
    
}
 
void loop() {
  // Check if a client has connected
  WiFiClient client = server.available();
  if (!client) {
    return;
  }
   
  // Wait until the client sends some data
  Serial.println("new client");
  while(!client.available()){
    delay(1);
  }
   
  // Read the first line of the request
  String request = client.readStringUntil('\r');
  Serial.println(request);
  client.flush();

  // Return the response
  client.println("HTTP/1.1 200 OK");
  client.println("Content-Type: text/html");
  client.println(""); //  do not forget this one
  client.println("<!DOCTYPE HTML>");
  client.println("<html>");

  client.println("<head>");
  client.println("<title>Arduino Read Switch</title>");
  client.println("<meta http-equiv=\"refresh\" content=\"1\">");
  client.println("</head>");
  client.println("<body>");
  client.println("<h1>Switch Example</h1>");
  client.println("<p>State of switch is:</p>");
  ReadSwitchState(client);
  client.println("</body>");
  client.println("</html>");
 
  delay(1);
  Serial.println("Client disconnected");

 
}


void ReadSwitchState(WiFiClient cl)
{
    if (digitalRead(switchPin)) 
    {
        cl.println("<p>ON</p>");
    }
    else 
    {
        cl.println("<p>OFF</p>");
    }
}

[/codesyntax]

 

Testing

Navigate to the IP address you specified in the code above

switch example

Now toggle the on and off switch and watch the text change

Links