问题
How to generate a PWM signal using an FPGA? Which is best method to generate a variable duty cycle?
I tried to solve this problem by using the following code but two or three errors occurred.
This is my code:
library IEEE;
use IEEE.STD_LOGIC_1164.ALL;
use IEEE.STD_LOGIC_ARITH.ALL;
use IEEE.STD_LOGIC_UNSIGNED.ALL;
use ieee.numeric_std.all;
--use ieee.float_pkg.all;
---- Uncomment the following library declaration if instantiating
---- any Xilinx primitives in this code.
--library UNISIM;
--use UNISIM.VComponents.all;
entity pwm_sne is
Generic(
sys_clk :integer :=50000000;
pwm_freq :integer :=100000;
bits_resolution :integer :=8
);
Port (
clk : in STD_LOGIC;
rst : in STD_LOGIC;
k : in STD_LOGIC_VECTOR (7 downto 0);
y : out STD_LOGIC
);
end pwm_sne;
architecture Behavioral of pwm_sne is
signal cnt :std_logic_vector(7 downto 0);
signal flag :std_logic;
signal reg :std_logic_vector(7 downto 0);
--variable duty :std_logic:=0;
begin
process(clk,rst)
begin
if rst='1' then
cnt<="00000000";
elsif(clk'event and clk='1')then
cnt<=cnt+"00000001";
elsif cnt="11111111" then
flag<='0';
cnt<="00000000";
end if;
end process;
process(clk,flag)
begin
if(clk'event and clk='1') then
reg<=k;
end if;
end process;
process(cnt,reg)
begin
if(flag='0')then
elsif cnt>reg then
y<=(reg/256)*100;
--y<=duty;
elsif cnt=reg then
y<=(reg/256)*100;
elsif cnt<=reg then
y<=period;
--y<=duty;
end if;
end process;
end Behavioral;
The errors occurred in output value y
and at the division operation.
Please suggest a good method to solve the problems from above.
回答1:
Solution : Do maths on numbers, not on untyped bags of bits.
If cnt, reg,k
were natural range 0 to 255
and you compared cnt
with 0 or 255 and added 1 to it, this would just work. And if k
MUST be std_logic_vector, use ONE type conversion function between it and reg
.
Also recommended : delete the non-standard std_logic_arith and
std_logic_unsignedlibs and use
numeric_std` instead.
来源:https://stackoverflow.com/questions/36083149/pwm-generation-using-fpga