Please help with my issue.
I am trying to avoid going out of the limit between 0 to 100 for the count up/down value in the program below;
I am using an 8051 microcontroller and 2x16 LCD to display a value between 0 and 100. when pressing the UP button the number increased by one, while when pressing down button it decreased by one.
my code keeps incrementing the value above 100 and less 0.
// This is a code in Embedded C written on MikroC compiler for 8051 microcontroller
// The microcontroller shall count up / down on the LCD when press up / down button.
unsigned int cntr=0; // counter value
char lcdv[6]; // Value to displau on lcd
sbit UP at P3.B7; // declare button UP at port 3 Bit 7.
sbit DN at P3.B6; // declare button UP at port 3 Bit 6.
// LCD module connections
sbit LCD_RS at P2_0_bit; // Declare LCD reset pin.
sbit LCD_EN at P2_1_bit; // Declare LCD Enable pin.
sbit LCD_D4 at P2_2_bit; // Declare LCD D4 pin.
sbit LCD_D5 at P2_3_bit; // Declare LCD D5 pin.
sbit LCD_D6 at P2_4_bit; // Declare LCD D6 pin.
sbit LCD_D7 at P2_5_bit; // Declare LCD D7 pin.
// End LCD module connections
char text[16]; // this is stored in RAM
void main() { // Main program
P3 = 255; // Configure PORT3 as input
Lcd_Init(); // Initialize LCD
cntr=0; // Starting counter value
Lcd_Cmd(_LCD_CLEAR);
Lcd_Cmd(_LCD_CURSOR_OFF);
while(1) {
while ((cntrset<=100)&&(cntrset>=0)) // Not sure how to limit Min and Max value.
{
wordTostr(cntrset,volset);
LCD_Out(2,1,volset);
if (UP==0)
cntrset ++;
while (UP==0);
if (DN==0)
cntrset=--;
while (DN==0);
}
}
}
if (UP==0 && cntrset < 100 ) cntrset++;
while (UP==0);
if (DN==0 cntrset > 0 ) cntrset--;
while (DN==0);
You may still have an issue with switch bounce causing a single press to result in the counter changing by more than one count. But that is a different question.
Regarding comment: If the increment is not by-one and the current value need not be a multiple of the increment, then it is easier to apply saturation instead:
if( UP == 0 ) cntrset += increment;
while (UP==0);
if( DN == 0 ) cntrset -= increment ;
while (DN==0);
if( cntrset < 0 ) cntrset = 0 ;
else if( cntrset > MAX_CNTRSET ) cntrset = MAX_CNTRSET ;
For that to work however you must change cntrset
to signed int
. If you'd rather not do that then (assuming 16 bit unsigned
):
...
if( (cntrset & 0x8000u) != 0 ) cntrset = 0u ;
else if( cntrset > MAX_CNTRSET ) cntrset = MAX_CNTRSET ;