模板一:
reg [18:0] cnt0 ;
always @(posedge clk or negedge rst_n)begin if(!rst_n)begin cnt0 <= 0; end else if(add_cnt0)begin if(end_cnt0) cnt0 <= 0; else cnt0 <= cnt0 + 1; end end assign add_cnt0 = 1; assign end_cnt0 = add_cnt0 && cnt0==400_000 -1 ;
模板二:
reg[24:0] cnt;//计数器 always@(posedge clk or negedge rst_n) begin if(!rst_n) cnt <= 25'd0; else if(cnt == 25'd24999999)
//500_000_000/20=25_000_000,因为计数到0也算时间,故再减1
cnt <= 25'd0; else
cnt <= cnt + 1'b1; end
模板三
//计数器对系统时钟计数,计时 0.2 秒 always @(posedge clk or negedge rst_n) begin if (!rst_n) counter <= 24'd0; else if (counter < 24'd1000_0000) counter <= counter + 1'b1; else counter <= 24'd0; end
linux应用程序或者是nios 应用程序里面计数器模板:
参考友晶科技2022年师资培训资料的第三课《开发与FPGA通信的Linux应用程序》的lab3_1:
while (!stop) { bool key0_pressed = *KEY_ptr & 0x1; //判断key0是否被按下 bool key1_pressed = (*KEY_ptr >> 1) & 0x1; //判断key1是否被按下 bool sw0_up = *SW_ptr & 0x1; //判断滑动开关sw0是否被拨向上 if (key0_pressed) { while (key0_pressed) { key0_pressed = *KEY_ptr & 0x1; }; //等待key0被释放 count_value = 0; //复位时计数器清零 } else if (sw0_up) { //当sw0拨向上 if (key1_pressed) { while (key1_pressed) { key1_pressed = (*KEY_ptr >> 1) & 0x1; }; //等待key1被释放
if(count_value == 15) //计数到15后清零
count_value = 0;
else
count_value++;
}
}