ESP8266 E01 and button

Hello,
I want to connect a button to an ESP8266, seems quite simple, but I'm having trouble making it work !
The GPIO0,GPIO2,RST and CH_PD pins must be connected to VCC with a pullup resistor for the chip to start, this makes it quite difficult to use a button with it but apparently, it is possible as shown on this website, but I can't figure out how to make it work !

I did the exact same schematics as shown on there ( in the "Using GPIO0, GPIO2 and GPIO15 as Inputs." part) and here is my code :

#include <SPI.h>
#include <ESP8266WiFi.h>

byte button = 2;
char ssid[] = "nop";           
char pass[] = "nop";          

unsigned long askTimer = 0;

IPAddress server(192,168,0,80);       
WiFiClient client;

void setup() {
pinMode(0,OUTPUT);
digitalWrite(0,LOW);
pinMode(button, INPUT);
  Serial.begin(115200);               
  WiFi.begin(ssid, pass);             
  while (WiFi.status() != WL_CONNECTED) {
  
    delay(1000);
  }
}

void loop () {
  client.connect(server, 80);   
  if (digitalRead(button)==HIGH);
     {
           client.println("test\r");
           
     }
  delay(1000);                  
}

The board will always send "test" if I push or not the button, any advice ?

Thanks !

with pull-ip on a pin, connect button between pin and ground. if you push the button down the pin will read LOW

Do yourself a favour, get a fully pinned module.

NodeMCU 12 or similar.

Playing with the 01 devices is hardly worth it unless you need to use one for deployment.

Hello,
I've tried to connect button between pin and ground, no luck there !
So I change my code and circuit to see the reading of the GPIO2 pin... And it just reads HIGH, LOW, HIGH, LOW etc... I've tried my 4 ESP's to see if it changes... nothing will do ! tried only connecting the GPIO2 to VCC with a 3.3K resistor, so i'm almost shure it should read HIGH... but keeps reading HIGH then LOW !
I tried the code directly from the USB adapter thingy, same results !
I checked my wiring and tested averything about 184203290 times to be shure, starting to get desperate x')

If you have an explication and a solution, I'dd be... well, very happy and gratefull !

Here is my code :

#include <SPI.h>
#include <ESP8266WiFi.h>

byte button = 2;
char ssid[] = "HELP";           
char pass[] = "I need somebody";          

unsigned long askTimer = 0;

IPAddress server(192,168,0,80);       
WiFiClient client;

void setup() {
pinMode(button, INPUT);
  Serial.begin(115200);               
  WiFi.begin(ssid, pass);             
  while (WiFi.status() != WL_CONNECTED) {
  
    delay(1000);
  }
}

void loop () {
 // client.connect(server, 80);   
  if (digitalRead(button)==LOW);
     {
      Serial.println("LOW");
           // client.println("He is awake\r");
           }

             if (digitalRead(button)==HIGH);
     {
      Serial.println("HIGH");
           
     }
  delay(1000);                  
}

And next time for a Wi-Fi project, I'll choose a node MCU... but now, I can't let this board sitting there, "J'en fais une affaire personnel" as we say in French !

"J'en fais une affaire personnel" as we say in French !

if (digitalRead(button)==LOW);

Lose the semicolon (perdre le point-virgule) as we say in English

carlitototo:
Hello,
I've tried to connect button between pin and ground, no luck there !
So I change my code and circuit to see the reading of the GPIO2 pin... And it just reads HIGH, LOW, HIGH, LOW etc... I've tried my 4 ESP's to see if it changes... nothing will do ! tried only connecting the GPIO2 to VCC with a 3.3K resistor, so i'm almost shure it should read HIGH... but keeps reading HIGH then LOW !
I tried the code directly from the USB adapter thingy, same results !
I checked my wiring and tested averything about 184203290 times to be shure, starting to get desperate x')

If you have an explication and a solution, I'dd be... well, very happy and gratefull !

Here is my code :

#include <SPI.h>

#include <ESP8266WiFi.h>

byte button = 2;
char ssid[] = "HELP";         
char pass[] = "I need somebody";

unsigned long askTimer = 0;

IPAddress server(192,168,0,80);     
WiFiClient client;

void setup() {
pinMode(button, INPUT);
  Serial.begin(115200);             
  WiFi.begin(ssid, pass);           
  while (WiFi.status() != WL_CONNECTED) {
 
    delay(1000);
  }
}

