Go Down

Topic: I need some expert help for combining two sketches together  (Read 172 times) previous topic - next topic

richland007

Sorry for the long write up i have to devide it into two messages because of the attached sketches code....

Hi everyone
I am new to Arduino and my biggest experience has been trying to get other people sketches to work with my home automation environment which is SmartThings using ST-Anything Arduino libraries developed by Dan (ogiewon) https://community.smartthings.com/t/release-st-anything-v2-9-2-arduino-esp8266-esp32-to-st-via-thingshield-ethernet-or-wifi/77707/2814

When i  was trying to automate my door lock which is a strike type i came across this project https://electropeak.com/learn/smart-door-lock-w-wifi-login-page-by-arduino-esp8266/

which basically has this 2 sketches
1: for the ESP-01
Code: [Select]
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
// WiFi network
const char* ssid     = "YourSSID";
const char* password = "YourPASSWORD";
ESP8266WebServer server ( 80 );
char htmlResponse[3000];
void handleRoot() {
 snprintf ( htmlResponse, 3000,
"<!DOCTYPE html>\
<html lang=\"en\">\
 <head>\
 <style>\
body {background-color: rgb(160, 0, 53);}\
h3   {color: white;text-align:center;}\
p    {color: white; text-align:center;}\
div  {color: white; text-align:center;}\
ID {text-align:center;}\
input {text-align:center;}\
</style>\
   <meta charset=\"utf-8\">\
   <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\
 </head>\
 <body>\
         <h3>\<canter>Electropeak Smart Security Door</canter>\</h3>\
         <p>\<canter>Please type your ID</canter>\</p>\
         <div>ID: <input type='text' name='pass_word' id='pass_word' align='center' size=10 autofocus></div> \
         <div>\
         <br><button id=\"save_button\">Log In</button>\
         </div>\
   <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js\"></script>\   
   <script>\
     var pass;\
     $('#save_button').click(function(e){\
       e.preventDefault();\
       pass = $('#pass_word').val();\       
       $.get('/save?pass=' + pass, function(data){\
         console.log(data);\
       });\
     });\     
   </script>\
 </body>\
</html>");
  server.send ( 200, "text/html", htmlResponse ); 
}
void handleSave() {
 if (server.arg("pass")!= ""){
   Serial.println(server.arg("pass"));
 }
}
void setup() {
 // Start serial
 Serial.begin(115200);
 delay(10);
 // Connecting to a WiFi network
 Serial.println();
 Serial.println();
 Serial.print("Connecting to ");
 Serial.println(ssid);
 WiFi.begin(ssid, password);
 while (WiFi.status() != WL_CONNECTED) {
   delay(500);
   Serial.print(".");
 }
 Serial.println("");
 Serial.println("WiFi connected"); 
 Serial.println("IP address: ");
 Serial.println(WiFi.localIP());
 server.on ( "/", handleRoot );
 server.on ("/save", handleSave);
 server.begin();
 Serial.println ( "HTTP server started" );
}
void loop() {
 server.handleClient();
}


and this one for the Arduino UNO-R3 (which i have no idea why is he using it when the ESP-01 could do it all)

Code: [Select]
String inputString = "";         // a String to hold incoming data
bool stringComplete = false;  // whether the string is complete
 
void setup() {
  // initialize serial:
  Serial.begin(9600);
  // reserve 200 bytes for the inputString:
  inputString.reserve(200);
 
  pinMode(9,OUTPUT);
}
 
void loop() {
  // print the string when a newline arrives:
  if (stringComplete) {
    if (inputString=="your_password")
   {
       digitalWrite(9,HIGH);
       delay(300);
       digitalWrite(9,LOW);
 
       Serial.println(inputString);
       // clear the string:
       inputString = "";
      stringComplete = false;
    }
  }
}
 
 
void serialEvent() {
  while (Serial.available()) {
    // get the new byte:
    char inChar = (char)Serial.read();
    // add it to the inputString:
    inputString += inChar;
    // if the incoming character is a newline, set a flag so the main loop can
    // do something about it:
    if (inChar == '\n') {
      stringComplete = true;
    }
  }
}

richland007

On amazon i got me one of these https://www.amazon.com/gp/product/B071WWMMDD/ref=ppx_yo_dt_b_asin_title_o06_s00?ie=UTF8&psc=1

That uses a ESP-01 and serial communication to trigger the attached realy ... With help form Ogiewon i got this sketch to work perfectly with SmartThings

Code: [Select]
///   Arduino SmartThings Ethernet ESP8266 WiFi On/Off with LED Example
///
///   Revised by Dan Ogorchock on 2017-02-11 to work with new "SmartThings v2.0" Library
///
///   Notes: The ESP-01 communicates via WiFi to your home network router,
///          then to the ST Hub, and eventually to the ST cloud servers.
///   For Denis Grabocka use case
///
//*****************************************************************************

#include <SmartThingsESP8266WiFi.h>

//*****************************************************************************
// Pin Definitions    | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
//                    V V V V V V V V V V V V V V V V V V V V V V V V V V V V V
//*****************************************************************************
//******************************************************************************************
//NodeMCU ESP8266 Pin Definitions (makes it much easier as these match the board markings)
//******************************************************************************************
/* #define LED_BUILTIN 16                 ****   // If i am understanding it correctly we do not need any digital Inputs or Outputs in this sketch
#define BUILTIN_LED 16                    ****   // hence the commenting out of this portion

#define D0 16
#define D1  5
#define D2  4
#define D3  0
#define D4  2
#define D5 14
#define D6 12
#define D7 13
#define D8 15
#define D9  3
#define D10 1


#define PIN_LED LED_BUILTIN  //Onboard LED   */

byte relON[] = {0xA0, 0x01, 0x01, 0xA2};  // Hex command to send to serial for open relay      Help needed here: Do I define these here or can i just serial write the hex command directly further down??
byte relOFF[] = {0xA0, 0x01, 0x00, 0xA1}; // Hex command to send to serial for close relay     Also is byte the proper parameter

//*****************************************************************************
// Global Variables   | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
//                    V V V V V V V V V V V V V V V V V V V V V V V V V V V V V
//*****************************************************************************
SmartThingsCallout_t messageCallout;    // call out function forward decalaration

//******************************************************************************************
//ESP8266 WiFi Information    CHANGE THIS INFORMATION ACCORDINGLY FOR YOUR NETWORK!
//******************************************************************************************
String str_ssid     = "grabockanet_2ghz";                           //  <---You must edit this line! // I will be putting my informations on this part
String str_password = "4697374387";                   //  <---You must edit this line!
IPAddress ip(192, 168, 1, 222);       // Device IP Address      //  <---You must edit this line!
IPAddress gateway(192, 168, 1, 1);    //router gateway          //  <---You must edit this line!
IPAddress subnet(255, 255, 255, 0);   //LAN subnet mask         //  <---You must edit this line!
IPAddress dnsserver(192, 168, 1, 1);  //DNS server              //  <---You must edit this line!
const unsigned int serverPort = 8090; // port to run the http server on

// Smartthings Hub Information
IPAddress hubIp(192, 168, 1, 192);    // smartthings hub ip     //  <---You must edit this line!
const unsigned int hubPort = 39500;   // smartthings hub port


//Create a SmartThings Ethernet ESP8266WiFi object
st::SmartThingsESP8266WiFi smartthing(str_ssid, str_password, ip, gateway, subnet, dnsserver, serverPort, hubIp, hubPort, messageCallout);

// bool isDebugEnabled;    // enable or disable debug in this example

bool momentaryActive = false;
int period = 2000;
unsigned long time_now = 0;

//*****************************************************************************
// Local Functions  | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
//                  V V V V V V V V V V V V V V V V V V V V V V V V V V V V V V
//*****************************************************************************
void on()
{
  Serial.write(relON, sizeof(relON));  // turn LED on
  time_now = millis();
  momentaryActive = true;
  smartthing.send("switch1 on");        // send message to cloud
}

//*****************************************************************************
void off()
{
  Serial.write(relOFF, sizeof(relOFF));   // turn LED off
  momentaryActive = false;
  smartthing.send("switch1 off");       // send message to cloud
}

//*****************************************************************************
// API Functions    | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
//                  V V V V V V V V V V V V V V V V V V V V V V V V V V V V V V
//*****************************************************************************
void setup()
{
  // setup default state of global variables
  // isDebugEnabled = true;

  // if (isDebugEnabled)
  // { // setup debug serial port          
  Serial.begin(9600);         // setup serial with a baud rate of 9600             **** In my ESP01 case the baud rate is the same as well 9600
    // Serial.println("");
    // Serial.println("setup..");  // print out 'setup..' on start
  // }
  
  // setup hardware pins
  // pinMode(PIN_LED, OUTPUT);     // define PIN_LED as an output    **** Should i comment this out in my case?? if Not what do i do here??
  Serial.write(relOFF, sizeof(relOFF));   // set value to HIGH (off) **** Is this right??

  //Run the SmartThings init() routine to make sure the ThingShield is connected to the ST Hub
  smartthing.init();

  //synch up the ST cloud
  smartthing.send("switch1 off");       // send message to cloud
}

//*****************************************************************************
void loop()
{
  // run smartthing logic
  smartthing.run();

  //check to see if we need to run off the momentary switch device
  if (momentaryActive) {
    if (millis() - time_now > period) {
      momentaryActive = false;
      off();
    }
  }
}

//*****************************************************************************
void messageCallout(String message)
{
  // if debug is enabled print out the received message
  // if (isDebugEnabled)
  // {
    // Serial.print("Received message: '");
    // Serial.print(message);
    // Serial.println("' ");
  // }

  // if message contents equals to 'on' then call on() function
  // else if message contents equals to 'off' then call off() function
  if (message.equals("switch1 on"))
  {
    on();
  }
  else if (message.equals("switch1 off"))
  {
    off();
  }
}


My question is how can i incorporate the above two sketches that work perfectly on their own with this third one that also works perfectly on its own??.... but so i can use either the ESP-01 by itself or the one form Amazon with SmartThings and also the above web enabled lock part as well.
So basically how can we combine the above 3 sketches into one run 2 web-servers (one for SmartThings part and the other for the webinterface part) off the same ESP-01 in 2 different ports (i have heard it can be done) and use the Serial print part to trigger the relay??

I know the SmartThings part works so we shouldn't preoccupy ourselves with, just to combine the 3 codes is the part we should worry about

All the code is ready i just don't know how to put it together what to include and what to take off from each so it can marry together

Please help any help will e appreciated greatly

thank you in advance
Denis

Go Up