Time alarms

Hola, perdon por reflotar el tema, pero dado que surbyte es un moderador me animo a preguntar.

En el codigo propuesto:

#include <Time.h>
#include <TimeAlarms.h>


AlarmID_t alarmaUA1Onn;
AlarmID_t alarmaUA1Off;

int hora = 7, minuto = 31;
int horaApagado = 7, minutoApagado = 32;
bool fseg = false, fminuto = false;

void setup() {
  Serial.begin(9600);
  Serial.println("Hora fijada a las 7:29:40am 2/6/2018 que fue sabado");
  Serial.println("Presionar y para cambioAlarmas()");
  Serial.println("Presionar s mostrar la hora segundo a segundo.");
  Serial.println("Presionar m para mostrar la hora cuando cambian los minutos.");
  Serial.println("Los dias van de Domingo = 0 a Sabado = 7");
  Serial.println();
  setTime(7,29,40,2,6,18); // set time to 7:29:40am 2/6/2018
  cambioAlarmas();
}


void loop() {

  if (Serial.available()) {
     char str = Serial.read();
     switch (str) {
       case 'y': cambioAlarmas();
                 break;
       case 's':  fseg = !fseg;
                  break;
       case 'm':  fminuto = !fminuto;
                  break;
     }
  }

  digitalClockDisplay();
  Alarm.delay(0); // sin esto no funciona nada
                  // he puesto 1 milisegundo para que puedas
                  // ver como evoluciona dia a dia en poco tiempo
                  // luego lo pones en 1000
}

void cambioAlarmas() {
  char buffer[30];

   
    Alarm.disable(alarmaUA1Onn);
    Alarm.free(alarmaUA1Onn);
    Alarm.disable(alarmaUA1Off);
    Alarm.free(alarmaUA1Off);
   
    Serial.println("Configuro alarma");
    alarmaUA1Onn  = Alarm.alarmOnce(dowSaturday,       hora,       minuto,  0, enciendeReleA1);
    sprintf(buffer, "ON : %02d:%02d:%02d Dia:%d", hora, minuto, 0, dowSaturday);
    Serial.println(buffer);
    if (minuto++> 59){
        minuto = 0;
        if (hora++>23) {
            hora = 0;
            minuto = 0;
        }
         
    }   
    alarmaUA1Off  = Alarm.alarmOnce(dowSaturday,horaApagado,minutoApagado,  0, apagaReleA1);
    sprintf(buffer, "OFF: %02d:%02d:%02d Dia:%d", horaApagado, minutoApagado, 0, dowSaturday);
    Serial.println(buffer);
 
    if (minutoApagado++> 59){
        minutoApagado = 0;
        if (horaApagado++>23) {
            horaApagado = 0;
            minutoApagado = 0;
        }
    }
}

void enciendeReleA1() {
  digitalClockDisplay();
  Serial.println("Enciendo Rele A1");
}

void apagaReleA1() {
  digitalClockDisplay();
  Serial.println("Apago Rele A1");
}

void digitalClockDisplay(){
  static int secondAnt = 0;
  static int minuteAnt = 0;
  char buffer[10];

  if (fseg)
      if (second() != secondAnt){
          sprintf(buffer, "%02d:%02d:%02d", hour(), minute(), second());
           Serial.println(buffer);
           secondAnt = second();
      }
  if (fminuto)
      if (minute() != minuteAnt){
          sprintf(buffer, "%02d:%02d:%02d", hour(), minute(), second());
           Serial.println(buffer);
           minuteAnt = minute();
      }
}

donde se indica que día se activa la alarma?, o como se indica.

Por ejemplo si quisiera que se active todos los lunes y viernes.

Saludos

@kapotik hola, bienvenido al foro.
Justamente porque soy el moderador, es que te pido no reflotes hilos viejos.
Ademas el hilo preguntaba por dia de semana y tu preguntas por algo que el mismo ejemplo de la librería hace.
Asi que siempre, siempre crea tu propio hilo con tu consulta cuando el hilo viejo tenga mas de 4 meses sin movimientos.

