Project in progress
Serial Timer

Serial Timer

Timer for Arduino pins controlled by Serial monitor

  • 314 views
  • 0 comments
  • 1 respect

Components and supplies

Apps and online services

About this project

This project is to demonstrate how to create timer outputs

#include "SerialTimer.h"

//* Objects

Timer clock1(3);

Timer clock2(4);

Timer clock3(13);

First add the library and define our objects (outputs)

void timer_switch(int isPin, float Time, bool serial_on_off, int mode) //Funcion para los multiples timers
{                                                                      //los casos son a necesidad del usuario
 unsigned long past = millis();
 switch (mode)
 {
 case 0:
   Serial.println("\nThe timer has started");
   switch (isPin) // Aqui puedes agregar los casos que necesites
   {
   case 1:
     clock1.set_timer(Time, past);//asignacion de tiempo
     break;
   case 2:
     clock2.set_timer(Time, past);
     break;
   case 3:
     clock3.set_timer(Time, past);
     break;
   default:
     Serial.println("Error");
   }
   break;
 case 1:
   switch (isPin) // aqui tambien debes añadir el numero de casos necesarios
   {
   case 1:
     clock1.switch_pin(serial_on_off);//cambio de estado
     Serial.println(clock1.get_pin());//lectura de estado
     break;
   case 2:
     clock2.switch_pin(serial_on_off);
     Serial.println(clock2.get_pin());
     break;
   case 3:
     clock3.switch_pin(serial_on_off);
     Serial.println(clock3.get_pin());
     break;
   default:
     Serial.println("Error");
     break;
   }
   break;
 default:
   Serial.println("Error");
 }

If you need to use more than 3 outputs you should edit this part and add them as cases

void setup()
{  
    Serial.begin(9600); 
    menu();
}

It's very important initialize the Serial and add the menu function

void loop()
{ 
    rx_menu(3); //mainn menu
    clock1.get_valor(); // read if the time is complete  
    clock2.get_valor();  
    clock3.get_valor();
}

In the loop, you only need to declare the function "rx_menu" and "get_valor" for each object's timer to run

You can use an HC05 or other Bluetooth module and use the "Serial Bluetooth" application to send commands

Code

main.inoC/C++
#include <string.h>
#include "SerialTimer.h"
//* Objects
Timer clock1(3);
Timer clock2(4);
Timer clock3(13);

/* -------------------------------- variables ------------------------------- */
String SerialData = "";
/* -------------------------------------------------------------------------- */

/* -------------------------------- funciones ------------------------------- */
void menu(void);
void rx_menu(int n_timers);
void _n_timers(int __n);
void timer_switch(int isPin, float Time, bool serial_on_off, int mode);
int pin_select(void);
float Read_time(void);
String serialText(void);
/* -------------------------------------------------------------------------- */

void setup()
{
  Serial.begin(9600);
  menu();
}

void loop()
{
  rx_menu(3); // menu to configure  timers and configure how many timers there are

  clock1.get_valor(); // read if the time is complete
  clock2.get_valor();
  clock3.get_valor();
}
/* ---------------------Funciones--------------------- */
void timer_switch(int isPin, float Time, bool serial_on_off, int mode) //Funcion para los multiples timers
{                                                                      //los casos son a necesidad del usuario
  unsigned long past = millis();
  switch (mode)
  {
  case 0:
    Serial.println("\nThe timer has started");
    switch (isPin) // Aqui puedes agregar los casos que necesites
    {
    case 1:
      clock1.set_timer(Time, past);
      break;
    case 2:
      clock2.set_timer(Time, past);
      break;
    case 3:
      clock3.set_timer(Time, past);
      break;
    default:
      Serial.println("Error");
    }
    break;
  case 1:
    switch (isPin) // aqui tambien debes añadir el numero de casos necesarios
    {
    case 1:
      clock1.switch_pin(serial_on_off);
      Serial.println(clock1.get_pin());
      break;
    case 2:
      clock2.switch_pin(serial_on_off);
      Serial.println(clock2.get_pin());
      break;
    case 3:
      clock3.switch_pin(serial_on_off);
      Serial.println(clock3.get_pin());
      break;
    default:
      Serial.println("Error");
      break;
    }
    break;
  default:
    Serial.println("Error");
  }
}
/* -------------------------------------------------------------------------- */
void menu(void)
{
  Serial.println("------------Timer-------------\n");
  Serial.println("1.Set Time\n2.ON_OFF Output\n");
  Serial.println("-------------------------------\n");
}

String serialText(void) // Funcion para poder obtener los datos ingresados
{
  char charData;
  if (Serial.available() > 0)
  {
    charData = (char)Serial.read();
    SerialData += charData;
  }
  if (charData == '\n')
  {
    return SerialData;
  }
  return "";
}

float Read_time(void) // Funcion que convierte los datos de String a Float
{
  float time_out = 0;
  String time_text = serialText();
  if (time_text != "")
  {
    SerialData = "";
    time_out = time_text.toFloat();
    Serial.println("Time: ");
    Serial.print(time_out);
    Serial.print(" minutes\n");
    time_text = "";
  }
  return time_out;
}

int pin_select(void) // Funcion que convierte los datos de String a Int
{
  int pin_out = 100;
  String pin_text = serialText();
  if (pin_text != "")
  {
    SerialData = "";
    pin_out = pin_text.toInt();
    if (pin_out > 0)
    {
      Serial.println("Selected timer: ");

      Serial.print(pin_out);
    }
    pin_text = "";
  }
  return pin_out;
}

void _n_timers(int __n) //Funcion para imprimir
{                       //el numero de objetos
  for (int z = 1; z <= __n; z++)
  {
    Serial.print(z);
    Serial.print(".Timer ");
    Serial.print(z);
    Serial.println("");
  }
}

/* -------------------------------------------------------------------------- */

void rx_menu(int n_timers) // Menu de control por Serial
{
  int isPin;
  float Time;
  int serial_on_off;
  char _command;
  bool flag = false;

  if (Serial.available() > 0) // si el serial esta disponible
  {
    _command = (char)Serial.read(); // guarda el caracter en _command
    flag = true;                    // Pon en true la flag
  }
  if (flag == true) // si esta es true activa el menu
  {
    flag = false;     // para prevnir futuros bucles pasa a falso
    switch (_command) // si el caracter tiene algun sub-menu
    {
    case '1': // Seleccion para asignar timer
      Serial.println("Select a timer");
      _n_timers(n_timers);
      while (true)
      {
        isPin = pin_select();
        if (isPin > 0 && isPin != 100) //Hasta que el valor de  isPin
        {                              //sea correcto terminara el bucle infinito
          break;
        }
      }
      Serial.println("\nEnter time:"); //Asignacion de tiempo al timer seleccionado
      while (true)
      {
        Time = Read_time();
        if (Time > 0.0) // Hasta que sea un valor  valido terminara el bucle infinito
        {
          timer_switch(isPin, Time, 0, 0); // Los datos son asignados
          menu();
          break;
        }
      }
      break;
    case '2': // Cambiar el estado de una salida
      Serial.println("Select a timer");
      _n_timers(n_timers);
      while (true)
      {
        isPin = pin_select();         //Hasta que el valor sea valido terminara
        if (isPin > 0 && isPin < 100) // el bucle infinito
        {
          break;
        }
      }
      Serial.println("\n0.OFF\n1.ON");
      while (true)
      {
        serial_on_off = pin_select();
        if (serial_on_off == 0 || serial_on_off == 1) //Si los valores son validos
        {
          Serial.println("\nOutput is on: ");
          timer_switch(isPin, Time, serial_on_off, 1); //Se asignan los valores
          menu();                                      // y termina el bucle infinito
          break;
        }

      }

      break;
    }
  }
}
SerialTimer.hC/C++
/* -------------------------------------------------------------------------- */
/*                                Serial Timer                                */
/* -------------------------------------------------------------------------- */
/*
Libreria para poder crear un temporizador apartir de la funcion millis
el tiempo a poner esta en float por lo tanto puedes poner 0.5 lo  que equivale a 
30 segundos.

 tiempo * 60s/1m

 ejemplo 
  
 1.5min * 60s/1min = 90s 

*/
#ifndef SeriaTimer_h
#define SerialTimer_h
#include <Arduino.h>

/* ---------------------------------- Clase --------------------------------- */

class Timer
{
public:
    Timer(int);
    void set_timer(float, unsigned long);
    void start_timer(void);
    bool get_valor(void);
    void switch_pin(bool);
    bool get_pin(void);
    float timer_register(void);

private:
    double isTime;
    unsigned long _current, _past;
    float Time;
    int pin;
    bool on_off = false;
};

#endif
SerialTimer.cppC/C++
#include <Arduino.h>
#include "SerialTimer.h"
/* -------------------------- Funciones de la clase ------------------------- */

Timer::Timer(int _pin)
{
    pin = _pin;
    pinMode(pin, OUTPUT);
}

void Timer::start_timer(void)
{
    if ((_current - _past >= isTime) && isTime > 0)
    {
        Serial.println("Time finished");
        digitalWrite(pin, !digitalRead(pin));
        on_off = true;
        isTime = 0;
    }
}

float Timer::timer_register()
{
    return isTime / 60000;
}

void Timer::set_timer(float time, unsigned long isPast)
{
    isTime = time * 60000;
    _past = isPast;
}

bool Timer::get_valor(void)
{
    on_off = false;
    _current = millis();
    start_timer();
    if (on_off == true)
    {
        return true;
    }
    else
    {
        return false;
    }
}

void Timer::switch_pin(bool estado)
{
    digitalWrite(pin, estado);
}

bool Timer::get_pin(void)
{
    bool _status;
    _status = digitalRead(pin);
    return _status;
}
SerialTimer.zipC/C++
No preview (download only).

Schematics

Circuit
Circuit ygldozmyhs
circuit_YyUUv66KRH.jpg
Circuit yyuuv66krh

Comments

Similar projects you might like

Custom Timer Functions on Arduino Nano

Project tutorial by Arduino “having11” Guy

  • 1,966 views
  • 0 comments
  • 9 respects

Wake Up Timer

Project showcase by Fatih Çil

  • 820 views
  • 0 comments
  • 7 respects

Morse Code Kitchen Timer

Project showcase by oklima

  • 2,249 views
  • 0 comments
  • 9 respects

Arduino Countdown Timer

Project tutorial by xXarduino_11Xx

  • 16,639 views
  • 1 comment
  • 12 respects

Retro 1980s LED Clock/Count Up Timer

Project in progress by randtekk

  • 5,371 views
  • 5 comments
  • 18 respects

Retro View Timer

Project tutorial by yilmazyurdakul

  • 1,570 views
  • 2 comments
  • 3 respects
Add projectSign up / Login