Repository navigation
Expand file tree
/
Copy pathtds2002c.py
More file actions
181 lines (157 loc) · 5.19 KB
/
Copy pathtds2002c.py
File metadata and controls
181 lines (157 loc) · 5.19 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
"""
POC to use Tektronix TDS2002C from remote computer
via USB and the VISA thing
"""
import pyvisa
import time
import numpy as np
from pathlib import Path
def connect():
rm = pyvisa.ResourceManager()
inst = rm.open_resource("ASRL/dev/ttyS1::INSTR")
inst.timeout = 50000 # time in ms
try:
idn = inst.query("*IDN?")
except:
print("Could not open device. Try:")
print(rm.list_resources())
print("Connected to:")
print(idn)
test_error(inst)
return(inst)
def test_error(inst):
err = inst.query("*ESR?")
try:
err = int(err)
except:
raise IOError(f"Invalid error code {err}")
if err != 0:
print(f"Error code {err}")
def set_up_scale(inst, time_div=500e-6, volt_div=5, trig_level=2.5):
inst.write("FACTORY")
inst.write(f"CH1:VOLTS {volt_div}")
inst.write(f"HOR:MAIN:SCALE {time_div}")
inst.write("TRIG:MAIN:LEVEL {trig_level}")
def exec_capture(inst):
inst.write("ACQUIRE:STOPAFTER SEQUENCE")
inst.write("ACQUIRE:STATE ON")
print(inst.query("*OPC?"))
def retrieve_measure(inst):
test_error(inst)
metadata = dict()
inst.write("MEASU:IMMED:TYPE MEAN")
val = inst.query("MEASU:IMMED:VALUE?")
print(val)
val = val.split(" ")[1].rstrip()
metadata["mean"] = float(val)
inst.write("MEASU:IMMED:TYPE FREQ")
val = inst.query("MEASU:IMMED:VALUE?")
val = val.split(" ")[1].rstrip()
metadata["freq"] = float(val)
test_error(inst)
inst.write("CURVE?")
values = inst.read_raw()
# Remove ":CURVE #42500"
# TODO find a better separator?
if b'00' in values:
value = values[13::]
value = value[:-1]
data = np.frombuffer(value, dtype='b')
# Print all measurement parameters
print("Measurement params:")
print(inst.query("WFMPRE?"))
# Retrieve info about values
# Xaxis * XINCR
xincr = inst.query("WFMP:XINCR?")
xincr = xincr.split(" ")[1]
xincr = float(xincr)
metadata["xincr"] = xincr
# Yaxis * YMULT
ymult = inst.query("WFMP:YMULT?")
ymult = ymult.split(" ")[1]
ymult = float(ymult)
metadata["ymult"] = ymult
# Number of points
nrpt = inst.query("WFMP:NR_P?")
nrpt = nrpt.split(" ")[1]
nrpt = int(nrpt)
# Description
val = inst.query("WFMP:WFID?")
val = val[13::]
val = val.replace('"', "")
metadata["description"] = val
if len(value) != nrpt:
raise IOError("Number of samples retrieved do not match")
time_val = np.arange(0, nrpt * xincr, xincr) - (nrpt * xincr / 2)
data = data * ymult
# Export data
fulldata = np.concatenate([time_val[:, np.newaxis], data[:, np.newaxis]], axis=1)
return(fulldata, metadata)
def retrieve_cursors(inst):
val = inst.query("CURSOR?")
print(val)
val = inst.query("CURSOR:FUNCTION?")
if val.find("VBARS") > -1:
is_vertical = True
val1 = inst.query("CURSOR:VBARS:POSITION1?")
val2 = inst.query("CURSOR:VBARS:POSITION2?")
elif val.find("HBARS") > -1:
is_vertical = False
val1 = inst.query("CURSOR:HBARS:POSITION1?")
val2 = inst.query("CURSOR:HBARS:POSITION2?")
else:
return None
val1 = val1.split(" ")[1]
val2 = val2.split(" ")[1]
try:
val1 = float(val1)
val2 = float(val2)
except:
print("Invalid cursor values")
return None
ret = {"is_vertical": is_vertical, "v1": val1, "v2": val2}
return(ret)
def save_data(fulldata, metadata, filename="oscillo", allscreen=True,
cursors=None):
np.savetxt(f"{filename}.csv", fulldata, delimiter=",",
header=f"""{metadata["description"]}\ntime (s), voltage (v)""")
if cursors is not None:
with open(f"{filename}_cursors.txt", "w") as myfile:
myfile.write(str(cursors))
# Loading saved data
#newdata = np.loadtxt(f"{filename}.csv", delimiter=",")
# Plot
from matplotlib import pyplot as plt
plt.plot(fulldata[:,0], fulldata[:,1])
plt.xlabel("Time (s)")
plt.ylabel("Voltage (V)")
if cursors is not None:
if cursors["is_vertical"]:
plt.axvline(x=cursors["v1"])
plt.axvline(x=cursors["v2"])
textstr = "Cursor dt = {} s".format(abs(cursors["v2"] - cursors["v1"]))
else:
plt.axhline(y=cursors["v1"])
plt.axhline(y=cursors["v2"])
textstr = "Cursor dv = {} V".format(abs(cursors["v2"] - cursors["v1"]))
plt.text(0.02, 0.02, textstr, fontsize=10, transform=plt.gcf().transFigure)
plt.title(metadata["description"])
if allscreen:
ymax = metadata["ymult"] * 25 * 4
plt.ylim(-ymax, ymax)
plt.grid()
plt.savefig(f"{filename}.png")
if __name__ == "__main__":
inst = connect()
#set_up_scale(inst, time_div=500e-6, volt_div=5, trig_level=2.5)
#exec_capture(inst)
data, metadata = retrieve_measure(inst)
cursors = retrieve_cursors(inst)
filename_root = "oscillo"
filename_num = 1
filename = f"{filename_root}{filename_num}"
while Path(filename + ".csv").exists():
filename_num += 1
filename = f"{filename_root}{filename_num}"
print(f"Creating file {filename}")
save_data(data, metadata, filename=filename, cursors=cursors)