Bueno esta es la librería TimeAlarms

Y este es su ejemplo

#include <TimeLib.h>
#include <TimeAlarms.h>

AlarmId id;

void setup() {
  Serial.begin(9600);
  while (!Serial) ; // wait for Arduino Serial Monitor

  setTime(8,29,0,1,1,11); // set time to Saturday 8:29:00am Jan 1 2011

  // create the alarms, to trigger at specific times
  Alarm.alarmRepeat(8,30,0, MorningAlarm);  // 8:30am every day
  Alarm.alarmRepeat(17,45,0,EveningAlarm);  // 5:45pm every day
  Alarm.alarmRepeat(dowSaturday,8,30,30,WeeklyAlarm);  // 8:30:30 every Saturday

  // create timers, to trigger relative to when they're created
  Alarm.timerRepeat(15, Repeats);           // timer for every 15 seconds
  id = Alarm.timerRepeat(2, Repeats2);      // timer for every 2 seconds
  Alarm.timerOnce(10, OnceOnly);            // called once after 10 seconds
}

void loop() {
  digitalClockDisplay();
  Alarm.delay(1000); // wait one second between clock display
}

// functions to be called when an alarm triggers:
void MorningAlarm() {
  Serial.println("Alarm: - turn lights off");
}

void EveningAlarm() {
  Serial.println("Alarm: - turn lights on");
}

void WeeklyAlarm() {
  Serial.println("Alarm: - its Monday Morning");
}

void ExplicitAlarm() {
  Serial.println("Alarm: - this triggers only at the given date and time");
}

void Repeats() {
  Serial.println("15 second timer");
}

void Repeats2() {
  Serial.println("2 second timer");
}

void OnceOnly() {
  Serial.println("This timer only triggers once, stop the 2 second timer");
  // use Alarm.free() to disable a timer and recycle its memory.
  Alarm.free(id);
  // optional, but safest to "forget" the ID after memory recycled
  id = dtINVALID_ALARM_ID;
  // you can also use Alarm.disable() to turn the timer off, but keep
  // it in memory, to turn back on later with Alarm.enable().
}

void digitalClockDisplay() {
  // digital clock display of the time
  Serial.print(hour());
  printDigits(minute());
  printDigits(second());
  Serial.println();
}

void printDigits(int digits) {
  Serial.print(":");
  if (digits < 10)
    Serial.print('0');
  Serial.print(digits);
}

Acá esta todo lo que puede hacer.

  Alarm.alarmRepeat(8,30,0, MorningAlarm);  // 8:30am every day
  Alarm.alarmRepeat(17,45,0,EveningAlarm);  // 5:45pm every day

estas son dos alarmas repetitivas dia a dia de Lunes a Domingo que se activan en ESE momento.
Son eventos y no se repiten asi que lo que hagas dependen de lo que pongas por ejemplo en MorningAlarm y en EveningAlarm

Si quieres que algo empiece y termina con la segunda Alarma entonces usas un flag.

El código propuesto es mas complejo, porque genera alarmas que van cambiando por necesidad del programa. En este caso jazpiroz necesitaba via SMS crear eventos de alarmas como los indicados.
El preguntaba puntualmente por alarmas semanales pero puedes usar todo para alarmas del tipo que acabo de señalarte.

Si no he respondido, reformula tu pregunta.

Gracias por responder, no logro entender algunas cosas de la libreria, por ejemplo donde se declara este evento:

void ExplicitAlarm(){
  Serial.println("Alarma: se activa solo en la fecha y hora indicadas");       
}

solo veo estos tres eventos declarados:

Alarma . alarmRepeat (8,30,0, MorningAlarm);  // 8:30 am todos los días 
  Alarma . alarmRepeat (17,45,0, EveningAlarm);  // 5:45 pm todos los días 
  Alarma . alarmRepeat (dow Saturday, 8,30,30, WeeklyAlarm);  // 8:30:30 todos los sábados

por que yo pensaba que era

