我正在研究皮质m0。我想增加声明为int8_t的变量的计数,但是在显示输出时它非常不稳定。代码:
//
// 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
}
}
例如输出结果如下: 12,28,28,29,41
我需要对代码进行哪些更改才能使计数变量正常递增?
答案 0 :(得分:1)
增量本身很好。问题是您在紧密循环中检查Scankey()
。无论你多快释放按钮,循环都会设置多次执行,将计数器增加不止一次。
在再次递增计数器之前,您需要等待按钮被释放。一种方法是保留Scankey()
的最新值,并在if
的输出发生变化时仅输入Scankey()
序列:
int8_t prev_number = 0;
...
while(1) {
number = Scankey();
if (number != prev_number) {
if(number == 1) {
clr_all_panel();
...
} else if (...) {
...
}
}
prev_number = number;
...
}
同时阅读debouncing。