void loop () {
// client.connect(server, 80); 
  if (digitalRead(button)==LOW);
    {
      Serial.println("LOW");
          // client.println("He is awake\r");
          }

if (digitalRead(button)==HIGH);
    {
      Serial.println("HIGH");
         
    }
  delay(1000);                 
}





And next time for a Wi-Fi project, I'll choose a node MCU... but now, I can't let this board sitting there, "J'en fais une affaire personnel" as we say in French !

do you have a pull-up resistor on io pin?

Hello !
Well as we say in French... je suis trop bête !
I didn't know we didn't need to put a semicolon after an if or a while !
The button code works perfectly now !
(and yes I had a pullup resistor on pin ^^)

But one problem leads to another I guess, when the time I set in the code arrives, it beeps kinda randomly, and never stops even if I push the button !
I tried to read the string in the while loop, wouldn't display anything ! Any idea why so ? I believe it should, in the loop, re read the string over and over again, when the button is pressed the string would make the while false and the code would move on to the next step... but apparently not !

As for the random bipping, I think it is due to the time the ESP takes to retrieve the string and it bugs or something like this... not shure, if you have a clue, tell me :slight_smile:

I tested outside of the loop, the string are received correctly and and change when button pushed !

here is the button code ( working :slight_smile: ) :

#include <SPI.h>
#include <ESP8266WiFi.h>

byte button = 2;
char ssid[] = "CDC2CV";           
char pass[] = "carlito2002";          

unsigned long askTimer = 0;

IPAddress server(192,168,0,80);       
WiFiClient client;

void setup() {
pinMode(button, INPUT);
  Serial.begin(115200);               
  WiFi.begin(ssid, pass);             
  while (WiFi.status() != WL_CONNECTED) {
  
    delay(1000);
  }
}

void loop () {
 client.connect(server, 80);   
  if (digitalRead(button)==LOW)
     {
      Serial.println("LOW");
      client.println("He is awake\r");
     }
  if (digitalRead(button)==HIGH)
     {
      Serial.println("HIGH");
      client.println("He is sleeping\r");
     }

       
  delay(1000);                  
}

and here is the buzzer code :

#include <NTPClient.h>
#include <SPI.h>                   
#include <ESP8266WiFi.h>
#include <WiFiUdp.h>

byte buzzer = 2;
char ssid[] ="CDC2CV";
char pass[] ="carlito2002";
WiFiServer server(80);              

const long utcOffsetInSeconds = 7200;


WiFiUDP ntpUDP;
NTPClient timeClient(ntpUDP, "pool.ntp.org", utcOffsetInSeconds);

int Hours = timeClient.getHours();
int Minutes = timeClient.getMinutes();
int Seconds = timeClient.getSeconds();

WiFiClient client;

void setup() {
Serial.begin(115200);                   // only for debug
  WiFi.begin(ssid, pass);                 // connects to the WiFi router
  while (WiFi.status() != WL_CONNECTED) {
    Serial.println("c'est connecté");
      delay(1000);
  }
  pinMode(buzzer, OUTPUT);
  server.begin();                         // starts the server
 }
void loop () {
  WiFiClient client = server.available();
int Hours = timeClient.getHours();
int Minutes = timeClient.getMinutes();
int Seconds = timeClient.getSeconds();
    //Serial.print(Hours);
    //Serial.print(":");
    //Serial.print(Minutes);
    //Serial.print(":");
    //Serial.println(Seconds);
timeClient.update();
String request = client.readStringUntil('\r'); 
//Serial.print("requete client :");
             // Serial.println(request); 
 if (Hours == 21 && Minutes == 13 && Seconds == 00)
  {
    while((request)==("He is sleeping"))
        {    
             //Serial.println("ça sonne normalement !");
             digitalWrite(buzzer, HIGH);
             //Serial.println("Bip");
             delay(500);
             digitalWrite(buzzer, LOW);
             //Serial.println("Bop");   
             delay(500);
             String request = client.readStringUntil('\r');
              //Serial.print("requete client :");
              //Serial.println(request); 
                 }
          
               
              }
              
       if ((request)==("He is awake"))
      
                
                {
                digitalWrite(buzzer, LOW);
                //Serial.println("normalement c'est éteint");
                //Serial.println("requete client :");
              //Serial.print(request); 
                
                }
            
        
    
   
    

  delay(500);
  }

Thank you very much !