Alarma . alarmRepeat (dow Saturday, 8,30,30, WeeklyAlarm);  // 8:30:30 todos los sábados

pero esa corresponde a

void WeeklyAlarm(){
  Serial.println("Alarm: - its Monday Morning");      
}

Me respondo a mi mismo, primero quiero aclarar que llevo muy poquitos días con arduino, entonces por ahí hay cosas obvias para otros, pero para mi todo un mundo jejejejeje.

Bien ya entendí como funciona la librería, ExplicitAlarm, es solo un nombre, podría haber sido cualquiera como NestorAlarm, solo que en el ejemplo no esta a lo que yo le digo "declarado", tal vez se diga de otra manera.

Bueno les explico que quiero hacer, la idea es programar una alarma determinado día y que me envié un mensaje por telegram, para eso estoy usando la librería Cbot.h, la cual puedo mandar mensajes usando el siguiente código:

#include "CTBot.h"

#define LIGHT_ON_CALLBACK  "lightON"  // callback data sent when "LIGHT ON" button is pressed
#define LIGHT_OFF_CALLBACK "lightOFF" // callback data sent when "LIGHT OFF" button is pressed

CTBot myBot;
CTBotInlineKeyboard myKbd;  // custom inline keyboard object helper

String ssid = "kapotik";                                           // REPLACE mySSID WITH YOUR WIFI SSID
String pass = "Florencia36";                                       // REPLACE myPassword YOUR WIFI PASSWORD, IF ANY
String token = "940672949:AAF5pljdZUJV16mpLum3mOugD1FHgQlWzjE";    // REPLACE myToken WITH YOUR TELEGRAM BOT TOKEN
uint8_t led = 2;                                                   // the onboard ESP8266 LED.    
                           

void setup() {
  // initialize the Serial
  Serial.begin(115200);
  Serial.println("Starting TelegramBot...");

  // connect the ESP8266 to the desired access point
  myBot.wifiConnect(ssid, pass);

  // set the telegram bot token
  myBot.setTelegramToken(token);

  // check if all things are ok
  if (myBot.testConnection())
    Serial.println("\ntestConnection OK");
  else
    Serial.println("\ntestConnection NOK");

  // set the pin connected to the LED to act as output pin
  pinMode(led, OUTPUT);
  digitalWrite(led, HIGH); // turn off the led (inverted logic!)

  // inline keyboard customization
  // add a query button to the first row of the inline keyboard
  myKbd.addButton("LED ON", LIGHT_ON_CALLBACK, CTBotKeyboardButtonQuery);
  // add another query button to the first row of the inline keyboard
  myKbd.addButton("LED OFF", LIGHT_OFF_CALLBACK, CTBotKeyboardButtonQuery);
  // add a new empty button row
  myKbd.addRow();
  // add a URL button to the second row of the inline keyboard
  myKbd.addButton("VER DOCUMENTACION", "https://www.ltech.com.ar/AUTOMATIZACIONES/", CTBotKeyboardButtonURL);
}

void loop() {
  // a variable to store telegram message data
  TBMessage msg;

  // if there is an incoming message...
  if (myBot.getNewMessage(msg)) {
    // check what kind of message I received
    if (msg.messageType == CTBotMessageText) {
      // received a text message
      if (msg.text.equalsIgnoreCase("VER TECLADO")) {
        // the user is asking to show the inline keyboard --> show it
        myBot.sendMessage(msg.sender.id, "TECLADO EN LINEA", myKbd);
      }
      else {
        // the user write anithing else --> show a hint message
        myBot.sendMessage(msg.sender.id, "INGRESE 'VER TECLADO'");
      }
    } else if (msg.messageType == CTBotMessageQuery) {
      // received a callback query message
      if (msg.callbackQueryData.equals(LIGHT_ON_CALLBACK)) {
        // pushed "LIGHT ON" button...
        digitalWrite(led, LOW); // ...turn on the LED (inverted logic!)
        // terminate the callback with an alert message
        myBot.endQuery(msg.callbackQueryID, "Led Encendido", true);
      } else if (msg.callbackQueryData.equals(LIGHT_OFF_CALLBACK)) {
        // pushed "LIGHT OFF" button...
        digitalWrite(led, HIGH); // ...turn off the LED (inverted logic!)
        // terminate the callback with a popup message
        myBot.endQuery(msg.callbackQueryID, "Led Apagado");
      }
    }
  }
  // wait 500 milliseconds
  delay(500);
}

