频率及占空比检测
項目名稱:
頻率計設計
具體要求:
檢測方波的頻率和占空比
設計架構
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ??
wave:方波輸入
freq:檢測出的方波頻率
duty_cycle:測試出的方波占空比
狀態轉移圖
測試出高電平和低電平的時間,經過計算得出頻率和占空比
high_state:高電平狀態
low_state:低電平狀態
low_cnt:低電平計數
high_cnt:高電平計數
low_time:低電平時間
high_time:高電平時間
代碼設計
verilog代碼設計
module freq_detect(input clk,input rst_n,input wave,output [25:0] freq, //檢測方波的頻率output [6:0] duty_cycle //檢測方波的占空比 );reg state; localparam high_state=1'd0; localparam low_state=1'd1; reg [25:0]high_cnt;//可測試到1hz reg [25:0]low_cnt; reg [25:0]high_time; reg [25:0]low_time; always@(posedge clk or negedge rst_n)if(!rst_n)beginstate<=high_state;high_cnt<=26'd0;low_cnt<=26'd0;high_time<=26'd0;low_time<=26'd0;endelse begincase(state)high_state: beginif(wave==1)beginhigh_cnt<=high_cnt+1'b1;state<=high_state;endelse beginhigh_cnt<=26'd0;high_time<=high_cnt;state<=low_state;endendlow_state : beginif(wave==0)beginlow_cnt<=low_cnt+1'b1;state<=low_state;endelse beginlow_time<=low_cnt;low_cnt<=26'd0;state<=high_state;endenddefault:state<=high_state;endcaseend //系統時鐘為50Mhz,計數需要時間=計數值*20ns,測試頻率的周期為high_time*20+low_time*20 assign freq=1000_000_000/(high_time*20+low_time*20); //占空比乘以100之后化為0-100之間的整數 assign duty_cycle=high_time*100/(high_time+low_time); endmodule仿真代碼
`timescale 1ns/1ns module freq_detect_tb;reg clk;reg rst_n;reg wave;wire [25:0] freq; //檢測方波的頻率wire [6:0] duty_cycle; //檢測方波的占空比freq_detect freq_detect(.clk(clk),.rst_n(rst_n),.wave(wave),.freq(freq), //檢測方波的頻率.duty_cycle(duty_cycle) //檢測方波的占空比 );initial clk=0; always #10 clk=~clk;initial beginrst_n=0;#200rst_n=1;#1_000_000_0 //仿真時間10ms$stop; endinitial beginwave=1;forever begin //產生占空比為60%,1khz的方波#600_000;wave=0;#400_000;wave=1;end endendmodule仿真結果
從結果可以看出待輸出穩定之后,檢測出1000hz的方波,待測試的方波在第二個周期可以穩定檢測到占空比60%,代碼中將檢測到的占空比乘以100,得到60.
總結
- 上一篇: 梁漱溟:做学问的八层境界
- 下一篇: 基于Echarts实现可视化数据大屏水质