**EDIT: I am receiving the following error message:*
"Error retrieving accessibility bus address: or.freedesktop.DBus.Error.ServiceUnknown: The name org.a11y.Bus was not provided by any .service files"
I wrote code for the PC platform using Python and it works just fine. I was looking to have this program run on a rasberry pi connected to a monitor.
I installed Raspbian and all of the libraries for the above needed functions.
The code is as follows:
############################################################
# Visualizing data from the Arduino serial monotor #
# and creating a graph in a nice format. Later work will #
# look into outputting this to a Android device #
############################################################
############################################################
############################################################
############################################################
#Becuase we can always use more time
import time
#Inport the fancy plotting library
import matplotlib.pyplot as plt
#Inport the serial library
import serial
#We want to do array math so we need Numpy
import numpy
#We also want to draw things so we need drawnow and
#everything that comes with it
from drawnow import *
############################################################
############################################################
#Creating an array to hold data for plotting. See several
#lines below for more information
tempArray = []
pressureArray = []
altitudeArray = []
#The object that is created to interact with the Serial Port
arduinoSerialInput = serial.Serial('/dev/ttyACM0', 230400)
time.sleep(3)
#Here we set the definition oto look for interactive mode
#and plot live data
plt.ion()
############################################################
############################################################
clippingCounter = 0
#Here we define a function to make a plot, or figure of
#the data aquired
def plotTempData():
plt.ylim(150,320)
plt.title('Plots from data of the BMP Sensor')
plt.grid(True)
plt.ylabel('Tempature')
plt.subplot(2, 2, 1)
plt.plot(tempArray, 'ro-', label='Degrees K', linewidth=2)
plt.legend(loc='upper left')
#plt2 = plt.twinx()
#plt2.plot(pressureArray, 'bx-')
def plotPresData():
#plt.ylim(260,320)
plt.title('Plots from data of the BMP Sensor')
plt.grid(True)
plt.ylabel('Pressure')
plt.subplot(2, 2, 2)
plt.plot(pressureArray, 'bo-', label='Pascals', linewidth=2)
plt.legend(loc='upper left')
plt.plot(pressureArray, 'bo-')
plt.show()
############################################################
############################################################
while (1==1):
#First things first, lets wait for data prior to reading
if (arduinoSerialInput.inWaiting()>0):
myArduinoData = arduinoSerialInput.readline()
# print myArduinoData -Line commented out, see below
#The arduino should be set up to proovide one string of data
#from here we will seperate that one string into two or more
#to make it easier to plot
#This will create an array seperated by the comma
#we specified in the Arduino IDE aasign it to a
#variable of our choice and convert the string
#back into a number using the float command
dataArray = myArduinoData.split(',')
temp = float(dataArray[0])
pressure = float(dataArray[1])
#Used to test the printing of values to output
#print temp, " , ", pressure, " , ", altitude
#We need to create an array to to hold the values in question
#Looking at the top, you will see the empty array we need to
#create that will hold the values we need to plot
tempArray.append(temp)
pressureArray.append(pressure)
plt.figure(1)
drawnow(plotTempData)
plt.pause(.000001)
#plt.figure(2)
drawnow(plotPresData)
plt.pause(.000001)
#We want to clip some data off since the graph keeps
#expanding and too many points are building up.
clippingCounter = clippingCounter + 1
if(clippingCounter>50):
tempArray.pop(0)
pressureArray.pop(0)
############################################################
############################################################
The error you mentioned is I believe an issue with 'at-spi2-core' module. The problem seems fixed on Ubuntu version 2.9.90-0ubuntu2, have you tried to upgrade the 'at-spi2-core' module? Alternatively forcing it to be enabled might solve your issue.
Information on ensuring the SPI is enabled is here :
http://www.raspberrypi-spy.co.uk/2014/08/enabling-the-spi-interface-on-the-raspberry-pi/
Would have added this in a comment as I am not 100% on this but I don't have the rep for that.
Related
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()
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
I am currently making a project which requires real time monitoring of various quantities like temperature, pressure, humidity etc. I am following a approach of making individual arrays of all the sensors and ploting a graph using matplotlib and drwnow.
HOST = "localhost"
PORT = 4223
UID1 = "tsJ" # S1
from tinkerforge.ip_connection import IPConnection
from tinkerforge.bricklet_ptc import BrickletPTC
import numpy as np
import serial
import matplotlib
from matplotlib.ticker import ScalarFormatter, FormatStrFormatter
import matplotlib.pyplot as plt
from matplotlib import style
style.use('ggplot')
from drawnow import *
# creating arrays to feed the data
tempC1 = []
def makeafig():
# creating subplots
fig1 = plt.figure(1)
a = fig1.add_subplot(111)
#setting up axis label, auto formating of axis and title
a.set_xlabel('Time [s]', fontsize = 10)
a.set_ylabel('Temperature [°C]', fontsize = 10)
y_formatter = matplotlib.ticker.ScalarFormatter(useOffset=False)
a.yaxis.set_major_formatter(y_formatter)
title1 = "Current Room Temperature (Side1): " + str(temperature1/100) + " °C"
a.set_title(title1, fontsize = 10)
#plotting the graph
a.plot(tempC1, "#00A3E0")
#saving the figure
fig1.savefig('RoomTemperature.png', dpi=100)
while True:
ipcon = IPConnection() # Create IP connection
ptc1 = BrickletPTC(UID1, ipcon) # S1
ipcon.connect(HOST, PORT) # Connect to brickd
#setting the temperature from PTC bricklet
temperature1 = ptc1.get_temperature()
#processing data from a temperature sensor to 1st array
dataArray1=str(temperature1/100).split(',')
temp1 = float(dataArray1[0])
tempC1.append(temp1)
#making a live figure
drawnow(makeafig)
plt.draw()
This is the approach I found good on the internet and it is working. The only problem I am facing is It consumes more time if I made more arrays for other sensors and the plot being made lags from the real time when I compare it with a stopwatch.
Is there any good and efficient approach for obtaining live graphs that will be efficient with lot of sensors and doen't lag with real time.
Or any command to clear up the already plotted array values?
I'd be obliged if anyone can help me with this problem.
I'd like to ask that, does filling data in arrays continuosly makes the process slow or is it my misconception?
That one is easy to test; creating an empty list and appending a few thousand values to it takes roughly 10^-4 seconds, so that shouldn't be a problem. For me somewhat surprisingly, it is actually faster than creating and filling a fixed size numpy.ndarray (but that is probably going to depend on the size of the list/array).
I quickly played around with your makeafig() function, placing a = fig1.add_subplot(111) up to (including) a.plot(..) in a simple for i in range(1,5) loop, with a = fig1.add_subplot(2,2,i); that makes makeafig() about 50% slower, but differences are only about 0.1-0.2 seconds. Is that in line with the lag that you are experiencing?
That's about what I can test without the real data, my next step would be to time the part from ipcon=.. to temperature1=... Perhaps the bottleneck is simply the retrieval of the data? I'm sure that there are several examples on SO on how to time parts of Python scripts, for these kind of problems something like the example below should be sufficient:
import time
t0 = time.time()
# do something
dt = time.time() - t0
I am trying to plot some reference lines say x=1 and x=3 and to label each of those lines in the figure beside the line. I am aware this can be done by manually by specifying the position however for my case (I am plotting hundreds of these lines automatically) this is not plausible.
Is there a simple way to do this?
I have been trying to use a function found online with no luck.
Here is what I currently have: - filename contains a time series - Yan_S and Yan_T are both files containing values I want to plot and information for the associated labels.
################## DEFINE SPECTRAL PLOTTING ##################
# plot_spectra(filename, title, deltaT, taper_onoff)
# filename should include full path to .txt of amplitudes (no headers)
# title will be the title of the figure
# deltaT is the time smapling in seconds
# taper_onoff 1-on 0-off
# mode_label_onoff 1-on 0-off
def plot_spectra(filename, title, deltaT, mode_label_onoff):
signal = np.genfromtxt(filename)
time_vector = np.arange(signal.size)*deltaT
spectra = np.fft.rfft(signal) # implement taper
freq_mHz = np.fft.rfftfreq(time_vector.size, deltaT)*1.e3
plt.ylabel(r'$\sqrt{P}$')
plt.xlabel('mHz')
#plt.plot(freq_mHz, abs(spectra.real))
# PLOT MODE LABELS
if mode_label_onoff != 0:
Yan_S_Vals = Yan_S[4]
Yan_T_Vals = Yan_T[4]
Yan_S_Labels = ["" for x in range(len(Yan_S))]
Yan_T_Labels = ["" for x in range(len(Yan_S))]
for i in np.arange(0,len(Yan_S)):
Yan_S_Labels[i] = str(Yan_S[0][i])+'S'+str(Yan_S[2][i])
Yan_T_Labels[i] = str(Yan_S[0][i])+'S'+str(Yan_S[2][i])
# Spheroidal Modes
lineid_plot.plot_line_ids(freq_mHz, abs(spectra.real), Yan_S_Vals, Yan_S_Labels)
# Toroidal Modes
lineid_plot.plot_line_ids(freq_mHz, abs(spectra.real), Yan_T_Vals, Yan_T_Labels)
plt.xlim(0, 10)
#plt.savefig('/Users/Alex/Desktop/Python/'+title.split('.')[0]+'_spectra.svg')
plt.savefig('/Users/Alex/Desktop/Python/'+title.split('.')[0]+'_spectra.png')
plt.show()
plt.close('all')
Any help would be great!
I've written a simple GUI in python using pylabs and tkinter based on an example found here:
http://hardsoftlucid.wordpress.com/various-stuff/realtime-plotting/
used for sine wave generation.
Except I tweaked it to pull data through suds from a server on the internet. It's not working as I exactly anticipated as the GUI is somewhat slow. I think its due to the timer. I just started learning how to use matplotlib functions yesterday so I'm not aware of how every function works.
How can I speed it up? Right now the data comes in at 2-3 seconds which is fine, but I just want to increase the GUI responsiveness.
Here is my code:
import numpy as np
from matplotlib import pyplot as plt
plt.ion() # set plot to animated
url = "http://10.217.247.36/WSDL/v4.0/iLON100.WSDL"
client = Client(url, username='ilon', password='ilon', location = 'http://10.217.247.36/WSDL/iLON100.WSDL')
read = client.factory.create('ns0:E_xSelect')
read['xSelect'] = """//Item[starts-with(UCPTname, "Net/MB485/MAIN POWER/Fb/PowerSum")]"""
ydata = [0] * 50
ax1=plt.axes()
# make plot
line, = plt.plot(ydata)
plt.ylim([10,40])
# start data collection
while True:
x = client.service.Read(read).Item[0].UCPTvalue[0].value #data stream
x = float(x)
ymin = float(min(ydata))-10
ymax = float(max(ydata))+10
plt.ylim([ymin,ymax])
ydata.append(x)
del ydata[0]
line.set_xdata(np.arange(len(ydata)))
line.set_ydata(ydata) # update the data
plt.draw() # update the plot
I have a script that plots data of some photometry apertures, and I want to plot them in an xy plot. I am using matplotlib.pyplot with python 2.5.
The input data is stored in around 500 files and read. I am aware that this is not the most efficient way of inputting the data but that's another issue...
Example code:
import matplotlib.pyplot as plt
xcoords = []
ycoords = []
# lists are populated with data from first file
pltline, = plt.plot(xcoords, ycoords, 'rx')
# then loop populating the data from each file
for file in filelist:
xcoords = [...]
ycoords = [...]
pltline.set_xdata(xcoords)
pltline.set_ydata(ycoords)
plt.draw()
As there are over 500 files, I will occasionally want to close the animation window in the middle of the plotting. My code to plot works but it doesn't exit very gracefully. The plot window does not respond to clicking the close button and I have to Ctrl+C out of it.
Can anyone help me find a way to close the animation window while the script is running whilst looking graceful (well more graceful than a series of python traceback errors)?
If you update the data and do the draw in a loop, you should be able to interrupt it. Here's an example (that draws a stationary circle and then moves a line around the perimeter):
from pylab import *
import time
data = [] # make the data
for i in range(1000):
a = .01*pi*i+.0007
m = -1./tan(a)
x = arange(-3, 3, .1)
y = m*x
data.append((clip(x+cos(a), -3, 3),clip(y+sin(a), -3, 3)))
for x, y in data: # make a dynamic plot from the data
try:
plotdata.set_data(x, y)
except NameError:
ion()
fig = figure()
plot(cos(arange(0, 2.21*pi, .2)), sin(arange(0, 2.21*pi, .2)))
plotdata = plot(x, y)[0]
xlim(-2, 2)
ylim(-2, 2)
draw()
time.sleep(.01)
I put in the time.sleep(.01) command to be extra sure that I could break the run, but in my tests (running Linux) it wasn't necessary.