PS : Not shure if I said it, but this is supposed to be a very annoying alarm clock were the only way to making it stop is either to cut the power cord or to press on the button ( placed as far away as possible from the bed ) to force myself to wake up :slight_smile:

Hi !

no debounce ... so you'll get many messages when pushing or releasing the push button.

After change detection and message sending insert a 100 mS delay, it could be enougth.

good luck

Just a quick tidy.
Both the Button and receiver code is in this.

//#define BUTTONCODE // Switch this line for different module

byte pin_buzzer = 2;
byte pin_button = 2;
char ssid[] = "***********";
char pass[] = "***********";
unsigned long askTimer = 0;

#include <SPI.h>
#include <ESP8266WiFi.h>
IPAddress serverIP(192,168,0,80);       
WiFiClient socket;


/////////////////////////////
#ifdef BUTTONCODE
/////////////////////////////
void setup() {
  pinMode(pin_button, INPUT_PULLUP);
  Serial.begin(115200);               
  while (!Serial){yield();}
  WiFi.begin(ssid, pass);             
  askTimer = millis();
  while (WiFi.status() != WL_CONNECTED) {
    Serial.print(".");
    delay(100);
  }
  Serial.println();
}
/////////////////////////////
void loop () {
  if((millis() - askTimer) < 1000){return;}
  askTimer = millis();
  socket.connect(serverIP, 80);   
  if (digitalRead(pin_button) == HIGH) {Say_HIGH();}
  if (digitalRead(pin_button) == LOW) {Say_LOW();}
}
/////////////////////////////
void Say_HIGH(){
  Serial.println("HIGH");
  socket.println("He is sleeping\r");
}       
/////////////////////////////
void Say_LOW(){
  Serial.println("LOW");
  socket.println("He is awake\r");
}
/////////////////////////////
/////////////////////////////
#else
/////////////////////////////
/////////////////////////////
const long utcOffsetInSeconds = 7200;
const int buzzint = 500;
unsigned long buzztime = 0;

#include <NTPClient.h>
#include <WiFiUdp.h>
WiFiUDP ntpUDP;
NTPClient timeClient(ntpUDP, "pool.ntp.org", utcOffsetInSeconds);

int Hours = 0;
int Minutes = 0;
int Seconds = 0;

bool pinstate = LOW;
bool alarmactive = false;

WiFiServer server(80);              
/////////////////////////////
void setup() {
  pinMode(pin_buzzer, OUTPUT);
  digitalWrite(pin_buzzer, LOW);
  
  Serial.begin(115200);                   // only for debug
  while (!Serial){yield();}
  WiFi.begin(ssid, pass);                 // connects to the WiFi router
  
  while (WiFi.status() != WL_CONNECTED) {
    Serial.println("c'est connecté");
    delay(1000);
  }
  server.begin();                         // starts the server
}
/////////////////////////////
void loop () {
  UpdateTime();
  if (Hours == 21 && Minutes == 13 && Seconds == 00) {alarmactive = true;}
  processAlarm();  
  WiFiClient client = server.available();  
  if(!client){return;}
  
  String request = client.readStringUntil('\r'); 
  if (request == "He is awake") {alarmactive = false;}
  
  //if (request == "He is sleeping"){alarmactive = true;}
  //Serial.print("requete client :");  // Serial.println(request); 
}
/////////////////////////////
void UpdateTime(){
  int lastsec = Seconds;
  timeClient.update();
  Hours = timeClient.getHours();
  Minutes = timeClient.getMinutes();
  Seconds = timeClient.getSeconds();
  if (Seconds != lastsec){
    Serial.print(Hours); Serial.print(":"); Serial.print(Minutes); Serial.print(":"); Serial.println(Seconds);
  }
}
/////////////////////////////
void processAlarm(){
  if (!alarmactive){pinstate = LOW; digitalWrite(pin_buzzer, pinstate); return;}  //Serial.println("Bop");   
  if ((millis() - buzztime) > buzzint){
    buzztime = millis();
    pinstate = !pinstate;
    digitalWrite(pin_buzzer, pinstate); //Serial.println("Bip");
  }
}
/////////////////////////////
void MakeNoise(){
  digitalWrite(pin_buzzer, HIGH); //Serial.println("Bip");
  delay(buzzint);
  digitalWrite(pin_buzzer, LOW);  //Serial.println("Bop");   
  delay(buzzint);
}
/////////////////////////////
#endif
/////////////////////////////

