Pushbottons state changing randomly

Hello, I have a problem with my pushbottons. I am controling a stepper motor and I have four push buttons and wich one has a function: start the motor, increase the velocity, increse the number of spins, decrease the velocity, decrease the number of spins. I tried this same program with another circuit and everything worked well but when a tried this same program with my actual circuit the bottons didn't accept the comands (both of the circuits were similar, I just changed de gates), they switch the valeus between 0 and 1 when I didn't press the button yet. When I press the button, the number go to 4846758397489590 or something like that . I just wanna to know if there is any problem with my program or if the problem is the new circuit

// ================================================================================= BIBLIOTECAS ====================================================================================================================================================================================

#include <AccelStepper.h> // biblioteca do motor
#include <LiquidCrystal.h> // biblioteca do LCD

// ================================================================================= DECLARAÇÃO DE VARIÁVEIS ===========================================================================================================================================================================

const int rs = A5, en = A4, d4=A3, d5 = A2, d6 = A1, d7 = A0; // pinagem LCD 

const int DIR = 12; // entrada DIR do driver
const int STEP = 13; // entrada STEP do driver

unsigned long volta;
int botaomais=6; //entrada do botão incremento da volta
int botaomenosvolta=7; //entrada botão decremento da volta
int botaoroda=3; //entrada do botão start
int botaovelocidade=5; //entrada do botão incremento da velocidade
int botaomenosvelocidade=4; //entrada botão decremento da velocidade
unsigned long lap;
unsigned long count=0;
unsigned long volta_atual=0;
unsigned long vel=0;

unsigned long startMillis;
unsigned long currentMillis;
const unsigned long period = 1000;


// ============================================================================== DEFINIÇÃO DAS PORTAS ==========================================================================================================================================================================

LiquidCrystal lcd(rs, en, d4, d5, d6, d7); // definião das portas do LCD

#define InterfaceMotor 1 // Defina o tipo de interface do motor; interface 1 = driver

AccelStepper Stepper(InterfaceMotor, STEP, DIR); // Cria uma instância

// ============================================================================== SETUP ===========================================================================================================================================================================================
void setup() {
   lcd.begin(16,2); // (colunas, linhas) LCD
 pinMode(3,INPUT_PULLUP); // define a porta 3 como entrada
 pinMode(4,INPUT_PULLUP); // define a porta 4 como entrada
 pinMode(5,INPUT_PULLUP); // define a porta 5 como entrada
 pinMode(6, INPUT_PULLUP); // define a porta 6 como entrada
 pinMode(7, INPUT_PULLUP); // define a porta 7 como entrada
 
   lcd.begin(16,2); // (colunas, linhas) LCD
   lcd.setCursor(0,0);
   lcd.print("Iniciando, nao");
   lcd.setCursor(0,1);
   lcd.print("mexa na maquina.");
   lcd.setCursor(0,1);

   delay (3000); // tempo para a balança zerar
   
   lcd.clear();
   lcd.setCursor(0,0);
   lcd.print("O tribometro");
   lcd.setCursor(0,1);
   lcd.print(" esta pronto!");
   lcd.setCursor(0,1);
   
 startMillis = millis();  //tempo inicial do programa
}

//end setup

