forked from fossasia/pslab-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathoscilloscope.py
More file actions
383 lines (322 loc) · 14.1 KB
/
oscilloscope.py
File metadata and controls
383 lines (322 loc) · 14.1 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
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
"""Classes and functions related to the PSLab's oscilloscope instrument.
Example
-------
>>> from PSL.oscilloscope import Oscilloscope
>>> scope = Oscilloscope()
>>> x, y1, y2, y3, y4 = scope.capture(channels=4, samples=1600, timegap=2)
"""
import time
from typing import Tuple, Union
import numpy as np
import PSL.commands_proto as CP
from PSL import achan, packet_handler
class Oscilloscope:
"""Capture varying voltage signals on up to four channels simultaneously.
Parameters
----------
device : :class:`Handler`, optional
Serial interface for communicating with the PSLab device. If not provided, a
new one will be created.
Attributes
----------
channel_one_map : str
Remap the first sampled channel. The default value is "CH1".
trigger_enabled
"""
MAX_SAMPLES = 10000
CH234 = ["CH2", "CH3", "MIC"]
def __init__(self, device: packet_handler.Handler = None):
self._device = packet_handler.Handler() if device is None else device
self._channels = {
a: achan.AnalogInput(a, self._device) for a in achan.ANALOG_CHANNELS
}
self.channel_one_map = "CH1"
self._trigger_voltage = 0
self._trigger_enabled = False
self._trigger_channel = "CH1"
def capture(
self,
channels: int,
samples: int,
timegap: float,
) -> np.ndarray:
"""Capture an oscilloscope trace from the specified input channels.
This is a blocking call.
Parameters
----------
channels : {1, 2, 4}
Number of channels to sample from simultaneously. By default, samples are
captured from CH1, CH2, CH3 and MIC. CH1 can be remapped to any other
channel (CH2, CH3, MIC, CAP, RES, VOL) by setting the channel_one_map
attribute of the Oscilloscope instance to the desired channel.
samples : int
Number of samples to fetch. Maximum 10000 divided by number of channels.
timegap : float
Time gap between samples in microseconds. Will be rounded to the closest
1 / 8 µs. The minimum time gap depends on the type of measurement:
+--------------+------------+----------+------------+
| Simultaneous | No trigger | Trigger | No trigger |
| channels | (10-bit) | (10-bit) | (12-bit) |
+==============+============+==========+============+
| 1 | 0.5 µs | 0.75 µs | 1 µs |
+--------------+------------+----------+------------+
| 2 | 0.875 µs | 0.875 µs | N/A |
+--------------+------------+----------+------------+
| 4 | 1.75 µs | 1.75 µs | N/A |
+--------------+------------+----------+------------+
Sample resolution is set automatically based on the above limitations; i.e.
to get 12-bit samples only one channel may be sampled, there must be no
active trigger, and the time gap must be 1 µs or greater.
Example
-------
>>> from PSL.oscilloscope import Oscilloscope
>>> scope = Oscilloscope()
>>> x, y = scope.capture(1, 3200, 1)
Returns
-------
numpy.ndarray
(:channels:+1)-dimensional array with timestamps in the first dimension
and corresponding voltages in the following dimensions.
Raises
------
ValueError
If :channels: is not 1, 2 or 4, or
:samples: > 10000 / :channels:, or
:channel_one_map: is not one of CH1, CH2, CH3, MIC, CAP, RES, VOL, or
:timegap: is too low.
"""
xy = np.zeros([channels + 1, samples])
xy[0] = self.capture_nonblocking(channels, samples, timegap)
time.sleep(1e-6 * samples * timegap + 0.01)
while not self.progress()[0]:
pass
active_channels = ([self.channel_one_map] + self.CH234)[:channels]
for e, c in enumerate(active_channels):
xy[e + 1] = self.fetch_data(c)
return xy
def capture_nonblocking(
self, channels: int, samples: int, timegap: float
) -> np.ndarray:
"""Tell the pslab to start sampling the specified input channels.
This method is identical to
:meth:`capture <PSL.oscilloscope.Oscilloscope.capture>`,
except it does not block while the samples are being captured. Collected
samples must be manually fetched by calling
:meth:`fetch_data<PSL.oscilloscope.Oscilloscope.fetch_data>`.
Parameters
----------
See :meth:`capture <PSL.oscilloscope.Oscilloscope.capture>`.
Example
-------
>>> import time
>>> from PSL.oscilloscope import Oscilloscope
>>> scope = Oscilloscope()
>>> x = scope.capture_nonblocking(1, 3200, 1)
>>> time.sleep(3200 * 1e-6)
>>> y = scope.fetch_data("CH1")
Returns
-------
numpy.ndarray
One-dimensional array of timestamps.
Raises
------
See :meth:`capture <PSL.oscilloscope.Oscilloscope.capture>`.
"""
self._check_args(channels, samples, timegap)
timegap = int(timegap * 8) / 8
self._capture(channels, samples, timegap)
return timegap * np.arange(samples)
def _check_args(self, channels: int, samples: int, timegap: float):
if channels not in (1, 2, 4):
raise ValueError("Number of channels to sample must be 1, 2, or 4.")
max_samples = self.MAX_SAMPLES // channels
if not 0 < samples <= max_samples:
e1 = f"Cannot collect more than {max_samples} when sampling from "
e2 = f"{channels} channels."
raise ValueError(e1 + e2)
min_timegap = self._lookup_mininum_timegap(channels)
if timegap < min_timegap:
raise ValueError(f"timegap must be at least {min_timegap}.")
if self.channel_one_map not in self._channels:
e1 = f"{self.channel_one_map} is not a valid channel. "
e2 = f"Valid channels are {list(self._channels.keys())}."
raise ValueError(e1 + e2)
def _lookup_mininum_timegap(self, channels: int) -> float:
channels_idx = {
1: 0,
2: 1,
4: 2,
}
min_timegaps = [[0.5, 0.75], [0.875, 0.875], [1.75, 1.75]]
return min_timegaps[channels_idx[channels]][self.trigger_enabled]
def _capture(self, channels: int, samples: int, timegap: float):
self._invalidate_buffer()
chosa = self._channels[self.channel_one_map].chosa
self._channels[self.channel_one_map].resolution = 10
self._device.send_byte(CP.ADC)
CH123SA = 0 # TODO what is this?
chosa = self._channels[self.channel_one_map].chosa
self._channels[self.channel_one_map].samples_in_buffer = samples
self._channels[self.channel_one_map].buffer_idx = 0
if channels == 1:
if self.trigger_enabled:
self._device.send_byte(CP.CAPTURE_ONE)
self._device.send_byte(chosa | 0x80) # Trigger
elif timegap >= 1:
self._channels[self.channel_one_map].resolution = 12
self._device.send_byte(CP.CAPTURE_DMASPEED)
self._device.send_byte(chosa | 0x80) # 12-bit mode
else:
self._device.send_byte(CP.CAPTURE_DMASPEED)
self._device.send_byte(chosa) # 10-bit mode
elif channels == 2:
self._channels["CH2"].resolution = 10
self._channels["CH2"].samples_in_buffer = samples
self._channels["CH2"].buffer_idx = 1 * samples
self._device.send_byte(CP.CAPTURE_TWO)
self._device.send_byte(chosa | (0x80 * self.trigger_enabled))
else:
for e, c in enumerate(self.CH234):
self._channels[c].resolution = 10
self._channels[c].samples_in_buffer = samples
self._channels[c].buffer_idx = (e + 1) * samples
self._device.send_byte(CP.CAPTURE_FOUR)
self._device.send_byte(
chosa | (CH123SA << 4) | (0x80 * self.trigger_enabled)
)
self._device.send_int(samples)
self._device.send_int(int(timegap * 8)) # 8 MHz clock
self._device.get_ack()
def _invalidate_buffer(self):
for c in self._channels.values():
c.samples_in_buffer = 0
c.buffer_idx = None
def fetch_data(self, channel: str) -> np.ndarray:
"""Fetch samples captured from specified channel.
Parameters
----------
channel : {'CH1', 'CH2', 'CH3', 'MIC', 'CAP', 'RES', 'VOL'}
Name of the channel from which to fetch captured data.
Example
-------
>>> from PSL.oscilloscope import Oscilloscope
>>> scope = Oscilloscope()
>>> scope.capture_nonblocking(channels=2, samples=1600, timegap=1)
>>> y1 = scope.fetch_data("CH1")
>>> y2 = scope.fetch_data("CH2")
Returns
-------
numpy.ndarray
One-dimensional array holding the requested voltages.
"""
data = bytearray()
channel = self._channels[channel]
samples = channel.samples_in_buffer
for i in range(int(np.ceil(samples / CP.DATA_SPLITTING))):
self._device.send_byte(CP.COMMON)
self._device.send_byte(CP.RETRIEVE_BUFFER)
offset = channel.buffer_idx + i * CP.DATA_SPLITTING
self._device.send_int(offset)
self._device.send_int(CP.DATA_SPLITTING) # Ints to read
# Reading int by int sometimes causes a communication error.
data += self._device.read(CP.DATA_SPLITTING * 2)
self._device.get_ack()
data = [CP.ShortInt.unpack(data[s * 2 : s * 2 + 2])[0] for s in range(samples)]
return channel.scale(np.array(data))
def progress(self) -> Tuple[bool, int]:
"""Return the status of a capture call.
Returns
-------
bool, int
A boolean indicating whether the capture is complete, followed by the
number of samples currently held in the buffer.
"""
self._device.send_byte(CP.ADC)
self._device.send_byte(CP.GET_CAPTURE_STATUS)
conversion_done = self._device.get_byte()
samples = self._device.get_int()
self._device.get_ack()
return bool(conversion_done), samples
def configure_trigger(self, channel: str, voltage: float, prescaler: int = 0):
"""Configure trigger parameters for 10-bit capture routines.
The capture routines will wait until a rising edge of the input signal crosses
the specified level. The trigger will timeout within 8 ms, and capture will
start regardless.
To disable the trigger after configuration, set the trigger_enabled attribute
of the Oscilloscope instance to False.
Parameters
----------
channel : {'CH1', 'CH2', 'CH3', 'MIC', 'CAP', 'RES', 'VOL'}
The name of the trigger channel.
voltage : float
The trigger voltage in volts.
prescaler : int, optional
The default value is 0.
Examples
--------
>>> from PSL.oscilloscope import Oscilloscope
>>> scope = Oscilloscope()
>>> scope.configure_trigger(channel='CH1', voltage=1.1)
>>> xy = scope.capture(channels=1, samples=800, timegap=2)
>>> diff = abs(xy[1, 0] - 1.1) # Should be small unless a timeout occurred.
Raises
------
TypeError
If the trigger channel is set to a channel which cannot be sampled.
"""
self._trigger_channel = channel
if channel == self.channel_one_map:
channel = 0
elif channel in self.CH234:
channel = self.CH234.index(channel) + 1
elif self.channel_one_map == "CH1":
e = f"Cannot trigger on {channel} unless it is remapped to CH1."
raise TypeError(e)
else:
e = f"Cannot trigger on CH1 when {self.channel_one_map} is mapped to CH1."
raise TypeError(e)
self._device.send_byte(CP.ADC)
self._device.send_byte(CP.CONFIGURE_TRIGGER)
# Trigger channel (4lsb) , trigger timeout prescaler (4msb)
self._device.send_byte((prescaler << 4) | (1 << channel)) # TODO prescaler?
level = self._channels[self._trigger_channel].unscale(voltage)
self._device.send_int(level)
self._device.get_ack()
self._trigger_enabled = True
@property
def trigger_enabled(self) -> bool:
"""Activate or deactivate a trigger set by :meth:`configure_trigger`.
Becomes True automatically when calling :meth:`configure_trigger`.
If trigger_enabled is set to True without first calling
:meth:`configure_trigger`, the trigger will be configured with a trigger
voltage of 0 V on CH1.
"""
return self._trigger_enabled
@trigger_enabled.setter
def trigger_enabled(self, value: bool):
self._trigger_enabled = value
if self._trigger_enabled:
self.configure_trigger(self._trigger_channel, self._trigger_voltage)
def select_range(self, channel: str, voltage_range: Union[int, float]):
"""Set appropriate gain automatically.
Setting the right voltage range will result in better resolution.
Parameters
----------
channel : {'CH1', 'CH2'}
Channel on which to apply gain.
voltage_range : {16, 8, 4, 3, 2, 1.5, 1, .5}
Examples
--------
>>> from PSL.oscilloscope import Oscilloscope
>>> scope = Oscilloscope()
>>> scope.select_range('CH1', 8)
# Gain set to 2x on CH1. Voltage range ±8 V.
"""
ranges = [16, 8, 4, 3, 2, 1.5, 1, 0.5]
if voltage_range in ranges:
idx = ranges.index(voltage_range)
gain = achan.GAIN_VALUES[idx]
self._channels[channel].gain = gain
else:
e = f"Invalid range: {voltage_range}. Valid ranges are {ranges}."
raise ValueError(e)