[RELEASE] ST_Anything - Arduino/ESP8266/ESP32

Hi Dan, sorry but i cant seem to get a child to create. In my ST IDE i have the Child Voltage Sensor DH, and all the other ogiewon* DH’s as well as ’ [ogiewon : On/Off Ethernet]’ . I upload this sketch to the 8266 after configuring the IP’s etc just to try it out, added the ‘smartthing.send(“voltage1 12.34”);’ , the device appears in ST’s when i upload it as a parent. If i say there is 1 button it turns the onboard LED on and OFF, but no Child devices are created. I can see the send you recommended in the logs but cant get at them as no child is created? i am definitely missing something? thanks

The On/Off sketch and associated DTH are a matched set. Just like the ST_Anything… sketches and DTHs are a matched set.

I suggested using the On/Off sketch with modifications to comply with the ST_Anything text communications protocol. This would allow you to use the ST_Anything Parent Ethernet driver, and thus be able to utilize the child devices.

The on/off sketch shows how to implement the SmartThings… communications library in a sketch. I am assuming you’re familiar with Arduino programming? If not, this is going to be a bit of a learning curve. Hopefully you’re a C/C++ programmer? :wink:

Hi @ogiewon do you see any issues on this sketch?
I’ve used it before fine but opened it again to add a switch but when it creates the child devices its only creating Contact1 and Switch1 but no Contact2 at first it did pop up with the child device creation failed message.
So after searching I deleted the parent device and re added but the same again.
I watched the live logging and didn’t spot any errors
Thanks

