Preciso que esse código funcione a função timer.
ligar e desligar a luz com toques rápidos com um só botão. (já está funcionando).
A função timer deve funcionar quando o botão for pressionado por 2 segundos, isso ativara um a luz e depois de 5 horas apagar automaticamente,
Aqui esta o código.
#define pinModuloLED 4
#define pinBotaoStart 2
#define tempoReset 2000 //define o tempo em que o botao Start deve ficar apertado para efetuar o reset (em milisegundos)
#define tempoContador 30 //define o tempo do contador (em segundos)
//FUNCOES
byte pinBotaoStartApertado();
int tempo = tempoContador;
int contador = 0;
byte contadorStatus = 0; //0=Pause, 1=Run
unsigned tempoTimer = 0;
void setup() {
pinMode(pinModuloLED, OUTPUT);
pinMode(pinBotaoStart, INPUT_PULLUP);
}
void loop(){
byte estadoBotaoStart = pinBotaoStartApertado();
if ( estadoBotaoStart == 1 ) {
if (tempo > 0) {
if (contadorStatus == 0) {
if (contador == 0) {
contador = tempo;
}
//Acende a barra de led
digitalWrite(pinModuloLED, HIGH);
contadorStatus = 1;
} else {
digitalWrite(pinModuloLED, LOW);
contadorStatus = 0;
}
}
}
if ( estadoBotaoStart == 2 ) {
tempoTimer = millis();
digitalWrite(pinModuloLED, HIGH);
if (tempo > 0) {
digitalWrite(pinModuloLED, HIGH);
contador = 0;
}else{
millis() - tempoTimer >= 4000;
digitalWrite( pinModuloLED, LOW); //Apaga o modulo led
}
}
}
byte pinBotaoStartApertado() {
#define tempoDebounce 50 //(tempo para eliminar o efeito Bounce EM MILISEGUNDOS)
static bool estadoBotaoAnt;
static unsigned long delayBotao = 0;
static unsigned long botaoApertado;
static byte fase = 0;
bool estadoBotao;
byte estadoRet;
estadoRet = 0;
if ( (millis() - delayBotao) > tempoDebounce ) {
estadoBotao = digitalRead(pinBotaoStart);
if ( !estadoBotao && (estadoBotao != estadoBotaoAnt) ) {
delayBotao = millis();
botaoApertado = millis();
fase = 1;
}
if ( (fase == 1) && ((millis() - botaoApertado) > tempoReset) ) {
fase = 0;
estadoRet = 2;
}
if ( estadoBotao && (estadoBotao != estadoBotaoAnt) ) {
delayBotao = millis();
if ( fase == 1 ) {
estadoRet = 1;
}
fase = 0;
}
```
digite ou cole o código aqui
Essa função para fazer o debounce dos botões, pinBotaoStartApertado(), não parece funcionar correctamente, ou então sou eu que a não compreendo. Usando essa função consegues acender e apagar a luz pressionando o botão com um toque rápido??
Em relação à lógica que tens no loop(), não a consigo compreender... Há muitas maneiras de programar para atingir o mesmo objectivo. Fiz outro código no loop() para verificar se o botão é premido durante mais de dois segundos para depois manter a luz ligada durante as 5 horas. Coloquei as constantes em letra maiúscula para as não confundir com variáveis.
Vê se funciona e se consegues compreender o código:
#define PINMODULOLED 4
#define PINBOTAOSTART 2
#define TEMPODEBOUNCE 50 //(tempo para eliminar o efeito Bounce EM MILISEGUNDOS)
#define TEMPOBOTAOPRES 2000 // Button long press time in ms.
#define TEMPOLUZON 18000000 // Light ON time in ms (when button long press detected).
unsigned long buttonTimePrev = 0;
unsigned long ledTimerOn = 0;
int ledState = LOW;
int ledStatePrev = LOW;
//FUNCOES
int verificaBotao();
void setup() {
pinMode(PINMODULOLED, OUTPUT);
pinMode(PINBOTAOSTART, INPUT_PULLUP);
// Mantem a luz apagada ao iniciar.
digitalWrite(PINMODULOLED, LOW);
}
void loop() {
int estadoBotaoStart = verificaBotao();
// Verifica se o botao esta a ser pressionado.
if ( estadoBotaoStart == HIGH ) {
// Verifica se o estado da luz ainda nao trocou.
if ( ledState == ledStatePrev ) {
ledState = !ledState; // Troca.
digitalWrite(PINMODULOLED, ledState);
buttonTimePrev = millis(); // Inicializa tempo de botao premido.
}
// Verifica se botao e' premido mais de 2 s.
if ( (millis() - buttonTimePrev) > TEMPOBOTAOPRES ) {
ledTimerOn = millis(); // Inicia temporizador de luz ligada.
ledState = HIGH; // Ajusta variaveis de controlo para luz ligada.
ledStatePrev = LOW;
digitalWrite(PINMODULOLED, ledState); // Liga a luz.
} else {
// Se o botao no e' premido mais de 2 s limpa o temporizador de luz ligada.
ledTimerOn = 0;
}
} else { // Botao nao pressionado.
if ( ledStatePrev != ledState ) {
ledStatePrev = ledState;
}
}
// Se o temporizador de luz ligada esta activo entao verifica se
// ja passaram as 5 horas para apagar a luz.
if ( ledTimerOn && ((millis() - ledTimerOn) > TEMPOLUZON) ) {
ledTimerOn = 0; // Limpa o temporizador de luz ligada.
ledState = LOW; // Ajusta variaveis de controlo para luz desligada.
ledStatePrev = LOW;
digitalWrite(PINMODULOLED, ledState); // Apaga a luz.
}
}
// Adapted from Arduino Debounce example at:
// https://www.arduino.cc/en/Tutorial/BuiltInExamples/Debounce
int verificaBotao() {
static unsigned long debounceTimePrev = 0; // the last time the output pin was toggled
static unsigned long debounceDelay = TEMPODEBOUNCE; // the debounce time; increase if the output flickers
static int buttonState = LOW; // the current reading from the input pin
static int buttonStatePrev = LOW; // the previous reading from the input pin
// read the state of the switch into a local variable:
int reading = digitalRead(PINBOTAOSTART);
// check to see if you just pressed the button
// (i.e. the input went from LOW to HIGH), and you've waited long enough
// since the last press to ignore any noise:
// If the switch changed, due to noise or pressing:
if (reading != buttonStatePrev) {
// reset the debouncing timer
debounceTimePrev = millis();
}
if ((millis() - debounceTimePrev) > debounceDelay) {
// whatever the reading is at, it's been there for longer than the debounce
// delay, so take it as the actual current state:
// if the button state has changed:
if (reading != buttonState) {
buttonState = reading;
}
}
// save the reading. Next time through the loop, it'll be the lastButtonState:
buttonStatePrev = reading;
return buttonState;
}
Quero usar o botão para ligar o timer, quando passar o tempo de 5 horas ele ira desligar o led, e só após pressionar o botão novamente ira acender e se caso eu precisar apagar o led pressionar o botão , e assim, sucessivamente, no código abaixo o led está piscando.
E também adicionei um código de um sensor de temperatura para acionar um cooler para resfriar o a agua do aquário, este está funcionando corretamente.
Só preciso de ajuda no caso do timer...
Se puderem ajudar, ficarei grato!
#include <Thermistor.h> //INCLUSÃO DA BIBLIOTECA
#define pinBotao 2
#define pinLED 4
#define cooler 6
boolean estadoBotao = true;
boolean estAntBotao = true;
boolean estadoPisca = false;
Thermistor temp(2); //VARIÁVEL DO TIPO THERMISTOR, INDICANDO O PINO ANALÓGICO (A2) EM QUE O TERMISTOR ESTÁ CONECTADO
unsigned long delay1 = 0;
void setup() {
pinMode(pinBotao, INPUT_PULLUP);
pinMode(pinLED, OUTPUT);
Serial.begin(9600);
}
void loop() {
estadoBotao = digitalRead(pinBotao);
if (!estadoBotao && estAntBotao) {
estadoPisca = !estadoPisca;
}
estAntBotao = estadoBotao;
if (estadoPisca) {
if ((millis() - delay1) >= 1000) {
digitalWrite( pinLED, LOW);
}
if ((millis() - delay1) < 3000) {
digitalWrite( pinLED, HIGH);
}
if ((millis() - delay1) >= 4000) {
delay1 = millis();
}
} else {
digitalWrite( pinLED, LOW);
}