Python Forum
Help with applying this instrument monitoring code to multiple inputs.
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Help with applying this instrument monitoring code to multiple inputs.
#1
Hello, world.

I have some working code (below) that communicates with a pressure gauge, takes the reading, saves it to a log file, and displays a live plot.

I am hoping that someone is willing to help with rewriting it so that I can neatly apply it to my other gauges. Right now I have a single plot, and I output a log file with two columns (time and pressure). I think that what I want is to have a function inside the animation loop that takes in instrumentID and "Title" as inputs, and maybe add an argument to the whole script that tells it how many gauges I have and how to arrange the subplots. That last bit might be dumb though?

Extra credit (I would be super appreciative if you help with these, but don't feel that you need to, to help with the above):
1) I've seen in other forum posts that I should be using "return line," instead of plt.draw(), but I can't seem to get that to display my datetime axis properly, if it works at all. Should I change it to this? If so, how?
2) I'd like to add a header line to the log file. This has made me realize I have a problem, though. What happens if I start the program with (GaugeA, GaugeB, GaugeC), then close it and reopen later with (GaugeB, GaugeA, GaugeD). This seems like a serious problem.
3) Also, just in general, it should be obvious that I am a total n00b. I would appreciate comments on how to write this code better in general (e.g. variable naming, order of operations, etc)

My thanks in advance,
Mike

import visa
from datetime import datetime
import time
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation

fig, (ax1) = plt.subplots(1, 1)

#-------------------------------------------------------

date = datetime.today().strftime('%Y-%m-%d') + '.txt'
logfile = open(date,'a')                 # Create or open a log file with today's date

rm = visa.ResourceManager()                     # Open up the visa RM that looks for connected instruments
CapGauge = rm.open_resource('ASRL3::INSTR')     # Open up the specific instrument I care about
CapGauge.read_termination = '\r\n'              # Fix the terminations so that I get a response at all
CapGauge.write_termination = '\r\n'

#-------------------------------------------------------
x = []
y = []

def animate(i):                                             # This is the animation loop for my live plot
    current_time = datetime.now().strftime("%H:%M:%S")      # Format the date how I like it
    CapGauge.query('PR1')                                   # I send the query to the instrument asking for Pressue Reading on gauge 1
                                                            # The instrument then replies with "\x06\x13\x10" (ACKNOWLEDGE CR LF)
                                                            # Or, if reading is unsuccessful,  "\x15\x13\x10" (NEGATIVE ACKNOWLEDGE CR LF)
    tempstr = CapGauge.query('\x05')                        # Then I send the "\x05" (ENQUIRY) character

    if len(tempstr)>1:                                      # This catches the junk feedback lines that happen sometimes because I'm a bad programmer
        tempstr = tempstr.split(',')[1]                     # The gauge sends a string with format "a,sxx.xxxxEsxx"
                                                            # where a is a status integer, s is a sign, and sxx.xxxxEsxx is my pressure reading
        x.append(datetime.now().replace(microsecond=0))     # I strip away the microseconds here just coz they annoy me, but I keep the datetime format
        y.append(float(tempstr))                            # Turn the pressure reading string into a float
        logfile.write(current_time + '\t')                  # Write it to my log file as well
        logfile.write(tempstr + '\n')
        logfile.flush()                                     # Save my logfile so that I don't lose the data if something goes wrong
        ax1.clear()                                         # Clear the axes
        ax1.plot(x,y)                                       # Plot the data (including the newly appended point)
        ax1.set_title("Capacitance Manometer")              # Make the live plot look nice
        ax1.set_xlabel("Time")                              # Make the live plot look nice
        ax1.set_ylabel("Pressure (mbar)")                   # Make the live plot look nice
    time.sleep(0.5)                                         # Wait to take the next data point
    plt.draw()                                              # I admit I'm not at all clear on what plt.draw() does, vs ax1.plot() and plt.show()

anim = animation.FuncAnimation(fig, animate, frames = 200, interval = 20) # Do the animation
plt.show()                                                  # Show the plot

CapGauge.close()
logfile.close()
raise SystemExit
Reply


Messages In This Thread
Help with applying this instrument monitoring code to multiple inputs. - by Kid_Meier - Mar-03-2020, 01:22 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Multiple variable inputs when only one is called for ChrisDall 2 510 Oct-20-2023, 07:43 PM
Last Post: deanhystad
  Monitoring a Directory for new mkv and mp4 Files lastyle 3 1,686 May-07-2023, 12:33 PM
Last Post: deanhystad
  Code freez if more inputs kiko058 2 836 Mar-28-2023, 03:52 PM
Last Post: kiko058
  python multiple try except block in my code -- can we shorten code mg24 10 6,265 Nov-10-2022, 12:48 PM
Last Post: DeaD_EyE
  gspread - applying ValueRenderOption to a range of cells dwassner 0 1,716 Jan-12-2022, 03:05 PM
Last Post: dwassner
Lightbulb Multiple inputs on the same line (beginner) dementshuk 9 2,859 Sep-03-2021, 02:21 PM
Last Post: dementshuk
  Generate Multiple sql Files With csv inputs vkomarag 13 4,285 Aug-20-2021, 07:03 PM
Last Post: vkomarag
  monitoring the temperature of the CPU with Python apollo 2 8,865 Apr-13-2021, 05:39 PM
Last Post: apollo
  IoT Air Monitoring System project_science 0 1,946 Mar-26-2021, 08:14 PM
Last Post: project_science
  Applying function mapypy 1 2,288 Mar-11-2021, 09:49 PM
Last Post: nilamo

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020