1

Using the below python(ubuntu) code and rtlsdr, I am able to plot a graph. Can anyone please tell me how to modify this code to plot the graph continuously in real time?

from pylab import *
from rtlsdr import *    
sdr = RtlSdr()    
sdr.sample_rate = 2.4e6
sdr.center_freq = 93.5e6
sdr.gain = 50    
samples = sdr.read_samples(256*1024)
sdr.close()   
psd(samples.real, NFFT=1024, Fs=sdr.sample_rate/1e6, Fc=sdr.center_freq/1e6)
xlabel('Frequency (MHz)')
ylabel('Relative power (dB)')
show()
user3661448
  • 45
  • 1
  • 9

1 Answers1

0

Normally you can update a pyplot-generated plot by calling plot.set_xdata(), plot.set_ydata(), and plot.draw() (Dynamically updating plot in matplotlib), without having to recreate the entire plot. However, this only works for plots that directly draw a data series. The plot instance cannot automatically recalculate the spectral density calculated by psd().

You'll therefore need to call psd() again when you want to update the plot - depending on how long it takes to draw, you could do this in regular intervals of a second or less.

This might work:

from pylab import *
from rtlsdr import *
from time import sleep    
sdr = RtlSdr()    
sdr.sample_rate = 2.4e6
sdr.center_freq = 93.5e6
sdr.gain = 50    

try:
    while True: # run until interrupted
        samples = sdr.read_samples(256*1024)
        clf()
        psd(samples.real, NFFT=1024, Fs=sdr.sample_rate/1e6, Fc=sdr.center_freq/1e6)
        xlabel('Frequency (MHz)')
        ylabel('Relative power (dB)')
        show()
        sleep(1) # sleep for 1s
except:
    pass

sdr.close()

Edit: Of course, I'm not sure how read_samples runs; my example here assumed that it returns almost immediately. If it blocks for a long time while waiting for data, you may want to read less data at a time, and discard old data as you do so:

from collections import deque

max_size = 256*1024
chunk_size = 1024

samples = deque([], max_size)

while True:
    samples.extend(sdr.read_samples(chunk_size))

    # draw plot
Christoph Burschka
  • 4,467
  • 3
  • 16
  • 31
  • Thanks a lot Chirstoph Burschka, I was able to get the Plot only once, if i remove the show(), then the loop is continuous. Even if i didnt get the plot no problem, can you tell me how to calculate the power spectral density for a particular frequency say 93.5Mhz. After googling for long time i came to know that Power Spectral Density is the Fourier Transform of the autocorrelation function of a signal. First compute the auto correlation function and then compute its Fourier Transform. Thank you once again... – user3661448 Mar 29 '19 at 08:58
  • Not really, sorry. You may be able to get help on https://stats.stackexchange.com/ – Christoph Burschka Mar 29 '19 at 18:24