Smart Home Automation Forum

Full Version: [Arduino IDE demo source code for KC868-A6]--#12-Web_server_code
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Pages: 1 2
[Arduino IDE demo source code for KC868-A6]--#12-Web_server_code
[attachment=1267]
[attachment=1268]

Code:
/***********************************************************
* Create Your own WebServer for KC868-A6 Smart Controller*
* https://www.kincony.com                                **
***********************************************************/

// Load Wi-Fi library
#include <WiFi.h>
#include "PCF8574.h"
#include <WiFiManager.h>
#define TRIGGER_PIN 0   // reset wifi button
WiFiManager wm;
int timeout =20; // seconds to run for
// Replace with your network credentials
/*******config the WIFI by phone*****************/

/* const char* ssid     = "xxx"; //your router's ssid
const char* password = "yyy"; //your router's password*/
/*******************************************************/

// Set web server port number to 80
WiFiServer server(80);

// Variable to store the HTTP request
String header;

// Current time
unsigned long currentTime = millis();
// Previous time
unsigned long previousTime = 0;
// Define timeout time in milliseconds (example: 2000ms = 2s)
const long timeoutTime = 2000;

int flag_read_di=0;

TwoWire I2Cone = TwoWire(0);
TwoWire I2Ctwo = TwoWire(1);

//set I2C of A6
PCF8574 pcf8574_I1(&I2Cone,0x22,4,15);
PCF8574 pcf8574_R1(&I2Cone,0x24,4,15);

String relaystate[16]={"relay1state","relay2state","relay3state","relay4state",
                       "relay5state","relay6state"
                      };
String relay1state = "off";// state of relay1
String relay2state = "off";// state of relay2
String relay3state = "off";// state of relay3
String relay4state = "off";// state of relay4
String relay5state = "off";// state of relay5
String relay6state = "off";// state of relay6


void setup() {

  pinMode(TRIGGER_PIN, INPUT_PULLUP); // wifi reset button
  Serial.begin(115200);

  // Set PCF8574 pinMode to OUTPUT
  for(int i=0;i<=5;i++)
  {
     pcf8574_R1.pinMode(i, OUTPUT);
  }
 
  pcf8574_R1.begin();

 
  for(int i=0;i<=5;i++)
  {
     pcf8574_I1.pinMode(i, INPUT);
  }
    pcf8574_I1.begin();
   
  for(int i=0;i<=5;i++)
  {
     pcf8574_R1.digitalWrite(i, HIGH);
  }
    WiFi.mode(WIFI_STA);
    wm.setConfigPortalTimeout(timeout);
     bool res;
       res = wm.autoConnect("KC868-A6-AP"); // anonymous ap
    if(!res) {
        Serial.println("Failed to connect");
    }
    else {
        //if you get here you have connected to the WiFi   
        Serial.println("connected...yeey :)");
    }   
 
  // Print local IP address and start web server
  Serial.println("");
  Serial.println("WiFi connected.");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
  server.begin();

}

