设计并制作一个电路,具备密码功能,有三个按键,连续按下K1两次,K2一次,K3-次,数码管显示1,其余无论何种情况均显示0。

img

设计并制作一个电路,具备密码功能,有三个按键,连续按下K1两次,K2一次,K3-次,数码管显示1,其余无论何种情况均显示0。

上次做了一个一样的

// 包含头文件和函数声明等
#include <reg51.h>
#define LED P2
//循环计数器 
unsigned char Cnt_K1 = 0, Cnt_K2 = 0, Cnt_K3 = 0;
sbit K1 = P1 ^ 0;
sbit K2 = P1 ^ 1;
sbit K3 = P1 ^ 2;
int state = 0;
void delay(unsigned int t)
{
    while (t--);
}
void display(int num)
{
    static const char  table[] = { 0x3f, 0x06, 0x5b, 0x4f, 0x66, 0x6d, 0x7d, 0x07, 0x7f, 0x6f };
    LED = table[num];
}

//延时函数-1ms 
void Delay1ms()
{
    unsigned char a, b, c;
    for (c = 45; c > 0; c--)
        for (b = 10; b > 0; b--)
            for (a = 10; a > 0; a--);
}

void main() {
    
    while (1) {

        if (K1 == 0)
        {
            Cnt_K1++;
            state = 1;
            Delay1ms();
            if (Cnt_K1 > 2)
            {
                Cnt_K1 = 0;
                state = 0;
            }
            
        }
        if (K2 == 0 && state == 1)
        {
            Cnt_K2++;
            state = 2;
            Delay1ms();
            if (Cnt_K2 > 1)
            {
                Cnt_K2 = 0;
                state = 0;
            }
        
        }
        if (K3 == 0 && state == 2)
        {
            Cnt_K3++;
            state = 3;
            Delay1ms();
            if (Cnt_K3 > 1)
            {
                Cnt_K3 = 0;
                state = 0;
            }
    
        }
        //连续按下K1两次,K2一次,K3一次,数码管显示1
        if (Cnt_K1 == 2 && Cnt_K2 == 1 && Cnt_K3 == 1 && state == 3)
        {
            display(1);
        }
        else
        {
            display(0);
        }
    }
}


小小代码示例:

module password_circuit(  
    input clk,          // 时钟信号  
    input k1,           // K1按键信号  
    input k2,           // K2按键信号  
    input k3,           // K3按键信号  
    output reg [3:0] led // 数码管输出信号  
);  
  
reg [2:0] count = 0;    // 计数器  
reg [1:0] password = 0; // 密码寄存器  
  
always @(posedge clk) begin  
    if (k1) begin  
        count <= count + 1;  
        if (count == 2) begin  
            password <= 0;  
        end  
    end  
    if (k2) begin  
        count <= 0;  
        password <= 1;  
    end  
    if (k3) begin  
        count <= 0;  
        password <= 0;  
    end  
    if (password == 1) begin  
        led <= 4'b1000; // 显示数字1  
    end else begin  
        led <= 4'b0000; // 显示数字0  
    end  
end  
  
endmodule

#如有帮助,恭请采纳