pero cuando la quiero fusionar con la de los tiempos no me anda el envió del mensaje cuando se produce el evento del tiempo

void ExplicitAlarm(){
  Serial.println("Limpiar equipo: -Viernes");
   myBot.sendMessage(msg.sender.id, "INGRESE 'VER TECLADO'");
}

este es el código completo, aclaro que las demás funciones con telegram me andan, la única que no, es enviarme el mensaje cuando llega a la fecha programada

#include <Time.h>
#include <TimeAlarms.h>
#include "CTBot.h"

#define LIGHT_ON_CALLBACK  "lightON"  // callback data sent when "LIGHT ON" button is pressed
#define LIGHT_OFF_CALLBACK "lightOFF" // callback data sent when "LIGHT OFF" button is pressed

CTBot myBot;
CTBotInlineKeyboard myKbd;  // custom inline keyboard object helper
TBMessage msg;

String ssid = "kapotik";                                           // REPLACE mySSID WITH YOUR WIFI SSID
String pass = "Florencia36";                                       // REPLACE myPassword YOUR WIFI PASSWORD, IF ANY
String token = "940672949:AAF5pljdZUJV16mpLum3mOugD1FHgQlWzjE";    // REPLACE myToken WITH YOUR TELEGRAM BOT TOKEN
uint8_t led = 2;                                                   // the onboard ESP8266 LED.    

void setup()
{
  Serial.begin(9600);
  Serial.println("Starting TelegramBot...");

  // connect the ESP8266 to the desired access point
  myBot.wifiConnect(ssid, pass);

  // set the telegram bot token
  myBot.setTelegramToken(token);

  // check if all things are ok
  if (myBot.testConnection())
    Serial.println("\ntestConnection OK");
  else
    Serial.println("\ntestConnection NOK");

  // set the pin connected to the LED to act as output pin
  pinMode(led, OUTPUT);
  digitalWrite(led, HIGH); // turn off the led (inverted logic!)

  // inline keyboard customization
  // add a query button to the first row of the inline keyboard
  myKbd.addButton("LED ON", LIGHT_ON_CALLBACK, CTBotKeyboardButtonQuery);
  // add another query button to the first row of the inline keyboard
  myKbd.addButton("LED OFF", LIGHT_OFF_CALLBACK, CTBotKeyboardButtonQuery);
  // add a new empty button row
  myKbd.addRow();
  // add a URL button to the second row of the inline keyboard
  myKbd.addButton("VER DOCUMENTACION", "https://www.ltech.com.ar/AUTOMATIZACIONES/", CTBotKeyboardButtonURL);
  
  setTime(23,00,0,1,1,11); // establecer el tiempo a sábado 08:29:00 es enero 1 2011
  // create the alarms 

  //seteo dias de aviso
  Alarm.alarmRepeat(dowMonday,10,0,0,WeeklyAlarm);  // 10 AM todos los lunes 
 // Alarm.alarmRepeat(dowFriday,9,15,0,ExplicitAlarm); // 10 AM todos los viernes 
  Alarm.alarmRepeat(dowSaturday,23,0,30,ExplicitAlarm); // 10 AM todos los viernes
  
 // Alarm.timerRepeat(15, Repeats);            // temporizador por cada 15 seconds    
 // Alarm.timerOnce(10, OnceOnly);             // llamado una vez después de 10 seconds 
}

