功能:检测近 400KHz 时钟信号的高电平的中点和低电平的中点,并输出两个中点的标志位,如下图所示:
1 module iic_test( 2 clk, 3 rst_n, 4 5 scl, 6 7 scl_h, 8 9 scl_l 10 ); 11 12 input clk; 13 input rst_n; 14 15 output reg scl; 16 output reg scl_h; 17 output reg scl_l; 18 19 reg[7:0] cnt; 20 always@(posedge clk or negedge rst_n) 21 if(!rst_n) 22 cnt <= 8'd0; 23 else if(cnt == 120) 24 cnt <= 8'd0; 25 else 26 cnt <= cnt + 1'b1; 27 28 always@(posedge clk or negedge rst_n) 29 if(!rst_n) 30 scl <= 1'b1; 31 else if(cnt == 59) 32 scl <= 1'b0; 33 else if(cnt == 0) 34 scl <= 1'b1; 35 else 36 scl <= scl; 37 38 //reg scl_h,scl_l; // 分别为 scl 高电平的中点和 scl 低电平的中点 39 40 always@(posedge clk or negedge rst_n) // scl 高电平的中点标志位设计 41 if(!rst_n) 42 scl_h <= 1'b0; 43 else if(cnt == 29) 44 scl_h <= 1'b1; 45 else 46 scl_h <= 1'b0; 47 48 always@(posedge clk or negedge rst_n) // scl 低电平的中点标志位设计 49 if(!rst_n) 50 scl_l <= 1'b0; 51 else if(cnt == 89) 52 scl_l <= 1'b1; 53 else 54 scl_l <= 1'b0; 55 56 endmodule
测试代码:
1 `timescale 1ns/1ps 2 module iic_test_tb; 3 reg clk; 4 reg rst_n; 5 6 wire scl; 7 wire scl_h; 8 wire scl_l; 9 10 iic_test u0( 11 .clk(clk), 12 .rst_n(rst_n), 13 14 .scl(scl), 15 16 .scl_h(scl_h), 17 18 .scl_l(scl_l) 19 ); 20 21 initial 22 clk = 0; 23 always #10 clk = ~clk; 24 25 initial 26 begin 27 rst_n = 1'b0; 28 #21; 29 rst_n = 1'b1; 30 31 #100000; 32 $stop; 33 end 34 endmodule
modelsim仿真图: