Friday, February 11, 2011

Arbitrary voltage source in LTSpice

Here is a post I found when searching for a way to use some data as an input to LTSpice to test a filter.

http://ltspicelabs.blogspot.com/2006/10/using-wav-files-for-io-and-transient.html

This talks about taking a .wav file as input. Which is fine if you are doing audio. But what if you want to generate a .wav file based on, say, a mathematical model?

Python has a nice wave module. So you could write a short script like this:

# Send data to output .wave file
# filename = string
# fsys = integer system clock rate
# data = list of integers
def writewave(filename, fsys, data):
oversample_factor = 8
offset_factor = 16384
scale_factor = 60 # 8 bit in to ~15 bit out

w = wave.open(filename, 'wb')
w.setnchannels(1)
w.setsampwidth(2)
w.setframerate(fsys * oversample_factor) # need to oversample to generate the steppy DAC output
w.setnframes(len(data))
d = '' # string to hold byte values in little-endian order
for i in data:
ii = scale_factor * i + offset_factor
rl = int(ii) & 255
rh = (int(ii) >> 8) & 255
for j in xrange(oversample_factor):
d = d + chr(rl) + chr(rh) # little-endian
w.writeframes(d)
w.close()

This will write out your data to a .wav file that can then be used in LTSpice. The example here has a sample width of 2, which would be two bytes, or signed 16 bits. I was modeling a signed 8-bit DAC output, so I scaled it up and offset it to get what I wanted. Also I put in an oversampling factor to get a more step-wise response instead of a linear ramp between sample points.

Don't forget "import wave" in the Python script!

No comments:

Post a Comment