// ============================================================================= LOOP ================================================================================================================================================================================================
void loop() {
  
  currentMillis = millis(); // tempo decorrido desde a inicialização do programa
  
 botaomais=digitalRead(6); //entrada do botão incremento da volta
 botaomenosvolta=digitalRead(7); //entrada botão decremento da volta
 botaoroda=digitalRead(3); //entrada do botão start
 botaovelocidade=digitalRead(5); //entrada do botão incremento da velocidade
 botaomenosvelocidade=digitalRead(4); //entrada botão decremento da velocidade

  volta=count*200; // volta é o número de passos que o motor irá fazer, logo, multiplica-se o count por 200
  
  //Ao cliclar no botão mais, ocorre acréscimo +1 na variável "count"
  if(botaomais==LOW){
   count++ ; 
   delay(400);
   lcd.clear();
   lcd.setCursor(0,0);
   lcd.print("Voltas: ");
   lcd.print(count);
   lcd.setCursor(0,1);
   lcd.print("Vel: ");
   lcd.print(vel);
   lcd.print(" RPM");
  }

   //Ao cliclar no botão menos volta, ocorre decremento -1 na variável "count"
  if(botaomenosvolta==LOW){
   count-- ; 
   delay(400);
   lcd.clear();
   lcd.setCursor(0,0);
   lcd.print("Voltas: ");
   lcd.print(count);
   lcd.setCursor(0,1);
   lcd.print("Vel: ");
   lcd.print(vel);
   lcd.print(" RPM");
  }

   
   //Ao cliclar no botão velocidade, ocorre o incremento =1 na variável "vel"
    if(botaovelocidade==LOW){
    vel++;
    delay(400);
    lcd.clear();
    lcd.setCursor(0,0);
    lcd.print("Voltas: ");
    lcd.print(count);
    lcd.setCursor(0,1);
    lcd.print("Vel: ");
    lcd.print(vel);
    lcd.print(" RPM");
   }

   //Ao cliclar no botão menos velocidade, ocorre o decremento -1 na variável "count" 
   if(botaomenosvelocidade==LOW){
   vel--; 
   delay(400);
   lcd.clear();
   lcd.setCursor(0,0);
   lcd.print("Voltas: ");
   lcd.print(count);
   lcd.setCursor(0,1);
   lcd.print("Vel: ");
   lcd.print(vel);
   lcd.print(" RPM");
   }
   
//Acionamento do botão roda
  if(botaoroda==LOW){

//O motor roda na velocidade solocitada   
if(vel>0 && count>0){
  
     Stepper.setAcceleration(10*(pow(vel,2))); // y=10x²
     lcd.setCursor(0,1);
     lcd.print("Vel: ");
     lcd.print(vel);
     lcd.print(" RPM");

          //O motor roda a quantidade de voltas solicitada e mostra quantas voltas faltam para parar  
          for(unsigned long i=0;i<=volta; i++){
            Stepper.runToNewPosition(i);
       
          lcd.setCursor(0,0);
          lcd.print("Volta atual: ");
          volta_atual =count - (i/200);
          if(volta_atual<10){lcd.print("0");}
          lcd.print(volta_atual);
          if(volta_atual==0){
          lcd.clear();
          lcd.setCursor(0,1);
          lcd.print("Parado.");
          }
          }
          }
          }
      
        startMillis = currentMillis;
        Stepper.setCurrentPosition(0);
    }


//=================================================================================================== END LOOP ========================================================================================================================================================================================================


A schematic would be helpful.

If using switches for counting, debouncing is absolutely necessary.

Open the Serial port and put some serial prints in the code to monitor variable values and program flow to confirm that the code is doing what you expect.

1 Like

It looks like You use the same pins for the display and for buttons. I my min mind 0 == pin D0, 1 == pin D1.....

Does something differ between those two setups in hardware? What MCU / board do you use?

I second this.

Lets see what board is used.

Can You show what You say, in a pen and paper drawing?

i am using arduino mega in both cases

right now I can't, maybe tomorrow. but in both cases i use arduino mega. I'm trying to put my program in another hardware that wans't made by me. the problem is happening on hardware that has already been finalized, I cannot change it so i have to adapt the program to it

Another Mega? Do You know the history of them? Are they new or have they been out in other projects, maybe being stressed?

In this part of you code, add this line:

Without line:

  //Ao cliclar no botão menos volta, ocorre decremento -1 na variável "count"
  if(botaomenosvolta==LOW){
   count-- ; 
   delay(400);
   lcd.clear();
   lcd.setCursor(0,0);
   lcd.print("Voltas: ");
   lcd.print(count);
   lcd.setCursor(0,1);
   lcd.print("Vel: ");
   lcd.print(vel);
   lcd.print(" RPM");
  }

Now with line :

  //Ao cliclar no botão menos volta, ocorre decremento -1 na variável "count"
  if(botaomenosvolta==LOW){
   if (count != 0)  //  <------------------------------------------------------
   count-- ; 
   delay(400);
   lcd.clear();
   lcd.setCursor(0,0);
   lcd.print("Voltas: ");
   lcd.print(count);
   lcd.setCursor(0,1);
   lcd.print("Vel: ");
   lcd.print(vel);
   lcd.print(" RPM");
  }

And here too:

  //Ao cliclar no botão menos velocidade, ocorre o decremento -1 na variável "count" 
   if(botaomenosvelocidade==LOW){
   if (vel != 0)    // <--------------------------------------------------
   vel--; 
   delay(400);
   lcd.clear();
   lcd.setCursor(0,0);
   lcd.print("Voltas: ");
   lcd.print(count);
   lcd.setCursor(0,1);
   lcd.print("Vel: ");
   lcd.print(vel);
   lcd.print(" RPM");
   }
   

Thank you so much! The problem was the bounce

Glad to see that your issue was solved. :slight_smile:

1 Like

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