Two recommendations for the buzzer code.

Do not have multiple local declarations of String request with different scopes. I would declare it as global, and use a request.reserve(20) at the top of loop() to help avoid memory fragmentation.

request = client.readStringUntil('\r');

This is a blocking call. I would place it within a if(client.available()) conditional

if(client.available())
{ request = client.readStringUntil('\r');
   Serial.print("requete client :");
   Serial.println(request)
}

Hello !

Hiddenvision:
Just a quick tidy.

Even if you have, I would guess 3000000000% more skill than me, I'm shure it's more than just a quick tidy ! You rewrote the whole thing ! I tested it and it works just as intended, would of taken me 1 month to get even close to this result :') And this code is mad, I'm trying to understand it, but so much synthax I don't know about, it's great... Thank you 1000 times !
I didn't know it was possible to make multiple void blocks, the yield thing is amazing, same goes for the #DefineIf, #EndIf, I'm going to dig into this and learn to try and improve my noob coding skills !

As for the debounce, I did a quick a search and it appears to prevent the button sending multiples states because of bouncing connector thingy inside it, I'm not shure why this would be usefull for my code, since I only need one push to send the string, but I'm willing to learn, can you explain me ?

As for the blocking call, if I understand the thing correcty, the bip code would be blocked asking for the string sent by the button module, wich came every seconds, plus a delay time to treat the info (I'm not shure how long it takes for an esp to read a string, I believe it takes time, but I don't know the exact number :confused: ) And so this would cause the random beeping... But with the client.available thing, it quickly looks for the client string and if it doesn't find it, it continues. But does the server stores the client string for a certain time or do they need to be exactly in sync to work ?
but this is certainly the reason of the request.reserve(20), that stock the string maybe ?

Thanks a lot - Merci infiniment

PS: Sorry for the late response, not the same time zone ^^ (see the code :P)

Hi C,
Many thanks for the reply.
Oh believe me I have no more Skill than the next person.
Just quite a lot of free time and little distraction.

I looked over the code I posted and there is much room for improvement,
so don't go thinking you are done.!!

Sorry for the extra unknown stuff in the example.
With little projects that require two versions of similar code I find it easier sometimes to wrap the two halfs in the same projects as many of the strings, commands and structure relate.

Blocking Code.
My take on this is you should never stay in one place for too long without giving some control back to the background code to let it do its house keeping. Stuff like the serial, wifi, timers and other background tasks all need some time to do their thing.

There is also the need to check things have actually started or exist before trying to read or manipulate.

