【背景】
朋友需要用FPGA输入16位二进制格式的数据,让帮忙用matlab产生这样一组正弦信号数据。【10KHz正弦波信号,每个周期25个样点,持续40ms,最后以16位二进制格式输出】
补充:
评论区有朋友在问,因此重新编辑了代码,给了更详细的注释,也绘制了各个变量的subplot图,便于理解。有需要的话,后续再补充方波,三角波相关代码。
【代码】
clc
clear all
close all
%% 生成正弦波信号
f = 10000; % 信号频率,10kHz
max_time = 0.04; % 波形绘制的最大时长为40ms
sample_per_period = 25; % 每个周期25pts
A = 1; % 振幅
phrase = 0; % 相位
vertical_offset = 0; % 垂直偏移
T = 1/f; % 信号周期,0.1ms
dt = T/sample_per_period; % dt表示采样信号周期(采样信号频率为25*f)
N = max_time/dt; % 40ms数据共计10000个点,离散化40ms连续时间
x = 0:dt:(N-1)*dt; % x为1*N的矩阵,表示离散时间序列
w = 2*pi*f; % 频率,rad/s
sin_wave = A*sin(w*x+phrase)+vertical_offset; % sin_wave为1*N的矩阵,表示正弦波各采样时间点上对应的正弦信号幅度信息
figure(1);
subplot(321);
plot(x,sin_wave);
title('sin\_wave');
xlabel('x/s');
ylabel('y/V');
grid on;
subplot(323);
plot(x,sin_wave,'.','color','r');
axis([0 0.001 -inf inf]);
title('sin\_wave');
xlabel('x/s');
ylabel('y/V');
grid on;
subplot(325);
plot(x,sin_wave,'-','color','b');
axis([0 0.001 -inf inf]);
title('sin\_wave');
xlabel('x/s');
ylabel('y/V');
grid on;
%% 量化位宽
width = 16; % 数据宽度16位
% width = 8; % 数据宽度8位
%% 量化滤波器系数
% 量化正弦波形数据并取整
wave = sin_wave;
sin_data = round(wave .* (2^(width-1) - 1)); % 1*N的幅度矩阵,对0-A的幅度均匀量化到0-2^(width-1)的范围上
subplot(322);
plot(sin_data,'.','color','r');
axis([0 100 -inf inf]);
title('sin\_data');
grid on;
data_com_sin = zeros(1,length(sin_data));
for i = 1:length(sin_data)
if sin_data(i) >= 0
data_com_sin(i) = sin_data(i); % 幅度为正
else
data_com_sin(i) = 2^width + sin_data(i); % 幅度为负,求补码,十进制表示
end
end
subplot(324);
plot(data_com_sin,'.');
axis([0 100 0 inf]);
title('data\_com\_sin');
grid on;
data_bin = dec2bin(data_com_sin); % 十进制转二进制,最高位表示符号位
% data_bin = dec2hex(data_com_sin); % 十进制转十六进制
- 代码附图:
- 选中变量,右键打开变量即可查看。