Millis function does not always return the same value (Solved the problem THX)

Hi, I'm new to the forum and I appreciate the good work, I'm trying to use the millis function, but I'm having problems when I try to do more than one function at the same time, it gets weird behavior.
This is the code I made:

//Definir Pinos
#define MotorS 12
#define MotorN 13
#define Botao 7

//Tempos de Abertura e Fecho
const unsigned long AbrirFecharPortaoS = 10000;
const unsigned long AbrirFecharPortaoN = 5000;
const unsigned long TempoAberto = 1000;

unsigned long TempoAnteriorS = 0;
unsigned long TempoAnteriorN = 0;
unsigned long TempoAbertoA = 0;

int estadoBotao;
int estadoPortoes;
int estadoPortaoS;
int estadoPortaoN;

void setup() {

Serial.begin(9600);
pinMode (MotorS, OUTPUT);
pinMode (MotorN, OUTPUT);
pinMode (Botao, INPUT_PULLUP);
estadoPortoes = 0;
}

void loop() {

Serial.print("Estado Portões:");
Serial.println(estadoPortoes);

//Atualiza o Tempo
unsigned long TempoAtual = millis();

//Funcionamento do Botão
estadoBotao = digitalRead(Botao);
if ((estadoBotao == LOW)&&(estadoPortoes==0)) {
delay(50);
estadoBotao = digitalRead(Botao);
if (estadoBotao == HIGH){
estadoPortoes = 1;
}}

//Abre o Portao Sul
if(estadoPortoes == 1){
digitalWrite(MotorS, HIGH);
digitalWrite(MotorN, HIGH);
estadoPortoes = 2;
}

if((estadoPortoes == 2)&&(TempoAtual - TempoAnteriorS >= AbrirFecharPortaoS)){
digitalWrite(MotorS, LOW);
estadoPortaoS = 1;
//Atualiza o Tempo para o Proximo Evento
TempoAnteriorS = TempoAtual;
}

if((estadoPortoes == 2)&&(TempoAtual - TempoAnteriorN >= AbrirFecharPortaoN)){
digitalWrite(MotorN, LOW);
estadoPortaoN = 1;
//Atualiza o Tempo para o Proximo Evento
TempoAnteriorN = TempoAtual;
}

if((estadoPortaoS == 1)&&(estadoPortaoN == 1)){
estadoPortoes = 0;
estadoPortaoN = 0;
estadoPortaoS = 0;
}
}

welcome to the forums. Please take a moment and read the sticky post at the top to learn how to get the most out of this forum. It starts with formatting your code and posting it in code tags. This makes it easier for people to help you.

I believe your problem is that you need to capture the start time when the button is first pressed so your motors stay on, starting from that point

  //Abre o Portao Sul
  if (estadoPortoes == 1) {
    digitalWrite(MotorS, HIGH);
    digitalWrite(MotorN, HIGH);
    estadoPortoes = 2;
    TempoAnteriorS = TempoAtual;
    TempoAnteriorN = TempoAtual;
  }
  ...

Thank you very much for the reply, I will read the topics as you suggest, the problem is solved thanks to you, thank you so much I am always learning, thank you.

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.