-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathAdcManager.py
44 lines (39 loc) · 1.47 KB
/
AdcManager.py
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
import busio
import board
import adafruit_ads1x15.ads1115 as ADS
from adafruit_ads1x15.ads1x15 import Mode
from adafruit_ads1x15.analog_in import AnalogIn
import csv
import traceback
import time
class AdcManager(object):
def __init__(self, csv_file_name=None):
self.i2c = busio.I2C(board.SCL, board.SDA, frequency=400000)
self.ads = ADS.ADS1115(self.i2c, data_rate=860, mode=Mode.CONTINUOUS)
self.chan = AnalogIn(self.ads, ADS.P0)
self.save_csv = not (csv_file_name is None)
self.csv_file_name = csv_file_name
self.csv_file = None
self.csv_writer = None
self.volts = -42.0 # error code
def __enter__(self):
if self.save_csv:
with open(self.csv_file_name,'w') as fd:
writer = csv.writer(fd)
writer.writerow(["pi_time", "voltage", "test_duration"])
self.csv_file = open(self.csv_file_name,'a').__enter__()
self.csv_writer = csv.writer(self.csv_file)
return self
def __exit__(self, etype, value, tb):
""" Closes the file properly """
if self.save_csv:
self.csv_file.__exit__(etype, value, tb)
if not (etype is None):
traceback.print_exception(etype, value, tb)
def update(self):
t0=time.time()
self.volts = self.chan.voltage
dur = time.time()-t0
if self.save_csv:
self.csv_writer.writerow([time.time(),self.volts, dur])
return self.volts