1

When i press a button to subtract 1 from 5 it skips to 3, it's the same when I add 1 to -5 it skips displaying - 4 and goes straight to -3.

This is the code that i am using:

//Testing the use of addition and subtraction with the menu options.

#include <LiquidCrystal.h>

LiquidCrystal lcd(8, 9, 4, 5, 6, 7);         


int lcd_key     = 0;
int adc_key_in  = 0;
int calc_total;

#define btnRIGHT  0
#define btnUP     1
#define btnDOWN   2
#define btnLEFT   3
#define btnSELECT 4
#define btnNONE   5

int read_LCD_buttons(){              
    adc_key_in = analogRead(0);     



    if (adc_key_in > 1000) return btnNONE; 


    if (adc_key_in < 50)   return btnRIGHT;  
    if (adc_key_in < 150)  return btnUP; 
    if (adc_key_in < 300)  return btnDOWN; 
    if (adc_key_in < 450)  return btnLEFT; 
    if (adc_key_in < 700)  return btnSELECT;  



    return btnNONE;      

}

void setup(){
   lcd.begin(16, 2);              
   lcd.setCursor(0,0);    
   lcd.print (calc_total);  

}

void loop(){

   lcd_key = read_LCD_buttons();  
   calc_total = constrain(calc_total, -4, 4);

   switch (lcd_key){              

       case btnRIGHT:{           
            lcd.clear();  
            calc_total = calc_total - 1;
            lcd.print (calc_total);
            delay(700);
            lcd.setCursor(0,0); 
            break;
       }
       case btnLEFT:{
            lcd.clear();
            calc_total = calc_total + 1;
            lcd.print (calc_total);
            delay(700);
            lcd.setCursor(0,0); 
            break;
       }
     }   
}
Liam
  • 167
  • 1
  • 2
  • 9

2 Answers2

1

Your main problem is that you aren't looking for a change in buttons. You're only doing your adding or subtracting while a button is pressed.

That means, all the time you're holding btnLEFT in your total is incrementing until it hits your limit.

You need to remember the button state from the previous iteration of loop() and compare it to the current state - and only if they differ do you need to do anything.

Also you should perform your constrain immediately after your addition or subtraction. As it is, you add or subtract, display the new value (I assume you do - I don't see the code for that), and only afterwards do you then chop the value back down to +/-4 (assuming it's outside the range). So your 5 becomes 4, and your next subtraction takes you to 3.

Majenko
  • 105,851
  • 5
  • 82
  • 139
0

The whole point of constrain function is to keep the values between -4 and 4 (including). In your code you can go to the -5 and show it, but right after that it's adjusted to -4 (and you are not displaying this value).

If you increment this value, you can get only result and this is -4 + 1 = -3.

KIIV
  • 4,907
  • 1
  • 14
  • 21