Welcome to Hackster!
Hackster is a community dedicated to learning hardware, from beginner to pro. Join us, it's free!
Hackster is hosting Impact Spotlights: Motorized movement. Watch the stream live on Thursday!Hackster is hosting Impact Spotlights: Motorized movement. Stream on Thursday!
scardeath0101
Published

Serial Timer

Timer for Arduino pins controlled by Serial monitor

IntermediateWork in progress3,686
Serial Timer

Things used in this project

Hardware components

Arduino Nano R3
Arduino Nano R3
×1
Relay Module (Generic)
×1
HC-05 Bluetooth Module
HC-05 Bluetooth Module
×1

Software apps and online services

Arduino IDE
Arduino IDE

Story

Read more

Schematics

Circuit

circuit_YyUUv66KRH.jpg

Code

main.ino

C/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.h

C/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.cpp

C/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.zip

C/C++
No preview (download only).

Credits

scardeath0101
2 projects • 1 follower
Contact

Comments

Please log in or sign up to comment.