Bluesir9
Bluesir9

Reputation: 121

Increment count for int8_t

I am working on cortex m0. I want to increment the count of a variable thats declared as int8_t but on displaying the output its pretty erratic. Code:

//
// Smpl_7seg_keypad
//
// Input:  3x3 keypad (input = 1~9 when key is pressed, =0 when key is not pressed
// Output: 7-segment LEDs
//
#include <stdio.h>                                                                                                           
#include "NUC1xx.h"
#include "DrvSYS.h"
#include "Seven_Segment.h"
#include "scankey.h"
#include "NUC1xx-LB_002\LCD_Driver.h"


int32_t main (void)
{
int8_t number;
char a[]={'0'};
int count=0;
char arr[]="    ";

UNLOCKREG();
  DrvSYS_Open(48000000);
LOCKREG();

OpenKeyPad();   
Initial_panel();
clr_all_panel();
//print_lcd(0, "Msrit");
sprintf(arr,"%d",count);
print_lcd(0,arr);
while(1)
{
  number = Scankey(); 
    //a[0]=48+number;
    if(number ==1)
    {
        clr_all_panel();
        count++;
        //print_lcd(0,"\(\\__/\)");
        //print_lcd(1,"\(='.'=\)");
        //print_lcd(2,"\(\"\)_\(\"\)");
        sprintf(arr,"%d",count);
        print_lcd(0,arr);


    }
    else if(number==2)
    {
        clr_all_panel();
        count--;
        //print_lcd(0," O");
        //print_lcd(1,"\/|\\");
        //print_lcd(2,"\/ \\");
        sprintf(arr,"%d",count);
        print_lcd(1,arr);

    }
    //print_lcd(1, a); 
    // scan keypad to get a number (1~9)
    show_seven_segment(1,number); // display number on 7-segment LEDs
    DrvSYS_Delay(5000);           // delay time for keeping 7-segment display 
    close_seven_segment();        // turn off 7-segment LEDs                                 
}

}

For example the output goes: 12,28,28,29,41

What changes do i need to make to the code so that the count variable increments normally?

Upvotes: 1

Views: 398

Answers (1)

NPE
NPE

Reputation: 500317

The increment itself is fine. The problem is that you are checking Scankey() in a tight loop. No matter how quickly you release the button, the loop manages to execute several times, increasing the counter by more than one.

You need to wait for the button to be released before incrementing the counter again. One way to do this would be to keep the most recent value you got from Scankey() and only enter the if sequence when the output of Scankey() changes:

int8_t prev_number = 0;
...
while(1) {
  number = Scankey();
  if (number != prev_number) {
    if(number == 1) {
      clr_all_panel();
      ...
    } else if (...) {
      ...
    }
  }
  prev_number = number;
  ...
}

Also read up on debouncing.

Upvotes: 1

Related Questions