使用FPGA输出一个PWM方波

发布于:2024-04-25 ⋅ 阅读:(21) ⋅ 点赞:(0)

介绍

我记得去年冬天的时候,那个时候我还在学verilog vhdl语言的时候,我特别想用FPGA输出一个pwm方波,大概因为太着急了吧,忽略了很多东西,最终也没有发出来一个PWM波。今天其实是想驱动一下板卡上的蜂鸣器,但是意识到驱动信号其实也就是一个方波,正好也学习了包集和元件,所以也用一下。


设计文件

分频器

通过改变N的值就可以实现不同的分频了,只针对偶数次分频。

library ieee;
use ieee.std_logic_1164.all;
entity div is
    generic(constant N : integer := 10000000);
    port(clk : in std_logic;
         clk_N : out std_logic);
end entity;
architecture behavior of div is
    signal temp : integer := 0;
    constant half : integer := N/2;
begin 
    process(clk)
    begin
    if rising_edge (clk) then
        temp <= temp + 1;
        if (temp < half) then
            clk_N <= '0';
        elsif (temp < N-1) then
            clk_N <= '1';
        else 
            temp <= 0;
            clk_N <= '1';
        end if;
    else
        temp <= temp;
    end if;
    end process;
end architecture;

PWM方波

library ieee;
use ieee.std_logic_1164.all;
entity pwm is
    port(clk : in std_logic;
         outp : out std_logic);
end entity;
architecture behavior of pwm is
    signal temp : integer := 0;
begin 
    process(clk)
    begin
    if rising_edge (clk) then 
        temp <= temp + 1;
        if (temp < 2) then
            outp <= '0';
        elsif (temp < 3) then
            outp <= '1';
        else
            temp <= 0;
            outp <= '0';
        end if;
    end if;
    end process;
end architecture;

包集

library ieee;
use ieee.std_logic_1164.all;
package my_component is
    component div is
        port(
             clk : in std_logic;
             clk_N : out std_logic);
    end component;
    component pwm is
        port(clk : in std_logic;
             outp : out std_logic);
    end component;
end package;

顶层

library ieee;
use ieee.std_logic_1164.all;
use work.my_component.all;
entity beep is
    port(inp : in std_logic;
         outp : out std_logic);
end entity;
architecture behavior of beep is
signal clk_N: std_logic;
begin
    u1: div
    port map(inp,clk_N);
    u2: pwm
    port map(clk_N,outp);
end architecture;


仿真文件

library ieee;
use ieee.std_logic_1164.all;
use work.my_component.all;
entity tb_beep is

end entity;
architecture behavior of tb_beep is
signal clk,outp : std_logic;
begin 
    dut: pwm
    port map(clk,outp);
    process
    begin
        clk <= '0';
        wait for 10ns;
        clk <= not clk;
        wait for 10ns;
    end process;
end architecture;


仿真结果


结语

其实不需要设计分频器的是吧,哈哈哈哈。使用包集之后,整个设计就显得很清晰了。

将这个输出设置到板卡led灯就可以实现led灯闪烁了,大家要多尝试啊。

另外有一点我特别疑惑,从仿真图上看,分频器没有发生作用,我没有发现哪里有问题,所以我放到示波器上看,显示分频器起作用了。