一. 脚本功能
- 根据采样点数,采样周期数等参数以及波形的数学表达式,生成任意波形
- 将波形数据转为指定位宽的二进制补码,然后存为txt
- 绘制原始波形和转换为二进制补码后的波形,验证转换是否正确
二. 使用效果
三. 代码分享
'''
Author : Xu Dakang
Email : XudaKang_up@qq.com
Date : 2021-11-19 19:12:31
LastEditors : Xu Dakang
LastEditTime : 2021-11-21 21:36:19
Filename :
Description :
'''
'''
模块功能:
1.根据采样点数,采样周期数等参数以及波形的数学表达式,生成任意波形
2.将波形数据转为指定位宽的二进制补码,然后存为txt
3.绘制原始波形和转换为二进制补码后的波形,验证转换是否正确
'''
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.pylab import mpl
mpl.rcParams['font.sans-serif'] = ['SimHei']
mpl.rcParams['axes.unicode_minus'] = False
import mplcursors
import time
now_time = time.strftime("%Y%m%d-%H%M%S", time.localtime(time.time()))
import myBin2dec2hex
file_name = 'waveform-' + now_time
N = 250
TNUM = 10
BIT_WIDTH = 24
f = 0.5
t0 = np.linspace(0, 1 / f, N)
pi = np.pi
y0 = np.sin(2 * pi * f * t0) + np.sin(2 * pi * f * 2 * t0)
x0_tnum = []
y0_tnum = []
y0_bit_tnum = []
for i in range(TNUM):
for j in t0:
x0_tnum.append(j + i * 1 / f)
for k in y0:
y0_tnum.append(k)
plt.figure(1)
plt.subplot(2, 1, 1)
plt.plot(x0_tnum, y0_tnum)
plt.grid()
plt.title('原始波形,最小频率 = ' + str(f) + '对应周期为' + str(1/f)
+ ',周期数 = ' + str(TNUM) + ',采样频率 = ' + str(f * N))
mplcursors.cursor()
y0_bit = np.int0((2**(BIT_WIDTH - 1) - 1) * y0 / max(abs(y0)))
y0_bit_tnum = []
for i in range(TNUM):
for j in y0_bit:
y0_bit_tnum.append(j)
fotxt = ''
fo = open(file_name + '.txt', 'w', encoding='utf8')
for dec_num in y0_bit_tnum:
fotxt += myBin2dec2hex.signed_dec2bin(dec_num, BIT_WIDTH)[2:] + '\n'
fo.write(fotxt[:-1])
print('生成' + file_name + '.txt文件成功!')
fo.close()
fi = open(file_name + '.txt', 'r', encoding='utf8')
y_out = []
for line in fi.readlines():
y_out.append(myBin2dec2hex.signed_bin2dec(line))
fi.close()
x_out = list(range(len(x0_tnum)))
plt.figure(1)
plt.subplot(2, 1, 2)
plt.plot(x_out, y_out)
plt.grid()
plt.title('先转二进制补码再转10进制后波形, 相当于十进制值乘以2^' + str(BIT_WIDTH - 1) + ' - 1即'
+ str('{:e}'.format(2**(BIT_WIDTH - 1) - 1)))
mplcursors.cursor()
plt.show()
|