我尝试使用键盘4x4读取用户的输入,并使用有限状态机比较输入,如下所示。
当我遇到第四种情况时,我的状态机不会转到检查大小写,而是转到默认状态,然后按一个键立即转到CHECK,这会使用户按下五次而不是四次。
while (1)
{
key=get_key();
if (key>=0 && key <=9){
switch (password){
case FIRST:
if (key==7 && i==0)
{
temp++; // increasing every time we enter correct number
password=SECOND;
HAL_Delay(300);
break;
}
HAL_Delay(300);
i++; // To check if we have fed in wrong digit
if(i==4) {
password=CHECK;
}
break;
//**********************************************************************************************************
case SECOND:
if (key==3 && temp==1){
temp++;
HAL_Delay(300);
password=THIRD;
break;
}
HAL_Delay(300);
i++;
if((i==3) || (i==2)) {
password=CHECK;
}
break;
//****************************************************************************************************
case THIRD:
if (key==9 && temp==2)
{
temp++;
HAL_Delay(300);
password = FOURTH;
break;
}
HAL_Delay(300);
i++;
if((i==2) || (i==1)) {
password=CHECK;
}
break;
//*******************************************************************************************************
case FOURTH:
if (key==2 && temp==3)
{
temp++;
password=CHECK;
break;
}
//HAL_Delay(300);
i++;
if(i==1) {
password=CHECK;
}
break;
//****************************************************************************************************
case CHECK:
if (temp==4){ // if temp has incresed to 4 that means that all the numbers entered are correct
HAL_GPIO_WritePin(Led_test_GPIO_Port,Led_test_Pin,1);
HAL_GPIO_WritePin(Led2_test_GPIO_Port,Led2_test_Pin,0);
password=IDLE_PASSWORD;
}
else if((i==4) || (i==3) || (i==2) || (i==1)) {
HAL_GPIO_WritePin(Led2_test_GPIO_Port,Led2_test_Pin,1);
HAL_GPIO_WritePin(Led_test_GPIO_Port,Led_test_Pin,0);
password=IDLE_PASSWORD;
}
break;
//******************************************************************************************************
case IDLE_PASSWORD:
temp=0;
i=0;
password = FIRST;
break;
default:
password = FIRST;
break;
}
}
}
答案 0 :(得分:0)
while (1)
{
static uint8 Password[4] = {7, 3, 9, 2};
static uint8 Guesses = 0;
static uint8 Wrong = 0;
/*Get the key*/
key=get_key();
/*If the key is not in range...*/
if (key<0 || key >9)
{
/*Return early*/
return;
}
/*Wait 300*/
HAL_Delay(300);
/*If the value at the Guess position is not equal to what they pressed...*/
if (key != Password[Guesses])
{
/*Mark the input as wrong*/
Wrong = 1
}
/*Increment Guesses for the next time*/
Guesses++;
/*After their fourth input...*/
if (Guesses == 4)
{
/*Reet Guesses*/
Guesses = 0;
/*If they were wrong...*/
if (Wrong == 1)
{
/*Reset Wrong*/
Wrong = 0;
}
/*Otherwise if they were right...*/
else
{
/*Do something*/
}
}
}
这是未经测试的 - 调试一下它应该可以工作。