40 lines
1.2 KiB
Python
Executable File
40 lines
1.2 KiB
Python
Executable File
#!/usr/bin/env python3
|
|
"""Averaged power spectrum of a raw rtl_sdr u8 IQ capture.
|
|
|
|
Usage: iq_spectrum.py iq.raw [sample_rate] [seconds]
|
|
Prints a coarse ASCII spectrum and the top peaks.
|
|
"""
|
|
import sys
|
|
import numpy as np
|
|
|
|
path = sys.argv[1]
|
|
fs = int(sys.argv[2]) if len(sys.argv) > 2 else 1_600_000
|
|
secs = float(sys.argv[3]) if len(sys.argv) > 3 else 5.0
|
|
|
|
NFFT = 4096
|
|
acc = np.zeros(NFFT)
|
|
count = 0
|
|
with open(path, "rb") as f:
|
|
raw = f.read(int(fs * 2 * secs))
|
|
buf = np.frombuffer(raw, dtype=np.uint8).astype(np.float32) - 127.5
|
|
iq = buf[0::2] + 1j * buf[1::2]
|
|
n = (len(iq) // NFFT) * NFFT
|
|
iq = iq[:n].reshape(-1, NFFT)
|
|
win = np.hanning(NFFT)
|
|
for row in iq[:2000]:
|
|
sp = np.fft.fftshift(np.abs(np.fft.fft(row * win)) ** 2)
|
|
acc += sp
|
|
count += 1
|
|
db = 10 * np.log10(acc / count + 1e-9)
|
|
freqs = np.fft.fftshift(np.fft.fftfreq(NFFT, 1 / fs))
|
|
|
|
# collapse to 64 bins for display
|
|
B = 64
|
|
cb = db[: (NFFT // B) * B].reshape(B, -1).max(axis=1)
|
|
lo, hi = cb.min(), cb.max()
|
|
print(f"spectrum dB range: {lo:.1f} .. {hi:.1f} (span {hi-lo:.1f} dB)")
|
|
for i, v in enumerate(cb):
|
|
bar = "#" * int(max(0, (v - lo) / max(1e-9, hi - lo) * 60))
|
|
fk = freqs[i * (NFFT // B)] / 1e3
|
|
print(f"{fk:+8.0f} kHz |{bar}")
|