void loop(){
  WiFiClient client = server.available();   // Listen for incoming clients

  if (client) {                             // If a new client connects,
    Serial.println("New Client.");          // print a message out in the serial port
    String currentLine = "";                // make a String to hold incoming data from the client
    currentTime = millis();
    previousTime = currentTime;
    while (client.connected() && currentTime - previousTime <= timeoutTime) { // loop while the client's connected
      currentTime = millis();         
      if (client.available()) {             // if there's bytes to read from the client,
        char c = client.read();             // read a byte, then
        Serial.write(c);                    // print it out the serial monitor
        header += c;
        if (c == '\n') {                    // if the byte is a newline character
          // if the current line is blank, you got two newline characters in a row.
          // that's the end of the client HTTP request, so send a response:
          if (currentLine.length() == 0) {
            // HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK)
            // and a content-type so the client knows what's coming, then a blank line:
            client.println("HTTP/1.1 200 OK");
            client.println("Content-type:text/html");
            client.println("Connection: close");
            client.println();
           
            // turns 16 relays on and off
            if (header.indexOf("GET /1/on") >= 0) {relay1state = "on";pcf8574_R1.digitalWrite(P0, LOW);}
            else if (header.indexOf("GET /1/off") >= 0) {relay1state = "off";pcf8574_R1.digitalWrite(P0, HIGH);}
            else if (header.indexOf("GET /2/on") >= 0)  {relay2state = "on";pcf8574_R1.digitalWrite(P1, LOW);}
            else if (header.indexOf("GET /2/off") >= 0) {relay2state = "off";pcf8574_R1.digitalWrite(P1, HIGH);}
            else if (header.indexOf("GET /3/on") >= 0)  {relay3state = "on";pcf8574_R1.digitalWrite(P2, LOW);}
            else if (header.indexOf("GET /3/off") >= 0) {relay3state = "off";pcf8574_R1.digitalWrite(P2, HIGH);}         
            else if (header.indexOf("GET /4/on") >= 0)  {relay4state = "on";pcf8574_R1.digitalWrite(P3, LOW);}
            else if (header.indexOf("GET /4/off") >= 0) {relay4state = "off";pcf8574_R1.digitalWrite(P3, HIGH);}
            else if (header.indexOf("GET /5/on") >= 0)  {relay5state = "on";pcf8574_R1.digitalWrite(P4, LOW);}
            else if (header.indexOf("GET /5/off") >= 0) {relay5state = "off";pcf8574_R1.digitalWrite(P4, HIGH);}
            else if (header.indexOf("GET /6/on") >= 0)  {relay6state = "on";pcf8574_R1.digitalWrite(P5, LOW);}
            else if (header.indexOf("GET /6/off") >= 0) {relay6state = "off";pcf8574_R1.digitalWrite(P5, HIGH);}         
       
            else if (header.indexOf("GET /read") >= 0) flag_read_di=1;
            else if (header.indexOf("GET /all/on") >= 0)
            {
              relay1state = "on";// state of relay1
              relay2state = "on";// state of relay2
              relay3state = "on";// state of relay3
              relay4state = "on";// state of relay4
              relay5state = "on";// state of relay5
              relay6state = "on";// state of relay6

              for(int i=0;i<=5;i++)
              {
                 pcf8574_R1.digitalWrite(i, LOW);
              }
             
            }
            else if (header.indexOf("GET /all/off") >= 0)
            {
              relay1state = "off";// state of relay1
              relay2state = "off";// state of relay2
              relay3state = "off";// state of relay3
              relay4state = "off";// state of relay4
              relay5state = "off";// state of relay5
              relay6state = "off";// state of relay6


              for(int i=0;i<=5;i++)
              {
                 pcf8574_R1.digitalWrite(i, HIGH);
              }
               
            }
           
            // Display the HTML web page
            client.println("<!DOCTYPE html><html>");
            client.println("<head><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">");
            client.println("<link rel=\"icon\" href=\"data:,\">");
            // CSS to style the on/off buttons
            // Feel free to change the background-color and font-size attributes to fit your preferences
            client.println("<style>html { font-family: Helvetica; display: inline-block; border: 3px solid green;margin: 0px 15px;}");
            client.println(".button { background-color: #195B00; border-radius: 10px;color: white; padding: 10px 40px;");
            client.println("text-decoration: none; font-size: 20px; margin: 2px;text-align: center; cursor: pointer;}");
            client.println(".button2 {background-color: #77878A;}</style></head>");
           
            if (flag_read_di==1)
            {
              client.println(" relay1:" + relay1state + " relay2:" + relay2state + " relay3:" + relay3state + " relay4:" + relay4state + " relay5:" + relay5state + " relay6:" + relay6state);
            }
            else
            {
            // Web Page Heading
            client.println("<body><h1>KC868-A6 Web Server</h1>");


            // Display current state, and ON/OFF buttons for relay
            //client.println("<p>relay1 - State " + relay1state + "</p>");
            // If the relay is off, it displays the ON button     
            if (relay1state == "off") client.println("<a href=\"/1/on\"><button class=\"button\">01-OFF</button></a>"); else client.println("<a href=\"/1/off\"><button class=\"button\">01-ON </button></a>");
            if (relay2state == "off") client.println("<a href=\"/2/on\"><button class=\"button\">02-OFF</button></a>"); else client.println("<a href=\"/2/off\"><button class=\"button\">02-ON </button></a>");                                 
            if (relay3state == "off") client.println("<a href=\"/3/on\"><button class=\"button\">03-OFF</button></a>"); else client.println("<a href=\"/3/off\"><button class=\"button\">03-ON </button></a>");
            if (relay4state == "off") client.println("<a href=\"/4/on\"><button class=\"button\">04-OFF</button></a>"); else client.println("<a href=\"/4/off\"><button class=\"button\">04-ON </button></a>");
            if (relay5state == "off") client.println("<a href=\"/5/on\"><button class=\"button\">05-OFF</button></a>"); else client.println("<a href=\"/5/off\"><button class=\"button\">05-ON </button></a>");
            if (relay6state == "off") client.println("<a href=\"/6/on\"><button class=\"button\">06-OFF</button></a>"); else client.println("<a href=\"/6/off\"><button class=\"button\">06-ON </button></a>");                                 
   
              client.println("<a href=\"/all/on\"><button class=\"button\">All-ON</button></a>");
              client.println("<a href=\"/all/off\"><button class=\"button\">All-OFF</button></a>");
            } 
            client.println("</body></html>");
           
            // The HTTP response ends with another blank line
            client.println();
            break;
          } else { // if you got a newline, then clear currentLine
            currentLine = "";
          }
        } else if (c != '\r') {  // if you got anything else but a carriage return character,
          currentLine += c;      // add it to the end of the currentLine
        }
      }
    }
    // Clear the header variable
    header = "";
    // Close the connection
    client.stop();
    Serial.println("Client disconnected.");
    Serial.println("");
    flag_read_di=0;
  }

  ScanKey();            //scan key
  if ( digitalRead(TRIGGER_PIN) == LOW) {wm.resetSettings();ESP.restart();}
}

void ScanKey()           
{
  for(int i=0;i<=5;i++)
  {
    if(pcf8574_I1.digitalRead(i) == LOW)         //key pressed
      {
        delay(20);                       
        if(pcf8574_I1.digitalRead(i) == LOW)       //key pressed again
        {
          pcf8574_R1.digitalWrite(i,!pcf8574_R1.digitalRead(i));    // toggle relay1 state     
          while(pcf8574_I1.digitalRead(i) == LOW); //wait remove hand
          if (pcf8574_R1.digitalRead(i) == LOW) relaystate[i+1]="on";else relaystate[i+1]="off";
        }
      }
  }


}
buen dia intento compilar el código y hace todo lo de la conexión pero al final me dice ip 0.0.0.0 y no me deja conectarme a ap 192.168.4.1
Do you have replaced wifi ssid and password in code?
(09-09-2024, 11:05 PM)administración Wrote: [ -> ]¿Has reemplazado el SSID y la contraseña del wifi en el código?

Si ya lo hice , de hecho use otro codigo para conectarme como cliente web y si funcionó , en el código que ustedes enviaron dice no conectado. Me pueden ayudar por favor , gracias de ante mano
Hi, I got the following error:
exit status 1

Compilation error: no matching function for call to 'PCF8574:TongueCF8574(TwoWire*, int, int, int)'

could you please help in this topic?

Thanks.
you need install PCF8574 arduino library.
download link: https://www.kincony.com/forum/attachment.php?aid=6459
Thank you.
Compiled successfully.
But on the serial monitor i can see this:
���Ƶ���9����� !�*wm:config portal has timed out
*wm:config portal exiting
Failed to connect

WiFi connected.
IP address:
0.0.0.0

is this normal?
do you have replace your router's ssid and password.l
Yes, I added the correct network, but I see this:
clk_drv:0x00,q_drv:0x00,d_drv:0x00,cs0_drv:0x00,hd_drv:0x00,wp_drv:0x00
modeBig GrinIO, clock div:1
load:0x3fff0030,len:4832
load:0x40078000,len:16460
load:0x40080400,len:4
load:0x40080404,len:3504
entry 0x400805cc
*wm:AutoConnect
*wm:No wifi saved, skipping
*wm:AutoConnect: FAILED for  1 ms
*wm:StartAP with SSID:  KC868-A6-AP
*wm:AP IP address: 192.168.4.1
*wm:Starting Web Portal
*wm:28 networks found
*wm:28 networks found
*wm:config portal has timed out
*wm:config portal exiting
Failed to connect

WiFi connected.
IP address:
0.0.0.0
*wm:resetSettings
E (148830) wifi:NAN WiFi stop
*wm:SETTINGS ERASED
ets Jul 29 2019 12:21:46

Shall I join to the kc869 AP?
Ot it is enough that both device is on the same network?
it should work in STA mode. you can also try to download our BIN file directly.
Pages: 1 2