[f84e81e5-7269-47b8-addc-e9704e9f016b](https://graph-eu01-euwest1.api.smartthings.com/ide/logs#f84e81e5-7269-47b8-addc-e9704e9f016b) 19:12:59: error Resync failed, code=429

[f84e81e5-7269-47b8-addc-e9704e9f016b](https://graph-eu01-euwest1.api.smartthings.com/ide/logs#f84e81e5-7269-47b8-addc-e9704e9f016b) 19:12:59: debug Update detected: DeviceCreated 12a1c334-b343-4657-94c5-5c8558b6d303

[acf758d7-28cf-4544-bbcc-78eb1f6016ad](https://graph-eu01-euwest1.api.smartthings.com/ide/logs#acf758d7-28cf-4544-bbcc-78eb1f6016ad) 19:12:59: debug 382B78038989-contact1 - name: contact, value: open

[acf758d7-28cf-4544-bbcc-78eb1f6016ad](https://graph-eu01-euwest1.api.smartthings.com/ide/logs#acf758d7-28cf-4544-bbcc-78eb1f6016ad) 19:12:59: trace createChildDevice: Creating Child Device 'ACED (contact1)'

[acf758d7-28cf-4544-bbcc-78eb1f6016ad](https://graph-eu01-euwest1.api.smartthings.com/ide/logs#acf758d7-28cf-4544-bbcc-78eb1f6016ad) 19:12:59: debug isChild = true, but no child found - Auto Add it!

[acf758d7-28cf-4544-bbcc-78eb1f6016ad](https://graph-eu01-euwest1.api.smartthings.com/ide/logs#acf758d7-28cf-4544-bbcc-78eb1f6016ad) 19:12:59: debug Parsing: contact1 open

[12a1c334-b343-4657-94c5-5c8558b6d303](https://graph-eu01-euwest1.api.smartthings.com/ide/logs#12a1c334-b343-4657-94c5-5c8558b6d303) 19:12:59: debug parse(contact open) called

[f84e81e5-7269-47b8-addc-e9704e9f016b](https://graph-eu01-euwest1.api.smartthings.com/ide/logs#f84e81e5-7269-47b8-addc-e9704e9f016b) 19:12:59: debug Update detected: DeviceCreated 3e514dbe-e528-4822-a50f-9478a2a20df7

[acf758d7-28cf-4544-bbcc-78eb1f6016ad](https://graph-eu01-euwest1.api.smartthings.com/ide/logs#acf758d7-28cf-4544-bbcc-78eb1f6016ad) 19:12:59: debug 382B78038989-switch1 - name: switch, value: off

[acf758d7-28cf-4544-bbcc-78eb1f6016ad](https://graph-eu01-euwest1.api.smartthings.com/ide/logs#acf758d7-28cf-4544-bbcc-78eb1f6016ad) 19:12:58: trace createChildDevice: Creating Child Device 'ACED (switch1)'

[acf758d7-28cf-4544-bbcc-78eb1f6016ad](https://graph-eu01-euwest1.api.smartthings.com/ide/logs#acf758d7-28cf-4544-bbcc-78eb1f6016ad) 19:12:58: debug isChild = true, but no child found - Auto Add it!

[acf758d7-28cf-4544-bbcc-78eb1f6016ad](https://graph-eu01-euwest1.api.smartthings.com/ide/logs#acf758d7-28cf-4544-bbcc-78eb1f6016ad) 19:12:58: debug Parsing: switch1 off

[3e514dbe-e528-4822-a50f-9478a2a20df7](https://graph-eu01-euwest1.api.smartthings.com/ide/logs#3e514dbe-e528-4822-a50f-9478a2a20df7) 19:12:59: debug parse(switch off) called

this is the sketch code…

//******************************************************************************************
//  File: ST_Anything_Multiples_ESP8266WiFi.ino
//  Authors: Dan G Ogorchock & Daniel J Ogorchock (Father and Son)
//
//  Summary:  This Arduino Sketch, along with the ST_Anything library and the revised SmartThings 
//            library, demonstrates the ability of one NodeMCU ESP8266 to 
//            implement a multi input/output custom device for integration into SmartThings.
//            The ST_Anything library takes care of all of the work to schedule device updates
//            as well as all communications with the NodeMCU ESP8266's WiFi.
//
//            ST_Anything_Multiples implements the following ST Capabilities as a demo of what is possible with a single NodeMCU ESP8266
//              - 1 x Alarm device (using a simple digital output)
//              - 1 x Contact Sensor devices (used to monitor magnetic door sensors)
//              - 1 x Switch devices (used to turn on a digital output (e.g. LED, relay, etc...)
//              - 1 x Motion devices (used to detect motion)
//              - 1 x Smoke Detector devices (using simple digital input)
//              - 1 x Temperature Measurement devices (Temperature from Dallas Semi 1-Wire DS18B20 device)
//              - 1 x Relay Switch devices (used to turn on a digital output for a set number of cycles And On/Off times (e.g.relay, etc...))
//              - 2 x Button devices (sends "pushed" if held for less than 1 second, else sends "held"
//              - 1 x Water Sensor devices (using the 1 analog input pin to measure voltage from a water detector board)
//    
//  Change History:
//
//    Date        Who            What
//    ----        ---            ----
//    2015-01-03  Dan & Daniel   Original Creation
//    2017-02-12  Dan Ogorchock  Revised to use the new SMartThings v2.0 library
//    2017-04-17  Dan Ogorchock  New example showing use of Multiple device of same ST Capability
//                               used with new Parent/Child Device Handlers (i.e. Composite DH)
//    2017-05-25  Dan Ogorchock  Revised example sketch, taking into account limitations of NodeMCU GPIO pins
//    2018-02-09  Dan Ogorchock  Added support for Hubitat Elevation Hub
//
//******************************************************************************************
//******************************************************************************************
// SmartThings Library for ESP8266WiFi
//******************************************************************************************
#include <SmartThingsESP8266WiFi.h>

//******************************************************************************************
// ST_Anything Library 
//******************************************************************************************
#include <Constants.h>       //Constants.h is designed to be modified by the end user to adjust behavior of the ST_Anything library
#include <Device.h>          //Generic Device Class, inherited by Sensor and Executor classes
#include <Sensor.h>          //Generic Sensor Class, typically provides data to ST Cloud (e.g. Temperature, Motion, etc...)
#include <Executor.h>        //Generic Executor Class, typically receives data from ST Cloud (e.g. Switch)
#include <InterruptSensor.h> //Generic Interrupt "Sensor" Class, waits for change of state on digital input 
#include <PollingSensor.h>   //Generic Polling "Sensor" Class, polls Arduino pins periodically
#include <Everything.h>      //Master Brain of ST_Anything library that ties everything together and performs ST Shield communications

#include <PS_Illuminance.h>  //Implements a Polling Sensor (PS) to measure light levels via a photo resistor

#include <PS_TemperatureHumidity.h>  //Implements a Polling Sensor (PS) to measure Temperature and Humidity via DHT library
#include <PS_DS18B20_Temperature.h>  //Implements a Polling Sesnor (PS) to measure Temperature via DS18B20 libraries 
#include <PS_Water.h>        //Implements a Polling Sensor (PS) to measure presence of water (i.e. leak detector)
#include <IS_Motion.h>       //Implements an Interrupt Sensor (IS) to detect motion via a PIR sensor
#include <IS_Contact.h>      //Implements an Interrupt Sensor (IS) to monitor the status of a digital input pin
#include <IS_Smoke.h>        //Implements an Interrupt Sensor (IS) to monitor the status of a digital input pin
#include <IS_DoorControl.h>  //Implements an Interrupt Sensor (IS) and Executor to monitor the status of a digital input pin and control a digital output pin
#include <IS_Button.h>       //Implements an Interrupt Sensor (IS) to monitor the status of a digital input pin for button presses
#include <EX_Switch.h>       //Implements an Executor (EX) via a digital output to a relay
#include <EX_Alarm.h>        //Implements Executor (EX)as an Alarm Siren capability via a digital output to a relay
#include <S_TimedRelay.h>    //Implements a Sensor to control a digital output pin with timing capabilities

//*************************************************************************************************
//NodeMCU v1.0 ESP8266-12e Pin Definitions (makes it much easier as these match the board markings)
//*************************************************************************************************
//#define LED_BUILTIN 16
//#define BUILTIN_LED 16
//
//#define D0 16  //no internal pullup resistor
//#define D1  5
//#define D2  4
//#define D3  0  //must not be pulled low during power on/reset, toggles value during boot
//#define D4  2  //must not be pulled low during power on/reset, toggles value during boot
//#define D5 14
//#define D6 12
//#define D7 13
//#define D8 15  //must not be pulled high during power on/reset

//******************************************************************************************
//Define which Arduino Pins will be used for each device
//******************************************************************************************
//#define PIN_WATER_1               A0  //NodeMCU ESP8266 only has one Analog Input Pin 'A0'
//
//#define PIN_ALARM_1               D0  //SmartThings Capabilty "Alarm"
//#define PIN_BUTTON_1              D8  //SmartThings Capabilty Button / Holdable Button (Normally Open!)
//#define PIN_MOTION_1              D3  //SmartThings Capabilty "Motion Sensor" (HC-SR501 PIR Sensor)
//#define PIN_BUTTON_2              D4  //SmartThings Capabilty Button / Holdable Button (Normally Open!)
#define PIN_SWITCH_1              D5  //SmartThings Capability "Switch"
//#define PIN_SMOKE_1               D1  //SmartThings Capabilty "Smoke Detector"
//#define PIN_TEMPERATURE_1         D7  //SmartThings Capabilty "Temperature Measurement" (Dallas Semiconductor DS18B20)
//#define PIN_TIMEDRELAY_1          D3  //SmartThings Capability "Relay Switch"
#define PIN_CONTACT_1             D6  //SmartThings Capabilty "Contact Sensor"
#define PIN_CONTACT_2             D2  //SmartThings Capabilty "Contact Sensor"


//******************************************************************************************
//ESP8266 WiFi Information
//******************************************************************************************
String str_ssid     = "XXXX";                           //  <---You must edit this line!
String str_password = "XXXX";                   //  <---You must edit this line!
IPAddress ip(192, 168, 0, 79);       //Device IP Address       //  <---You must edit this line!
IPAddress gateway(192, 168, 0, 1);    //Router gateway          //  <---You must edit this line!
IPAddress subnet(255, 255, 255, 0);   //LAN subnet mask         //  <---You must edit this line!
IPAddress dnsserver(90, 207, 238, 97);  //DNS server              //  <---You must edit this line!
const unsigned int serverPort = 8090; // port to run the http server on

// Smartthings / Hubitat Hub TCP/IP Address
IPAddress hubIp(192, 168, 0, 78);    // smartthings/hubitat hub ip //  <---You must edit this line!

// SmartThings / Hubitat Hub TCP/IP Address: UNCOMMENT line that corresponds to your hub, COMMENT the other
const unsigned int hubPort = 39500;   // smartthings hub port (default)
//const unsigned int hubPort = 39501;   // hubitat hub port

//******************************************************************************************
//st::Everything::callOnMsgSend() optional callback routine.  This is a sniffer to monitor 
//    data being sent to ST.  This allows a user to act on data changes locally within the 
//    Arduino sktech.
//******************************************************************************************
void callback(const String &msg)
{
//  Serial.print(F("ST_Anything Callback: Sniffed data = "));
//  Serial.println(msg);
  
  //TODO:  Add local logic here to take action when a device's value/state is changed
  
  //Masquerade as the ThingShield to send data to the Arduino, as if from the ST Cloud (uncomment and edit following line)
  //st::receiveSmartString("Put your command here!");  //use same strings that the Device Handler would send
}

//******************************************************************************************
//Arduino Setup() routine
//******************************************************************************************
void setup()
{
  //******************************************************************************************
  //Declare each Device that is attached to the Arduino
  //  Notes: - For each device, there is typically a corresponding "tile" defined in your 
  //           SmartThings Device Hanlder Groovy code, except when using new COMPOSITE Device Handler
  //         - For details on each device's constructor arguments below, please refer to the 
  //           corresponding header (.h) and program (.cpp) files.
  //         - The name assigned to each device (1st argument below) must match the Groovy
  //           Device Handler names.  (Note: "temphumid" below is the exception to this rule
  //           as the DHT sensors produce both "temperature" and "humidity".  Data from that
  //           particular sensor is sent to the ST Hub in two separate updates, one for 
  //           "temperature" and one for "humidity")
  //         - The new Composite Device Handler is comprised of a Parent DH and various Child
  //           DH's.  The names used below MUST not be changed for the Automatic Creation of
  //           child devices to work properly.  Simply increment the number by +1 for each duplicate
  //           device (e.g. contact1, contact2, contact3, etc...)  You can rename the Child Devices
  //           to match your specific use case in the ST Phone Application.
  //******************************************************************************************
  //Polling Sensors
//  static st::PS_Water               sensor1(F("water1"), 60, 20, PIN_WATER_1, 200);
//  static st::PS_DS18B20_Temperature sensor2(F("temperature2"), 15, 0, PIN_TEMPERATURE_1, false, 10, 1); 
//  static st::PS_TemperatureHumidity sensor9(F("temphumid1"), 60, 40, PIN_TEMPERATUREHUMIDITY_1, st::PS_TemperatureHumidity::DHT21,"temperature1","humidity1");
//  static st::PS_TemperatureHumidity sensor10(F("temphumid2"), 60, 40, PIN_TEMPERATUREHUMIDITY_2, st::PS_TemperatureHumidity::DHT21,"temperature2","humidity2");
  
  //Interrupt Sensors 
  static st::IS_Contact             sensor1(F("contact1"), PIN_CONTACT_1, LOW, true);
  static st::IS_Contact             sensor2(F("contact1"), PIN_CONTACT_2, LOW, true);
//  static st::IS_Button              sensor4(F("button1"), PIN_BUTTON_1, 1000, LOW, true, 500);
//  static st::IS_Button              sensor5(F("button2"), PIN_BUTTON_2, 1000, LOW, true, 500);
//  static st::IS_Motion              sensor6(F("motion1"), PIN_MOTION_1, HIGH, false);
//  static st::IS_Smoke               sensor7(F("smoke1"), PIN_SMOKE_1, HIGH, true, 500);
//
  //Special sensors/executors (uses portions of both polling and executor classes)
  //static st::S_TimedRelay           sensor8(F("relaySwitch1"), PIN_TIMEDRELAY_1, LOW, false, 3000, 0, 1);
  
  //Executors
//  static st::EX_Alarm executor1(F("alarm1"), PIN_ALARM_1, LOW, true);
  static st::EX_Switch executor2(F("switch1"), PIN_SWITCH_1, LOW, true);  //Inverted logic for "Active Low" Relay Board
  
  //*****************************************************************************
  //  Configure debug print output from each main class 
  //  -Note: Set these to "false" if using Hardware Serial on pins 0 & 1
  //         to prevent communication conflicts with the ST Shield communications
  //*****************************************************************************
  st::Everything::debug=true;
  st::Executor::debug=true;
  st::Device::debug=true;
  st::PollingSensor::debug=true;
  st::InterruptSensor::debug=true;

  //*****************************************************************************
  //Initialize the "Everything" Class
  //*****************************************************************************

  //Initialize the optional local callback routine (safe to comment out if not desired)
  st::Everything::callOnMsgSend = callback;
  
  //Create the SmartThings ESP8266WiFi Communications Object
    //STATIC IP Assignment - Recommended
    st::Everything::SmartThing = new st::SmartThingsESP8266WiFi(str_ssid, str_password, ip, gateway, subnet, dnsserver, serverPort, hubIp, hubPort, st::receiveSmartString);
 
    //DHCP IP Assigment - Must set your router's DHCP server to provice a static IP address for this device's MAC address
    //st::Everything::SmartThing = new st::SmartThingsESP8266WiFi(str_ssid, str_password, serverPort, hubIp, hubPort, st::receiveSmartString);

  //Run the Everything class' init() routine which establishes WiFi communications with SmartThings Hub
  st::Everything::init();
  
  //*****************************************************************************
  //Add each sensor to the "Everything" Class
  //*****************************************************************************
  st::Everything::addSensor(&sensor1);
  st::Everything::addSensor(&sensor2);
//  st::Everything::addSensor(&sensor3);
//  st::Everything::addSensor(&sensor4); 
//  st::Everything::addSensor(&sensor5); 
//  st::Everything::addSensor(&sensor6); 
//  st::Everything::addSensor(&sensor7);  
//  st::Everything::addSensor(&sensor8);  
//  st::Everything::addSensor(&sensor9);
//  st::Everything::addSensor(&sensor10);  
      
  //*****************************************************************************
  //Add each executor to the "Everything" Class
  //*****************************************************************************
//  st::Everything::addExecutor(&executor1);
  st::Everything::addExecutor(&executor2);
    
  //*****************************************************************************
  //Initialize each of the devices which were added to the Everything Class
  //*****************************************************************************
  st::Everything::initDevices();
  
}

//******************************************************************************************
//Arduino Loop() routine
//******************************************************************************************
void loop()
{
  //*****************************************************************************
  //Execute the Everything run method which takes care of "Everything"
  //*****************************************************************************
  st::Everything::run();
}

in your arduino code:

//Interrupt Sensors
static st::IS_Contact sensor1(F(“contact1”), PIN_CONTACT_1, LOW, true);
static st::IS_Contact sensor2(F(“contact1”), PIN_CONTACT_2, LOW, true);

should be

//Interrupt Sensors
static st::IS_Contact sensor1(F(“contact1”), PIN_CONTACT_1, LOW, true);
static st::IS_Contact sensor2(F(“contact2”), PIN_CONTACT_2, LOW, true);

looks like copy/paste error

1 Like

Oh god yeah :joy:
You know how many times I looked through that as well
Thanks

1 Like

I have done the same as well. Setup a buddies house with 22 window/door contact sensors. All to be remotely installed due to Covid so Arduino code had to be right.

1 Like

Is there a way to set the Hostname on an esp32 or 8266? When I go into my router the names are all the same like “espressif” and hard to tell which is which. Calling WiFi.setHostname(“myname”); after the setting the ssid and password doesn’t compile.

I have not tried to precompile the hostname, and to make it worse I have not programmed an esp for several months. What I did do, is once the device connected in my router, I can change the hostname there for ease of administration in the router

But looking into the library files, I believe the command looks like WiFi.hostname(st_devicename); as found in the Smartthings8266WiFi.cpp

Based upon that, I think your call should be WiFi.hostname(“myname”);

https://github.com/esp8266/Arduino/issues/2826 kind of confirms this for me. I don’t have any active projects to try this out to confirm.

Good luck

Just tried that, same compile error:
exit status 1
stray ‘\342’ in program

@kampto did you already post your code? I will try setting up an 8266 with that line added here shortly

Actually im using an esp32. Its and NTP clock with large 7-seg LED’s. My use of the ST anything code is a bit unconventional so I get more control.
Here’s the full code

 /* 
Tom K.  April 2015
WiFi Clock
BOARD INFO: "Adafruit esp32 feather" or TTGO Clone.  CPU freq 80Mhz, Flash 4M,  Upload Speed 921600
  Adafruit 7-seg backback https://learn.adafruit.com/adafruit-led-backpack/1-2-inch-7-segment-backpack
  For clock NTP grab use start with this example:  https://lastminuteengineers.com/esp32-ntp-server-date-time-tutorial/
ST_ANYTHING INFO: Github set up info  https://github.com/DanielOgorchock/ST_Anything/blob/master/README.md
  ST_Anything info:  https://community.smartthings.com/t/release-st-anything-v2-8-arduino-esp8266-esp32-to-st-via-thingshield-ethernet-or-wifi/77707
FUNCTION: Displays time down to msec on large LED's, periodically displays temp and humidity, send temp and humidity to smarthings hub, has button to set daylight saving time offsey.
          Periodically WiFi pools the real NTP time time to keep the millis accurate
REVISIONS:
Sept13-2016: Initial inception and build, small 7-seg LED, Uno board
July14-2017: Mega board, serial esp-01, and Big LED's. NTP clock using WiFiUDP.h
Oct20-2018: Set up ST_Anything on Mega
July12-2019: Converter to esp32 board for more reliable connectivity, switch to time.h library, add daylights savings change button
Mar24-2020: Add client to server communication for Arduino to Arduino,  added button to set the Dayllight savings offset
*/

//******************************* Adafruit i2c 7-Seg library requirements ***************************
#include <Wire.h> 
#include <Adafruit_GFX.h>
#include "Adafruit_LEDBackpack.h"
#include "time.h"

//********************************************  ST_Anything Librarys **********************************************
#include <SmartThingsESP32WiFi.h>  // SmartThings Library for ESP32 boards.  Use " " if library is custom and local 
#include <Constants.h>       //Constants.h is designed to be modified by the end user to adjust behavior of the ST_Anything library
#include <Device.h>          //Generic Device Class, inherited by Sensor and Executor classes
#include <Sensor.h>          //Generic Sensor Class, typically provides data to ST Cloud (e.g. Temperature, Motion, etc...)
#include <Executor.h>        //Generic Executor Class, typically receives data from ST Cloud (e.g. Switch)
#include <InterruptSensor.h> //Generic Interrupt "Sensor" Class, waits for change of state on digital input 
#include <PollingSensor.h>   //Generic Polling "Sensor" Class, polls Arduino pins periodically
#include <Everything.h>      //Master Brain of ST_Anything library that ties everything together and performs ST Shield communications

//#include <PS_TemperatureHumidity.h>  //Implements a Polling Sensor (PS) to measure Temperature and Humidity via DHT library
//#include <IS_Motion.h>       //Implements an Interrupt Sensor (IS) to detect motion via a PIR sensor on a digital input pin
//#include <IS_Contact.h>      //Implements an Interrupt Sensor (IS) to monitor the status of a digital input pin
//#include <IS_Button.h>       //Implements an Interrupt Sensor (IS) to monitor the status of a digital input pin for button presses
#include <EX_Switch.h>       //Implements an Executor (EX) via a digital output to a relay
#include <EX_Alarm.h>        //Implements Executor (EX)as an Alarm capability with Siren and Strobe via digital outputs to relays
#include <S_TimedRelay.h>    //Implements a Sensor to control a digital output pin with timing/cycle repeat capabilities

Adafruit_7segment matrix1 = Adafruit_7segment(); // For Adafruit 7-seg i2c
Adafruit_7segment matrix2 = Adafruit_7segment(); // For Adafruit 7-seg i2c

//***************************************** Adafruit Feather ESP32 Pins ***********************************************
//#define xxxxxx      A13 // GPI35 or A13, - Internal Fetaher pin, used for internal Bat voltage Divider, The voltage is divided by 2.
//#define Button1       34 // GPI #34 or A2, Note it is not an output-capable pin!
#define DHTpin        4 // GPIO #4 or A5, AI only
//#define xxxxxx      A0 // GPIO #26 or A0, AI & AO an analog output DAC2 
//#define xxxxxx      A1 // GPIO #25 or A1, AI & AO an analog output DAC1
//#define xxxxxx      A3 // GPI #39 or A3, Note it is not an output-capable pin!
//#define xxxxxx      A4 // GPI #36 or A4, Note it is not an output-capable pin!
#define Button1       21 // GPIO #21, General purpose IO
//#define xxxxxx      13 // GPIO #13 or A12, It's also connected to the red LED next to the USB port
//#define xxxxxx      12 // GPIO #12 or A11. has a pull-down resistor built int, recommend as output only, or sure that the pull-down is not affected during boot.
#define ST_Messege      27 // GPIO #27 or A10
//#define xxxxxx      33 // GPIO #33 or A9. It can also be used to connect a 32 KHz crystal.
//#define xxxxxx      15 // GPIO #15 or A8,  Use this as the STI trigger pin, not hooked up to anything
//#define xxxxxx      32 // GPIO #32 or A7. It can also be used to connect a 32 KHz crystal.
//#define xxxxxx    14 // GPIO #14 or A6
//#define xxxxxx      12 // GPIO #12, has an internal pulldown, Bootloading on Feather, or output only
//SDA                 23 // SDA I2C (Wire) data pin, Adafruit Feather Specific?
//SCL                 22 // SCL I2C (Wire) clock pin, Adafruit Feather Specific?
//MOSI                18 // MOSI SPI Master-Out-Slave-In, Adafruit Feather Specific?
//MISO                19 // MISO SPI Master-In-Slave-Out, Adafruit Feather Specific?
//RX                  16 // RX receive (input) pin, Adafruit Feather Specific?
//TX                  17 // TX transmit (output) pin, Adafruit Feather Specific?
//SCK                 5  // SCK SPI Clock, Adafruit Feather Specific?
//EN                  // this is the 3.3V regulator's enable pin. It's pulled up, so ground to disable the 3.3V regulator

//// DHT (non-i2c) Temp and Humidity, DHT Pin1 = Vcc, Pin2 = Data, Pin4 = gnd, Connect a 10K resistor from pin 2 (data) to pin 1 (power)
#include "DHTesp.h" // DHT Library specific for esp32 boards 
DHTesp dht;
float humid1; // Humidity
float DHT_TempC; // Temp in C
float temp1; // Temp in F

const char* ntpServer = "pool.ntp.org";
long  gmtOffset_sec = -28800; // California, -7hrs + Daylight savings    // < ------------- YOU MUST SET THIS
const int   daylightOffset_sec = 0; // 0 or -3600              // This didnt work!!
bool DaylightSavngs = false;
int RFrssi;
const byte SenderID = 5; //  ID of this station                                 <------You must edit this line!

// TIMERS and CLOCK
unsigned long TempTimeDelay = 60000; // For temp display
unsigned long TempTimer = 0;  // For temp display
unsigned long NTPpollDelay = 300000; // Set long to reduce polling internet traffic, millis will calc the minute in between
unsigned long NTPpollTimer = 0;  
unsigned long TempReadTimer = 0; 
unsigned long TempReadDelay = 120000; // Wait Time for local Temp reads
unsigned long STSendTimer = 0; 
unsigned long STSendDelay = 310000; // Wait Time for local Temp reads
unsigned long SerialTimeTimer = 0; // only serial print in intervals otherwise IDE seril monitor will overload
unsigned long SerialTimeDelay = 30000;
unsigned long ClientSendTimer = 0; // For wifi data sends, non-ST
unsigned long ClientSendDelay = 480000;

int Hour = 0;
int Minute = 0;
int Second = 0;
unsigned long DisplayMsec = 0;
int DisplayTime = 0;
int DisplaySeconds = 0;
unsigned long Msec = 0; 
byte DisplayState = 0;

char HourAndMinuteString[6]; //5 digits plus the null char
char SecondAndMsecString[6]; //5 digits plus the null char

//******************************** ESP8266 WiFi Information **********************************************
String str_ssid     = "xxxx";       //                                        <------You must edit this line!
String str_password = "xxxxxxxxxxxxx";  //                                        <------You must edit this line!
//WiFi.hostname(“NTPclock”);  // ************* Doesnt Work
IPAddress ip(192, 168, 0, 153);       //Device IP Address                       <------You must edit this line!
IPAddress gateway(192, 168, 0, 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, 0, 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, 0, 150);    // smartthings hub ip                     <------You must edit this line!
const unsigned int hubPort = 39500;   // smartthings hub port
// Server info, where the non ST data goes
IPAddress server(192,168,0,155);      // fixed IP address of arduino server     <------You must edit this line!
WiFiClient client; // to connect to server

struct tm timeinfo; // Call out NTPclock get structure

//************************** ************  Arduino Setup() routine ************************************************
void setup(){
  Serial.begin(115200); 
  Serial.println("Setting Up!!!!!!!!!");
  
  dht.setup(DHTpin, DHTesp::DHT22);
  Serial.println("DHT initiated............");
  //Wire.begin(23,22); // Feather32 board SCL->22 and SDA->23 with a revised Wire.begin(SDA,SCL)
  Wire.begin(); // Feather32 board SCL->22 and SDA->23 with a revised Wire.begin(SDA,SCL)

  pinMode(Button1, INPUT_PULLUP); // 
  pinMode(ST_Messege, INPUT); 
  
//// ESP32 ADC Set-up
  analogReadResolution(11); // Set pin Resolution. Default of 12 is not very linear. 12 = 0-4095, 11 = 0-2047, 10 = 0-1024, 9 = 0-512 
  analogSetAttenuation(ADC_11db);  // Sets attenuation for all pins. 11db=0-3.3v, 6dB=0-2.2v, 2.5db=0-1.5v, 0db= 0-1v, Default is 11db which is noisy. 
    
//Initialize the Adafruit LED display i2c  device(s)
   matrix1.begin(0x70); // Address the Adafuit 7-seg i2c display, Default no jumper
   matrix1.setBrightness(2); // 0 is least bright, 15 is brightest 
   matrix2.begin(0x74); // Address the Adafuit 7-seg i2c display, Short A2 jumper
   matrix2.setBrightness(2); // 0 is least bright, 15 is brightest 

//SPECIAL sensors/executors (uses portions of both polling and executor classes)
  static st::S_TimedRelay           sensor2(F("relaySwitch1"),ST_Messege, LOW, false, 2000, 0, 1); // Low = init stae, false = no inverted logic, 10000 on time
  //static st::S_TimedRelay           sensor22(F("relaySwitch2"), PIN_TIMEDRELAY_2, LOW, true, 3000, 0, 1);

//EXECUTORS
  //static st::EX_Switch              executor1(F("switch1"), PURGEBUTTON, LOW, false);  // LOW = "initial state off", false = no inverted logic
  //static st::EX_Switch              executor2(F("switch2"), PIN_SWITCH_2, LOW, true);
 
//********************************** Configure debug print output from each main class  *******************************************
  st::Everything::debug=true;
  st::Executor::debug=true;
  st::Device::debug=true;
  st::PollingSensor::debug=true;
  st::InterruptSensor::debug=true;

//*************************************Initialize the "Everything" Class****************************************
   //Create the SmartThings ESP32 Communications Object,  STATIC IP Assignment - Recommended
   st::Everything::SmartThing = new st::SmartThingsESP32WiFi(str_ssid, str_password, ip, gateway, subnet, dnsserver, serverPort, hubIp, hubPort, st::receiveSmartString);
  
   //DHCP IP Assigment - Must set your router's DHCP server to provice a static IP address for this device's MAC address
   //st::Everything::SmartThing = new st::SmartThingsESP32WiFi(str_ssid, str_password, serverPort, hubIp, hubPort, st::receiveSmartString);
   
st::Everything::init();  //Run the Everything class' init() routine which establishes Ethernet communications with the SmartThings Hub
  
//********************************Add each sensor to the "Everything" Class*********************************************
  //st::Everything::addSensor(&sensor1);
  st::Everything::addSensor(&sensor2);
 
//******************* Add each executor to the "Everything" Class******************************************
  //st::Everything::addExecutor(&executor1);
  //st::Everything::addExecutor(&executor2);
  
st::Everything::initDevices(); //Initialize each of the devices which were added to the Everything Class

NTPclock(); // Start off with getther NTP time

}

//****************************************  Arduino Loop() routine **************************************************
void loop(){
  sensorReads(); //FUNCTION
  STsend(); // FUNCTION
  ClientSend();
 
//// Daylight Savings offset Button push
  if ((digitalRead(Button1) == LOW) && (DaylightSavngs == false)) {DaylightSavngs = true; gmtOffset_sec = -25200; Serial.println(F("...Button Pushed...")); delay(2000); NTPclock();}
  if ((digitalRead(Button1) == LOW) && (DaylightSavngs == true)) {DaylightSavngs = false; gmtOffset_sec = -28800; Serial.println(F("...Button Pushed...")); delay(2000); NTPclock();}
  
  st::Everything::run();  //Execute the Everything run method which takes care of "Everything"

//// NTP pooling and temp/humid display timers
  if (digitalRead(ST_Messege) == HIGH) {TempTimer = (millis() - TempTimeDelay); Serial.println(F("...ST Messege Recieved...")); }  // if switched from ST, Write temp to big display
   
    if (millis() - NTPpollTimer < NTPpollDelay && DisplayState == 0) {ClockDisplay(); }  // Display Time running on millis()
    else if (millis() - NTPpollTimer > NTPpollDelay) {NTPclock(); NTPpollTimer = millis();}  // Get new refernce from NTP
    
    if ((millis() - TempTimer >= TempTimeDelay) && DisplayState == 0) {refreshDisplay(); DisplayState = 1; }  
    else if ((millis() - TempTimer < TempTimeDelay + 5000) && DisplayState == 1) {BigTempHumid(); }  
    else if ((millis() - TempTimer > TempTimeDelay + 5000) && DisplayState == 1) {refreshDisplay(); TempTimer = millis(); DisplayState = 0; } 
              
  }

//****************************************** Read Sensors ********************************************  
void sensorReads() {
  if (millis() - TempReadTimer > TempReadDelay) {
     RFrssi = WiFi.RSSI();
//// DHT Temperature and Humidity Read
      delay(dht.getMinimumSamplingPeriod());
      float humidity = dht.getHumidity();
      float temperature = dht.getTemperature();
      Serial.print(F("DHT Humidity = "));Serial.print(humidity, 1); Serial.println(F(" %"));
      Serial.print(F("DHT Temp = "));Serial.print(temperature, 1); Serial.println(F(" *C"));
      Serial.print(F("DHT Temp = "));Serial.print(dht.toFahrenheit(temperature), 1); Serial.println(F(" *F"));
      humid1 = humidity; DHT_TempC = temperature; temp1 = (dht.toFahrenheit(temperature)); // Assign to global variables
   TempReadTimer = millis();
  }
}

//****************************************** Send Data to ST ********************************************  
void STsend() {
  if (millis() - STSendTimer > STSendDelay) {
    if ((temp1 > -30) && (temp1 < 160)) {String STtemperature1("temperature1 " + String(temp1)); st::Everything::sendSmartString(STtemperature1);} //
    if ((humid1 > 0) && (humid1 < 101)) {String SThumidity1("humidity1 " + String(humid1)); st::Everything::sendSmartString(SThumidity1);} //
  STSendTimer = millis();
  }
}

//****************************************** Send Data to Arduino Server ****************************************
void ClientSend() {
  if (millis() - ClientSendTimer > ClientSendDelay) {
  client.connect(server, 23); 
  String strSenderID("SenderID"); strSenderID.concat(" "); strSenderID.concat(SenderID);
  String strtemp1("temp1"); strtemp1.concat(" "); strtemp1.concat(temp1);
  String strhumid1("humid1"); strhumid1.concat(" "); strhumid1.concat(humid1);
  String strRFrssi("RFrssi"); strRFrssi.concat(" "); strRFrssi.concat(RFrssi);

  Serial.println(""); Serial.println("..........Sending Variables to Server");
  client.println("Starting Data Stream");
  client.println(strSenderID); Serial.println(strSenderID); // Need to send ID first
  client.println(strtemp1); Serial.println(strtemp1); 
  client.println(strhumid1); Serial.println(strhumid1); 
  client.println(strRFrssi); Serial.println(strRFrssi); 

  client.flush();
  client.stop(); 
  Serial.println("..........Disconnecting"); Serial.println("");
  delay(7); // add appropriate delay here before sending next data element
  ClientSendTimer = millis();
  }
}

//*********************************** Big Temperature Display ****************************
void BigTempHumid() {
///Temp
  matrix1.print(temp1); 
  matrix1.writeDigitRaw(4, 0b0000000001110001); // 0b0000000001110001 = F, 0b0000000011110110 = H, look in backpack.cpp file for others characters
  matrix1.writeDigitRaw(2, 0x02); // location 2 is for dots, 0x02 center colon (both dots), 0x04 left colon lower dot, 0x08 left colon upper dot, 0x10 decimal point 
  matrix1.writeDisplay(); // required to update display
///Humid  
  matrix2.print(humid1); 
  matrix2.writeDigitRaw(4, 0b0000000011110110); // 0b0000000001110001 = F, 0b0000000011110110 = H, look in backpack.cpp file for others characters
  matrix2.writeDigitRaw(2, 0x02); // location 2 is for dots, 0x02 center colon (both dots), 0x04 left colon lower dot, 0x08 left colon upper dot, 0x10 decimal point 
  matrix2.writeDisplay(); // required to update display
 }

//*************************************** Big Clock Display ***********************************
void ClockDisplay() {

  Msec = ((millis() - NTPpollTimer)/10); // get 100th of second in between NTP calls

  String strMsec(Msec);
  if (Msec - DisplayMsec  >99) {DisplayMsec = Msec; Second = Second + 1;}
  if (Msec < 1000) {strMsec.remove(0,1);}  // Strip out seconds as it incriments
  else if (Msec < 10000) {strMsec.remove(0,2);}
  else if (Msec < 100000) {strMsec.remove(0,3);}  
  Msec = strMsec.toInt();
  
  if (Second > 59) {Second = 0; Minute = Minute + 1;}
  if (Minute > 59) {Minute = 0; Hour = Hour + 1;}
  if (Hour >23) {Hour = 0;}

   sprintf(HourAndMinuteString, "%02d%02d", Hour, Minute); // Add leading zero if needed
   String strTime(HourAndMinuteString);
   DisplayTime = strTime.toInt();

   sprintf(SecondAndMsecString, "%02d%02d", Second, Msec); // Add leading zero if needed
   String strTimeSec(SecondAndMsecString);
   DisplaySeconds = strTimeSec.toInt();
  
  //// Display 1 Hr + Min
  matrix1.print(DisplayTime);
  matrix1.drawColon(true); // colon
  if (Hour < 10 ) {matrix1.writeDigitNum(0, 0); } //Write 0 in first digit
  matrix1.writeDisplay(); // required to update display

  //// Display 2 Sec + Msec
   matrix2.print(DisplaySeconds);
   matrix2.writeDigitRaw(2, 0x02 | 0x04 | 0x08); // center colon, left lower dot colon, left upper dot colon
   if (Second < 1 ) {matrix2.writeDigitNum(0, 0); matrix2.writeDigitNum(1, 0);} // Write 00
   if (Second < 10 ) {matrix2.writeDigitNum(0, 0); } //Write 0
   matrix2.writeDisplay(); // required to update display

//// Serial Prints of NTP time
  if (millis() - SerialTimeTimer > SerialTimeDelay) {
    Serial.println(&timeinfo, "%A, %B %d %Y %H:%M:%S");
    Serial.println(&timeinfo, "%H:%M:%S");
    //Serial.println(strDisplayHour);
    Serial.print(HourAndMinuteString); Serial.println(" HourAndMinuteString");
    Serial.print(DisplaySeconds); Serial.println(" DisplaySeconds");
    //Serial.print(Second); Serial.println(" Second");
    Serial.print(Msec); Serial.println(" Msec");
    SerialTimeTimer = millis();
  }

}


//***************************************** Display Refesh *******************************************
void refreshDisplay() {
  
  for (int m=0; m<4; m++){
  for (int k=0; k<6; k++){
  matrix1.clear(); // Clear display
  if (k==2) {k++;} // incriment if 2 becuase 2 is the dots
  matrix1.writeDigitRaw(k, 0b0000000011000000); // write "-" to digit
  matrix1.writeDisplay(); // required to update display
  delay(20);
    }
  for (int k=0; k<6; k++){
  matrix2.clear(); // Clear display
  if (k==2) {k++;} // incriment if 2 becuase 2 is the dots
  matrix2.writeDigitRaw(k, 0b0000000011000000); // write "-" to digit
  matrix2.writeDisplay(); // required to update display
  delay(20);
  }
 }
}

//***************************************** UDP NTP Clock Recieve *******************************************
void NTPclock() {
  
  configTime(gmtOffset_sec, daylightOffset_sec, ntpServer); //init and get the time
  
  if(!getLocalTime(&timeinfo)){Serial.println("Failed to obtain time"); return; }
  Serial.print(" Aquired NTP Time!! "); Serial.println(&timeinfo, "%A, %B %d %Y %H:%M:%S");

  //// Convert compenets to integers for later calculations
  char HourStringBuff[3];  strftime(HourStringBuff, sizeof(HourStringBuff), "%H", &timeinfo);
  char MinStringBuff[3];  strftime(MinStringBuff, sizeof(MinStringBuff), "%M", &timeinfo);
  char SecStringBuff[3];  strftime(SecStringBuff, sizeof(SecStringBuff), "%S", &timeinfo);
  String strHour(HourStringBuff);
  String strMinute(MinStringBuff);
  String strSecond(SecStringBuff);

  Second = strSecond.toInt();
  Minute = strMinute.toInt();
  Hour = strHour.toInt();

/*
%A  returns day of week
%B  returns month of year
%d  returns day of month
%Y  returns year
%H  returns hour
%M  returns minutes
%S  returns seconds
*/
  NTPpollTimer = millis(); // reset NTP polling timer so it doesnt constant poll 
 }

I’m having trouble using the basic demo script for the ultrasound device… I have an HC-SR04…

Smartthings found it, but doesn’t respond to motion events… :man_facepalming:

@kampto try moving your code into the void setup() area

also, I think your original code was correctly syntaxed as

WiFi.setHostname(“NTPclock”);

@danielccm what do you mean by

Smartthings found it

Also, is the parent showing up as present in the app?

Yes, you can easily set the Microcontroller Hostname in the sketch, by simply adding a parameter to the following line of code…

  //Create the SmartThings ESP32WiFi Communications Object
    //STATIC IP Assignment - Recommended
    st::Everything::SmartThing = new st::SmartThingsESP32WiFi(str_ssid, str_password, ip, gateway, subnet, dnsserver, serverPort, hubIp, hubPort, st::receiveSmartString);

make it look like…

  //Create the SmartThings ESP32WiFi Communications Object
    //STATIC IP Assignment - Recommended
    st::Everything::SmartThing = new st::SmartThingsESP32WiFi(str_ssid, str_password, ip, gateway, subnet, dnsserver, serverPort, hubIp, hubPort, st::receiveSmartString, "ESP32Wifi");

change the “ESP32Wifi” to whatever name you’d like. That’s it! :slight_smile:

UPDATE: This may only work on the ESP8266, not the ESP32… Let me take a deeper look…

I just confirmed adding “devicename” to the end of the IP assignment doesn’t compile either with esp32. This isnt a big deal having the name but more of a convenience troubleshooting thing. Thanks.

I have updated my GitHub repo with new versions of the “SmartThingsESP32WiFi” library files. Please grab both the new .h and .cpp files. Modify your sketch’s setup() routine as shown above.

Currently, I have mixed results with this using my new Unifi Dream Machine network. If you comment out the static IP line, and uncomment the DHCP line, and add the Hostname as shown above, it works. My Unifi network shows the client with the correct host name. If I tried it with a static IP address, my Unifi system showed the name as the device MAC address.

Give it a try and let me know what you see, please.

Thanks… I loaded your new library, closed IDE and reopened. It compiled this time. Uploaded new sketch with the name at the end of IP assignment. Rebooted router. Powered up the device. Unfortunately still showing up as “espressif”. Could be the router hanging onto old names. Will play with it some.

Did you switch to DHCP in the sketch? It will require A DHCP Address Reservation in order to guarantee the IP address of the ESP32 does not change. Just a test to see if it makes a difference for you, like it did for me.

Hells Yes! DHCP mode worked. Name shows up on router even without a reboot! Thanks.

1 Like