Like Cattle... mentioned if(client.available()){//it exists}
Also calling something that is going to wait for a certain thing to arrive.
Not sure if the readstringuntil has any sort of timeout or if it will just sit there waiting.
But it is always best to ask "does the room have a door" before you try and find a way out.

Things like Delay() & yield()are great as they do some house keeping thru the process,
Using flags and timers to give a delay can be less intrusive than delay() and allow the background tasks a bit of air to do their thing.

bool alreadyhere = false;

void mydelay(int dly){
  unsigned long starttime = millis();
  while (1==1){
    refresh(false);
    if ((millis()-starttime) >= dly){break;}
  }
}

void refresh(bool full){
  yield();
  WIFI_loop();  
  if (alreadyhere){return;}
  alreadyhere = true;

  // perhaps some other loops() that may also use mydelay().
  LCD_loop();  

  alreadyhere = false;
}

void WIFI_loop() {
  C_webSocket.loop();  
  S_webSocket.loop();
  ESP_server.handleClient();
}

You just have to make sure that you do not crash the stack by not using mydelay() in anything that could be called as a result of the refresh() call.
Not sure if that makes sense, or even if it is accepted practice but it works for me.!

And this was the (bad) example of using timers and flags to resist the delay().
If you wanted to only do something once per second.

//unsigned long askTimer;
void loop(){
  
  server.loop();

  if((millis() - askTimer) < 1000){return;}
  askTimer = millis();

  // do something

}

is slightly better than

void loop(){

  server.loop();

  // do something

  delay(1000);
}

Debounce:
Basicly switches can often give multiple high and lows during the process of activation.
It is good practice to read the state of switch inputs for a minimum period of time to establish a positive activation rather than just a glitch.
In your case it is not really needed as you have a long process happening if the button is pressed before you then test if the button is not pressed. so little chance of multiple triggers.

Others will describe that better perhaps.

Oh and a BIG issue is the checking of the alarm time.
It is limited to an exact match lasting for only 1 second.
This could easily be missed if the device was busy elsewhere.
Best to perhaps have a slightly more complex process of detection, timers and flags so you do not miss that appointment.
Perhaps use timeserial rather than the hours:mins:secs.
That will give an easier way to say

if ( (ntp.timeserial >= alarmtime-1000) && (ntp.timeserial <= alarmtime+1000) ){
 if (donealarm == false){
    donealarm = true;
    // Start the alarm process
  }
} else { 
  donealarm = false;
}

Sorry the names (or numbers) may not be right.

Also consider using a softRTC along side your NTP solution, so that you do not need to call the update on every loop perhaps.

You could call the time.update at start once connected and then on the hour or every 30mins perhaps. That update call to the timeserver may be the reason for the slightly odd tones you mention. But to be honest I have not looked at the NTP code so not sure what it gets up to.

Sorry got to dash out, will finish off later

Hello,
I'm so sorry for a respons this late... Tough past 3 days :confused:
But I had time to learn what you shared in your message ! understood (not without trouble :stuck_out_tongue: ) just about everything in the code :slight_smile:

So far I've managed to do make it sync to NTP time every 10min and have a +-10seconds accuracy so the appointment won't be miss.

here is the code so far

//#define BUTTONCODE // Switch this line for different module

int AlarmH = 17;
int AlarmM = 20;
int AlarmS = 30;
int innacuracy = 10 ;
int AccurateS = AlarmS+innacuracy ;
int TimingSync = 0 ;
byte pin_buzzer = 2;
byte pin_button = 2;
char ssid[] = "******";
char pass[] = "¯\_(ツ)_/¯";
unsigned long askTimer = 0;

#include <SPI.h>
#include <ESP8266WiFi.h>
IPAddress serverIP(192,168,0,80);       
WiFiClient socket;


/////////////////////////////
#ifdef BUTTONCODE
/////////////////////////////
void setup() {
  pinMode(pin_button, INPUT_PULLUP);
  Serial.begin(115200);               
  while (!Serial){yield();}
  WiFi.begin(ssid, pass);             
  askTimer = millis();
  while (WiFi.status() != WL_CONNECTED) {
    Serial.print(".");
    delay(100);
  }
  Serial.println();
}
/////////////////////////////
void loop () {
  if((millis() - askTimer) < 1000){return;}
  askTimer = millis();
  socket.connect(serverIP, 80);   
  if (digitalRead(pin_button) == HIGH) {Say_HIGH();}
  if (digitalRead(pin_button) == LOW) {Say_LOW();}
}
/////////////////////////////
void Say_HIGH(){
  Serial.println("HIGH");
  socket.println("He is sleeping\r");
}       
/////////////////////////////
void Say_LOW(){
  Serial.println("LOW");
  socket.println("He is awake\r");
}
/////////////////////////////
/////////////////////////////
#else
/////////////////////////////
/////////////////////////////
const long utcOffsetInSeconds = 7200;
const int buzzint = 500;
unsigned long buzztime = 0;

#include <NTPClient.h>
#include <WiFiUdp.h>
WiFiUDP ntpUDP;
NTPClient timeClient(ntpUDP, "pool.ntp.org", utcOffsetInSeconds);

int Hours = 0;
int Minutes = 0;
int Seconds = 0;
bool pinstate = LOW;
bool alarmactive = false;

WiFiServer server(80);             
/////////////////////////////
void setup() {
  pinMode(pin_buzzer, OUTPUT);
  digitalWrite(pin_buzzer, LOW);
 
  Serial.begin(115200);                   // only for debug
  while (!Serial){yield();}
  WiFi.begin(ssid, pass);                 // connects to the WiFi router
 
  while (WiFi.status() != WL_CONNECTED) {
    Serial.println("c'est connecté");
    delay(1000);
  }
  server.begin();                         // starts the server
}
/////////////////////////////
void loop () {
  UpdateTime();
  if (Hours == AlarmH && Minutes == AlarmM && Seconds == AlarmS) 
  {if ( (Seconds >= AlarmS ) && (Seconds <= AccurateS) ){alarmactive = true;}}
  processAlarm(); 
  WiFiClient client = server.available(); 
  if(!client){return;}
 
  String request = client.readStringUntil('\r');
  if (request == "He is awake") {alarmactive = false;}
 
  //if (request == "He is sleeping"){alarmactive = true;}
  Serial.print("requete client :");   Serial.println(request);
    
}
/////////////////////////////
void UpdateTime(){
  int lastsec = Seconds;
  if ( TimingSync == 600 )  
  { TimingSync = 0; }
  if ( TimingSync == 0 )  
  { timeClient.update(); TimingSync = 0; Serial.println("TimeSynced"); Serial.println("TimeSync+1"); TimingSync++ ; } 
   Hours = timeClient.getHours();
  Minutes = timeClient.getMinutes();
  Seconds = timeClient.getSeconds();
    if (Seconds != lastsec){
    Serial.print(Hours); Serial.print(":"); Serial.print(Minutes); Serial.print(":"); Serial.println(Seconds);TimingSync++ ; Serial.println(TimingSync);} 

  }
/////////////////////////////
void processAlarm(){
  if (!alarmactive){pinstate = LOW; digitalWrite(pin_buzzer, pinstate); return;}  //Serial.println("Bop");   
  if ((millis() - buzztime) > buzzint){
    buzztime = millis();
    pinstate = !pinstate;
    digitalWrite(pin_buzzer, pinstate); //Serial.println("Bip");
  }
}
/////////////////////////////
void MakeNoise(){
  digitalWrite(pin_buzzer, HIGH); Serial.println("Bip");
  delay(buzzint);
  digitalWrite(pin_buzzer, LOW);  Serial.println("Bop");   
  delay(buzzint);
}
/////////////////////////////
#endif
/////////////////////////////

I tested it and it works flawlessly !
But now that I think about it, it could be nice to have a webinterface to change the alarme time ! So this is my next goal for this project !
I'll try to scavange some code from where I can to try and do something functionnal tommorow ^^

If you have any other ideas, I'dd be happy to know :slight_smile:

Thanks !

Have a quick look at the WebSockets example at the bottom of this

https://forum.arduino.cc/index.php?topic=630014.0

Post number #14 if your numbered the same way.

You should be able to cut various parts into your code and give a web interface to play with.
Websocket are nice because the are interactive (sort of like a serial connection).
Either end can shout at the other and can also broadcast to all clients connected.

I will smash something together for the fun of it later but DON'T wait for me,
have a play anyway and see where you go.

On a side note,
I have been playing with some OLED and some older LCD screens on the ESP this week.
So if you are looking to plonk a display on the Alarm then look at:

https://www.ebay.co.uk/itm/0-91-128x32-IIC-I2C-Blue-OLED-LCD-Display-DIY-Module-DC3-3V-5V-For-PIC-Arduino/273951985012

or

https://www.ebay.co.uk/itm/3Color-0-96-I2C-IIC-Serial-128-64-OLED-LCD-LED-Display-Module-Board-for-Arduino/292834086803

links are only given for reference.

Nice displays they only take up two pins.
But a third for reset or power could be handy.
There is no reset pins on the boards but to be honest it has not presented an issue yet.

Very happy with the quality and readability.
Super quick refresh rate, even while taking care of WiFi requests and other things.

The older LCD 128x160 panels run on SPI and need 5 pins,
and on an ESP that is a big portion of the I/O so I2C is better.
Also pretty good display, pretty quick for RGB.
but the OLED displays makes this stuff look OLD even if they are single colour.

Anyway, just thought I would share .

So while playing with my lcd's I thought I could try to mash that Web page together.

Believe me this is starting to look a little messy as I am just lobbing stuff in with little thought.

I have tried to keep the web page basic.

Having it in the esp code is handy but if it gets much bigger your best off running the SPIFFS file system and serving the pages up from proper files that are then easier to edit.

I wont bother to explain anything ! that's the secret of code, you can see exactly what it does !!

I dropped the 10 min counter you had,
Now that I downloaded the library I can see what it does.
The NTP library has an update interval that you can set, then calling the .update() will actually only update once the interval has passed. The .forceUpdate() will ignore the timer if you need it updated NOW.
Anyway, I guess it must be working, it shows the correct time for here.

You will notice that the quickwifi.h file has the define option for ASCLIENT.
Just ignore all the CLIENT stuff, you only need the SERVER side for now.
Down the road you could use the client stuff for your Button perhaps

Sorry this version has an error. Did you find it.?

SEE LATER POST FOR UPDATED VERSION.

Forum_ESP_Button_R.zip (6.71 KB)

Oops.
I put some of the bits in the quickwifi.h file but then forgot to include it with the buttoncode portion.

Also you should remember that NOTHING is saved, so if you change the alarm time and the ESP resets then it will default back to the original time.
You should start to use the EEPROM or SPIFFS to save settings to flash.

If you were to use SPIFFS then you could have a file called alarms.txt.
That would allow you to have multiple alarms and perhaps even allocate different sounds/tones per alarm.
You know that you can play simple tones using the TONE library.?

Once you get spiffs running you should also look into the esp HTTP update at some point,
this will allow you to update the firmware remotely.
THAT WOULD BE HANDY on that esp-01 module, no more unplugging.!
but little steps hey,,,

This version is better.

Ps: Just watch out for my (BAD) habit of no comments and compacting code to single lines.
It is not tradition and I thought I would have been keel hauled by now but if you are going to do similar then best to not hide stuff in the middle of things. remembering your addition of the 600 ticktimer, you had the ++ tucked away in a long line of print time code. I just try to keep it readable so you can see the separate logical sections but still compact enough to save scrolling up and down too much. I am not a big comment lover either, believing that if the variables and functions are given logical names the code should comment itself.! I am not saying I always adopt this process, to be honest my coding methods change daily.

Forum_ESP_Button_R.zip (6.82 KB)

Hello,
Just connected quickly to see if you had any suggestions for a webinterface... but looks like you wrote the whole thing before I could do anything... Do you even sleep :') ? I quickly read through what you posted and the updated code. I'll try to understand everything new by tomorow, last week I was blinking a led with an arduino and now you make me face this kind of code :

void S_webSocketEvent(uint8_t num, WStype_t type, uint8_t * payload, size_t lenght) {
  IPAddress ip(0,0,0,0);
  switch(type) {
  case WStype_DISCONNECTED:
    USE_SERIAL.printf("%u [%u] Disconnected!\n", millis(), num);
    WS_State = WStype_DISCONNECTED;
    if (num == WS_ClientNum){WS_ClientNum = 99;}
    if (num == WS_PCNum){WS_PCNum = 99;}    
    break;
  case WStype_CONNECTED:         
    ip = S_webSocket.remoteIP(num);
    USE_SERIAL.printf("%u [%u] Connected from %d.%d.%d.%d url: %s\n", millis(), num, ip[0], ip[1], ip[2], ip[3], payload);
    // send message to client
    S_webSocket.sendTXT(num, "Connected");  
    WS_State = WStype_CONNECTED;
    break;
  case WStype_TEXT:
    USE_SERIAL.printf("%u [%u] get Text: %s\n", millis(), num, payload);
    if (payload[0] == 'F') {
      WS_ClientNum = num;
      if(PassedData == ""){PassedData = "NONE_F";}
      S_webSocket.sendTXT(num, PassedData);
      if (WS_PCNum != 99){
        String xtopc = String((const char *) &payload[0]);
        xtopc += "\r\n";
        S_webSocket.sendTXT(WS_PCNum, xtopc);

it's hard to keep your pace ! But hey, learn on the job ^^

For the tones I wanted to (try) implement them after the web interface.
But I had no idea it was possible to use an OLED screen with this board... this board can do quite a lot of things !

As for the code, I follow your logic of not commenting everyline, if names are logicall, so is the code ! And also, even if it's harder to read for a noob like me, learning on this code seems to be a good exercise !

I'll try and study the code, I'll report then :slight_smile:

Thank you ! ! !

PS : I didn't know the keen hauled expression, checked it out, it's pretty hardcore, I'll try to make my lines clearer, wouldn't want that to happen :stuck_out_tongue:

Hey C,
Glad I have not scared you off.

Don't worry too much about understanding everything,
Most of it I don't touch thus less to understand.!
But hey you don't have to understand how AIR works to use and manipulate it.

Yes Keelhauling was pretty standard punishment back in the days.
My lack of code discipline must get a few of the hard core coders (respect) screaming.

Yes the ESP is a mighty fine processor.
It just lacks I/O pins but that is where the Arduino boards step up.
Using two interconnect pins** between them gives you plenty of I/O and another processor too.
** REMEMBER TO LEVEL SHIFT YOUR INTERCONNECTS.

Anyway,
a little amplified speaker,
OLED display,
navigation key (wired to A2D with resistor ladder)
or rotary encoder (if you can spare the pins)

One cool clock later....

Yes I do sleep a little, but most of the code so far has just been examples or snippets from existing code so not a lot of effort went in, not as much as I know you are putting in to understand it, so a fair trade.

I'll tidy up my HTTP update stuff a little thru the week so I am ready when you ask.

No seriously I am happy to help, no point in knowing things if I have no outlet for it.

Ok ! Read and understood all the Forum_ESP_Button_R file code... took me a while to understand the modulo operator and the clever way you used it ! A counter that goes back to 0 simply, that's genius !

  if (alarmready == true){
    if ((Theday == AlarmD) || (AlarmD >= 7)  ){
    //This may / will fail when epoc/alarm is at start of week.! We better add more checks
      if (((epoc % 86400L) == (alarmEPOC))){alarmactive = true;}
      if (((epoc % 86400L) >= (alarmEPOC)) && ((epoc % 86400L) <= (alarmEPOC + innacuracy))){alarmactive = true;}
//      if (((epoc % 86400L) >= (alarmEPOC - innacuracy)) && ((epoc % 86400L) <= (alarmEPOC))){alarmactive = true;}
      if (Hours == AlarmH && Minutes == AlarmM && Seconds == AlarmS) {alarmactive = true;}
//    if ( (Seconds >= AlarmS ) && (Seconds <= AccurateS) ){alarmactive = true;}
    }
    if (alarmactive == true){lasttrigger = millis(); alarmready = false;}

I'm not shure but I think this line is not necessary, is there a reason why you kept it ? if (Hours == AlarmH && Minutes == AlarmM && Seconds == AlarmS) {alarmactive = true;}
Thinking it's an extra check, but I don't know where the other one would fail :confused:

Also, I didn't understand why it would fail at the start of a week, can you please explain ?

The rest of the code is pretty straight forward ( I think I'm getting better at this :') ), the only thing I can't understand is with the last 2 functions

void Do_SocketSend(String xtopc){
  if (WS_PCNum != 99){S_webSocket.sendTXT(WS_PCNum, xtopc);}
}
/////////////////////////////
void a2d_read() {
  // read the analog in value
  sensorValue = analogRead(analogInPin);  
  outputValue = map(sensorValue, 0, 1024, 0, 255); 
//  // print the readings in the Serial Monitor
  Serial.print("sensor = "); Serial.print(sensorValue);
  Serial.print(" output = "); Serial.println(outputValue);
}

I think a2d means AnalogInput, but there aren't any (easely accessible) analog pin on the esp01, so what is the a2d_read used for ?
And the other one I believe is related to the quickwifi.h file... wich i can't fully understand, there are a lot of unknown synthaxe to learn in there ! But hey, it's always good to learn new things ^^

Well connecting a esp8266 with an Arduino must be a pretty good combo, tones of IO pins and WIFI, for a next project maybe :slight_smile:

As for putting an amplified speaker, a display that would be the cherry on top of the cake ! But still some way to go until then :slight_smile:

But for the navigation keys, I still don't understand how you can use A2D... mystère et boule de gomme !

I still can't thank you enough for helping me, even if you say it's a fair trade, it's more usefull for me than it is for you... Thank you !

Hi C,

Your asking questions, so you are getting it.
If you weren't you would be back to flashing the LED.

I kept that extra testing the time line cos it made no difference.
You will see that when you update the time from the web interface it will set both the H:M:S variables as well as the epocALARM time.

Re failing at the start of the week.
I guess if the epoc time is close to the 86400 number (1 day).
When we test to see if epoc >= alarm && epoc +2 <= alarm.
If the epocALARM was 86399 then it MAY have failed (not sure).
Feels like it may have.

The A2D_read.
Yep the ESP does have an A2D pin** but is not pinned on the ESP-01 modules.
**REMEMBER THE bare ESP8266 A2D has max input voltage of 1v.
The nodemcu boards, and others perhaps, add two resistors to make it 3.3v tolerant.
I just left the code even though it is not needed right now.

The Socket_send stuff is just the easy call to send data to the webSocket clients.
Yep part of quickwifi.h

Using a 5way navigation button will normally take up 5 pins.
However if you choose the right resistors for each button contact and use the single A2D input you can read what button was pressed by the voltage it creates on the pin.
Sorry that is a terrible description.
Oh, here we go Ignorant of Things: The perfect multi-button input resistor ladder