LCD, Menu and Buttons

Guys, I'm developing a project to a filling machine where there is a mat , a pump , sensor , keypad and buttons and using an Arduino Mega

  • My main question is in regards to the LCD menu where I want to be on the first screen after being triggered by a " bverde " button a message with the hostname and then passing one second will show the amount to be bottled . The amount will be the value entered in the keypad ;

  • After the value is entered by the keypad a second screen is shown , this screen will be told the amount of bottled and pressing the " bamarelo " changes the screen to the third screen which will show the level of the storage tank , by pressing the " bamarelo " again it goes back to the second screen , ie the " bamarelo " will act as an options button that moves between these two screens ;

  • Using a decrementador want the same decrement the value entered in the first screen showing the message that the Lot is ready and that it is entering a new value ;

  • A third button " bvermelho " would be the emergency button is pressed ie the machine hangs.

  • This whole program was based on examples and projects that I found here on the forum and other sites .
    Follows the program :

#include <Keypad.h>
#include <LiquidCrystal.h>  
LiquidCrystal lcd(22,23,24,25,26,27);  // DECLARAÇÃO DOS PINOS DO LCD NO ARDUINO

// DEFINIÇÃO DOS BOTÕES - VERDE. VERMELHO, AMARELO
#define bverde    A1  // Os pinos analógicos podem ser
#define bamarelo  A2  // usados como digitais, bastando
#define bvermelho      A3  // referenciá-los por A0, A1..
#define bDown    A4

#define bverde0   90  // Valor de referência que a
#define bamarelo0 91  // função CheckButton() passa
#define bvermelho0     92  // indicando que um botão foi
#define bDown0   93  // solto

boolean averde, aamarelo, avermelho, aDown;  // Grava o ultimo valor lidos nos botões.
// Utilizado pela função Checkbutton p/ identificar quando há uma alteração no estado do pino dos botões

// DEFINIÇÃO DOS PINOS E VALORES PARA O SENSOR, ESTEIRA E BOMBA
int contador = 0;  
int Sensor = 0;   
int sensorPin = A0;  
int MotorEsteira =  11;
int MotorBomb= 12;
int EstadoMotor=0;
int EstadoSensor=1;
int LED1=8;
int LED2=9;
int LED3=10;
int LED4=2;
int buzzer=7;
int variavel;  // VARIAVEL A SER ALTERADA PELO MENU
char state=1;  // VARIÁVEL QUE GUARDA POSIÇÃO ATUAL DO MENU
int dec=-1;
int i=0;

const byte LIN = 4; // TECLADO POSSUI 4 LINHAS
const byte COL = 3; //TECLADO POSSUI 3 COLUNAS
char keys[LIN][COL] = { 
  {//MATRIZ CORRESPONDENTE AOS CARACTERES DO KEYPAD  
    '1','2','3'                                                                                                            }
  ,    
  {
    '4','5','6'                                                                                                            }
  ,
  {
    '7','8','9'                                                                                                            }
  ,
  {
    '*','0','#'                                                                                                            }
};
byte LinPins[LIN] = {
  28,29,30,31}; //PINOS DO ARDUINO CORRESPONDENTES AS COLUNAS
byte ColPins[COL] = {
  32,33,34};    //E AS LINHAS DA MATRIZ

Keypad keypad = Keypad( makeKeymap(keys), LinPins, ColPins, LIN, COL );
char key = keypad.getKey();

void setup()
{
  lcd.begin(16, 2);  // Iniciando a biblioteca do LCD
  Serial.begin(9600); // DEFINIÇÃO DA PORTA SERIAL

  pinMode(bverde,  INPUT);   // Botões
  pinMode(bamarelo,INPUT);
  pinMode(bvermelho,    INPUT);
  pinMode(bDown,  INPUT);

  digitalWrite(bverde,  HIGH);  // Aciona o pull-up interno
  digitalWrite(bamarelo,HIGH);  // dos botões
  digitalWrite(bvermelho,    HIGH);
  digitalWrite(bDown,  HIGH);

  pinMode(sensorPin, INPUT);           //DEFINIR SE A VARIAVEL É ENTRADA(IMPUT) OU SAIDA(OUTPUT) DE DADOS
  pinMode(MotorEsteira, OUTPUT);    
  pinMode(MotorBomb, OUTPUT);
  pinMode(EstadoSensor, INPUT);
  pinMode(LED1, OUTPUT);
  pinMode(LED2, OUTPUT);
  pinMode(LED3, OUTPUT);
  pinMode(LED4, OUTPUT);
  pinMode(buzzer, OUTPUT);
}