void  loop(){  
  digitalClockDisplay();
  Alarm.delay(1200); // espera un segundo entre la visualización del reloj

  // a variable to store telegram message data
  //TBMessage msg;

  // if there is an incoming message...
  if (myBot.getNewMessage(msg)) {
    // check what kind of message I received
    if (msg.messageType == CTBotMessageText) {
      // received a text message
      if (msg.text.equalsIgnoreCase("VER TECLADO")) {
        // the user is asking to show the inline keyboard --> show it
        myBot.sendMessage(msg.sender.id, "TECLADO EN LINEA", myKbd);
      }
      else {
        // the user write anithing else --> show a hint message
        myBot.sendMessage(msg.sender.id, "INGRESE 'VER TECLADO'");
      }
    } else if (msg.messageType == CTBotMessageQuery) {
      // received a callback query message
      if (msg.callbackQueryData.equals(LIGHT_ON_CALLBACK)) {
        // pushed "LIGHT ON" button...
        digitalWrite(led, LOW); // ...turn on the LED (inverted logic!)
        // terminate the callback with an alert message
        myBot.endQuery(msg.callbackQueryID, "Led Encendido", true);
      } else if (msg.callbackQueryData.equals(LIGHT_OFF_CALLBACK)) {
        // pushed "LIGHT OFF" button...
        digitalWrite(led, HIGH); // ...turn off the LED (inverted logic!)
        // terminate the callback with a popup message
        myBot.endQuery(msg.callbackQueryID, "Led Apagado");
      }
    }
  }
  // wait 500 milliseconds
  

  
}




// funciones a las que se llamará cuando se active una alarma:

void WeeklyAlarm(){
  Serial.println("Limpiar equipo: - Lunes");      
}

void ExplicitAlarm(){
  Serial.println("Limpiar equipo: -Viernes");
   myBot.sendMessage(msg.sender.id, "INGRESE 'VER TECLADO'");
}



void digitalClockDisplay()
{
  // visualización del reloj digital de la hora en
  Serial.print(hour());
  printDigits(minute());
  printDigits(second());
  Serial.println(); 
}

void printDigits(int digits)
{
  Serial.print(":");
  if(digits < 10)
    Serial.print('0');
  Serial.print(digits);
}

espero puedan tirarme una manito
saludos

Ponle tiempo kapotik, sino no haras honor a tu nick!! jaja

Bueno prueba primero dominando los eventos. Los eventos los llamas como quieras, de eso ya te diste cuenta.

void WeeklyAlarm(){
  Serial.println("Limpiar equipo: - Lunes");      
}

void ExplicitAlarm(){
  Serial.println("Limpiar equipo: -Viernes");
   myBot.sendMessage(msg.sender.id, "INGRESE 'VER TECLADO'");
}

Estos sos tus eventos, el primero no envia nada.
El segundo si o sea lo hará el sabado 23:00:30

Eso dices que no ocurre?

Hola, si el evento programado en dia y horario si se ejecuta perfectamente, lo que no hace es enviar el mensaje, osea esta linea no funciona

myBot.sendMessage(msg.sender.id, "INGRESE 'VER TECLADO'");

Estoy seguro de que estoy algo mas le falta para que lo envie

Mira la memoria utilizada, no se sea cosa que te estes quedando sin RAM en algún momento y eso evite que el msg llegue.

Otra recomendación es que no uses TimeAlarm y en cambio leas hora minuto segundo de tu RTC y conviertas a un entero con el que consultes entre que puntos del dia te encuentras.

Todo RTC tiene comandos para la lectura de hora, minuto
Si armas una variable como tiempo tal que

Puedes definir entonces horaSemanaInicio, horaSemanaFin del mismo modo pero con valores fijos
10,0,0

unsigned long tiempoSemana, horaSemanaInicio, horaSemanaFin;
tiempoSemana = diaSemana*1440+hora*60+minutos; // donde hora tiene el valor leido del RTC al igual que minutos

Lo que debes hacer entonces es comparar

if (tiempoSemana == horaSemanaInicio && flag) // flag será el que controle que una vez enviado no se repita la acción

Esto disparará la acción de enviar el msg por CTBot

el resto es un poco de trabajo.

Luego pulo un poco mas la idea.

Hola, no tengo un RTC, todavía esta pendiente su compra.

solucion al envio de mensajes

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