相对于有源蜂鸣器,无源蜂鸣器的成本更低,声音频率可控。而有源蜂鸣器因其内部
自带振荡源,只要加上适当的直流电源即可发声,程序控制较为方便。
(1)设计定义:设计一个无源蜂鸣器的驱动程序,实现7个音调的循环发声,每个音调持续0.5s,占空比为50%。
(2)Visio视图:
(2)Verilog代码:
module beep(clk,reset_n,beep);input clk;input reset_n;output reg beep;
//0.5s = 500_000_000ns = 20ns * 25_000_000; 需要一个十五位的寄存器去计数reg[24:0]cnt;reg[2:0]cnt_500ms;
//freq最大值为190840,可以用一个二十位的寄存器去计数reg[19:0]freq_cnt;reg[19:0]freq_data;wire[19:0]duty_data;parameter MCNT_Time = 25'd24_999_999;parameter Do = 20'd190839 ;parameter Re = 20'd170067 ;parameter Mi = 20'd151514 ;parameter Fa = 20'd143265 ;parameter So = 20'd127550 ;parameter La = 20'd113635 ;parameter Si = 20'd101213 ;//500ms计数器模块设计always@(posedge clk or negedge reset_n)if(!reset_n)cnt <= 25'd0;else if(cnt == MCNT_Time)cnt <= 25'd0;else cnt <= cnt + 25'd1;//cnt_500ms计数器模块设计always@(posedge clk or negedge reset_n)if(!reset_n)cnt_500ms <= 3'd0;else if((cnt_500ms == 3'd6) && (cnt == MCNT_Time))cnt_500ms <= 3'd0;else if(cnt == MCNT_Time)cnt_500ms <= cnt_500ms + 3'd1;else cnt_500ms <= cnt_500ms;//freq_cnt计数器模块设计always@(posedge clk or negedge reset_n)if(!reset_n)freq_cnt <= 20'd0;else if((freq_cnt == freq_data) || (cnt == MCNT_Time))freq_cnt <= 20'd0;else freq_cnt <= freq_cnt + 20'd1;//freq_data设计always@(posedge clk or negedge reset_n)if(!reset_n)freq_data <= Do;else begincase(cnt_500ms)3'd0: freq_data <= Do;3'd1: freq_data <= Re;3'd2: freq_data <= Mi;3'd3: freq_data <= Fa;3'd4: freq_data <= So;3'd5: freq_data <= La;3'd6: freq_data <= Si;default:freq_data <= Do;endcaseend
//duty_data设计 assign duty_data = (freq_data >> 1);//beep输出设计always@(posedge clk or negedge reset_n)if(!reset_n)beep <= 1'd0;else if(freq_cnt > duty_data)beep <= 1'd1;else beep <= 1'd0;endmodule
(3)仿真文件代码;
`timescale 1ns / 1psmodule beep_tb;reg clk;reg reset_n;wire beep;beep beep_inst(.clk(clk),.reset_n(reset_n),.beep(beep));defparam beep_inst.MCNT_Time = 25'd24_999_9;defparam beep_inst.Do = 20'd1908 ;defparam beep_inst.Re = 20'd1700 ;defparam beep_inst.Mi = 20'd1515 ;defparam beep_inst.Fa = 20'd1432 ;defparam beep_inst.So = 20'd1275 ;defparam beep_inst.La = 20'd1136 ;defparam beep_inst.Si = 20'd1012 ;initial clk = 1'b1;always #10 clk = ~clk;initial beginreset_n = 1'b0;#15;reset_n = 1'b1;#50_000_000;$stop;endendmodule
(4)仿真波形:
(5)引脚绑定:
set_property IOSTANDARD LVCMOS33 [get_ports reset_n]
set_property IOSTANDARD LVCMOS33 [get_ports clk]
set_property IOSTANDARD LVCMOS33 [get_ports beep]
set_property PACKAGE_PIN N15 [get_ports reset_n]
set_property PACKAGE_PIN W19 [get_ports clk]
set_property PACKAGE_PIN M17 [get_ports beep]