void esteira(){
  Sensor = digitalRead(sensorPin); // A VARIAVEL SENSOR CORRESPONDE AO sensorPin QUE ESTÁ LIGADO A PORTA ANALÓGICA A0 DO ARDUIN

  if(Sensor == LOW){                      
    digitalWrite(MotorEsteira, HIGH);   // SE O SENSOR NÃO ESTIVER ACIONADO O MOTOR DA BOMBA ESTA PARADO E O LED1  ASCESO
    digitalWrite(LED1,HIGH);           
    digitalWrite(LED2, LOW);
    digitalWrite(MotorBomb, LOW);
    digitalWrite(buzzer, LOW);
  }
  if(Sensor == HIGH) {                // SE O SENSOR  ESTIVER ACIONADO O MOTOR DA ESTEIRA ESTA PARADO E O  LED1  APAGA
    digitalWrite(MotorEsteira, LOW); //  O MOTOR DA BOMBA LIGA E O LED2 ASCENDE E UM TOQUE DE 2 SEGUNDO É 
    digitalWrite(MotorBomb, HIGH);  //  ACIONADO PELO BUZZER 
    digitalWrite(LED1, LOW);
    digitalWrite(LED2, HIGH);
    delay(8000);//ESTE DELAY SERVE PARA A BOMBA JOGAR 200ml DE AGUA NA GARRAFA
    contador++;
    Sensor == !Sensor;    //O SINAL DO SENSOR É INVERTIDO PARA A FUNÇAO RETORNAR DE ONDE ESTAVA
  }
  EstadoSensor = digitalRead(sensorPin);  // O SINAL DO SENSOR É MOSTRADO NO SERIAL MONITOR 
  Serial.println(Sensor);

  if(EstadoSensor == HIGH){            // A FUNÇAO RETORNA AO ESTADO INICIAL
    digitalWrite(MotorEsteira, HIGH); 
    digitalWrite(MotorBomb, LOW);
    digitalWrite(LED1, HIGH);
    digitalWrite(LED2, LOW);
    digitalWrite(buzzer,LOW);
    delay(2000);
  }
}

void loop()
{

  esteira();

  switch (state) {  // Define checa qual tela atual

  case 1:          // executado quando na TELA 1
    switch (CheckButton()) {

    case bverde:
      lcd.setCursor(0,0);
      lcd.print("Maquina Envase");
      delay(1000);
      lcd.setCursor(0,0);    
      lcd.print("Quantidade LOTE:");


      Set_state(1);
      break;
    case bamarelo:
      lcd.clear(); 
      Set_state(2); // antes de mudar de tela, é necessário limpar o
      break;
      lcd.clear(); 
      Set_state(3);        // display com a função lcd.clear()
      // break;
    default:   // Caso nenhum botão tenha sido apertado, ela executa a set_state
      Set_state(1); // mesmo assim para atualizar o display.
    }
    break;

  case 2:          // executado quando na TELA 2
    switch (CheckButton()) {
    case bverde:  
      lcd.clear(); 
      Set_state(1);
      break;
    case bamarelo:  //
      lcd.clear(); 
      Set_state(3);
      break;
      lcd.clear(); 
      Set_state(1);
      break;
      lcd.clear(); 
      Set_state(2);
      break;
    default:
      Set_state(2);
    }
    break;

  case 3:          // executado quando na TELA 3
    switch (CheckButton()) {
    case bverde:  
      lcd.clear(); 
      Set_state(1);
    case bamarelo:
      lcd.clear(); 
      Set_state(2);
      break;
      lcd.clear(); 
      Set_state(3);
      break;
      lcd.clear(); 
      Set_state(1);
      break;
    default:
      Set_state(3);
    }
    break;

  case 4:          // executado quando na TELA 4
    switch (CheckButton()) {
    case bamarelo:
      lcd.clear(); 
      Set_state(1);
      break;
    default:
      Set_state(1);
    }
    break;

  default: 
    ;
  }
}// FIM DO LOOP

char CheckButton() {                                              
  if (averde!=digitalRead(bverde)) {    
    averde=!averde;                    
    if (averde) return bverde0;       
    else return bverde;
  } 
  else
    if (aamarelo!=digitalRead(bamarelo)) {
      aamarelo=!aamarelo;
      if (aamarelo) return bamarelo0; 
      else return bamarelo;
    } 
    else
      if (avermelho!=digitalRead(bvermelho)) {
        avermelho=!avermelho;
        if (avermelho) return bvermelho0; 
        else return bvermelho;
      } 
      else
        if (aDown!=digitalRead(bDown)) {
          aDown=!aDown;
          if (aDown) return bDown0; 
          else return bDown;
        } 
        else
          return 0;
}


void Producao() // FUNÇÃO QUE DEFINE A QUANTIDADE DE GARRAFAS A SEREM ENVASADAS NO DIA
{
  char key = keypad.getKey();
  if (key != NO_KEY){

    lcd.setCursor(i,2); 
    lcd.print(key);    
    lcd.print(" garrafas");
    i++;
  }
}

void Set_state(char index) {
  state = index;  // Atualiza a variável state para a nova tela
  switch (state) {  // verifica qual a tela atual e exibe o conteúdo correspondente

    case 1: //==================== state 1

      Producao();

    break;
  case 2: //==================== state 2

      lcd.setCursor(0,0);
    lcd.print("Qnt. Envasada:");
    lcd.setCursor(0,1);
    lcd.print(contador);  // mostra os segundos na tela
    lcd.print(" garrafas");
    delay(20);
    break;
  case 3: //==================== state 3

      lcd.setCursor(0,0);
    lcd.print("Nivel Tanque");
    lcd.setCursor(1,2);
    lcd.print("%");
    break;
  case 4: //==================== state 4

      break;
  default: 
    ;
  }
}

Please re-attach your code using the code # button not the Quote button.

LarryD:
Please re-attach your code using the code # button not the Quote button.

Sorry, :slight_smile: