make ads111x threadsafe

This commit is contained in:
Nikolay Khabarov
2017-06-18 15:20:19 +03:00
parent 10f92cdf0d
commit 87df112541

View File

@@ -3,6 +3,7 @@ import fcntl
import struct
import time
import atexit
import threading
ADS111x_ADDRESS = 0x48
I2C_SLAVE = 0x0703
@@ -10,6 +11,9 @@ I2C_SLAVE = 0x0703
# Initialize i2c interface and register it for closing on exit.
__i2c_dev = os.open("/dev/i2c-1", os.O_SYNC | os.O_RDWR)
# mutex for multi threading requests
lock = threading.Lock()
def __close():
os.close(__i2c_dev)
@@ -28,12 +32,14 @@ def measure(channel):
"""
Measure voltage on chip input.
Raises OSError(Errno 121) "Remote I/O error" on reading error.
Thread safe.
:param channel: chip channel to use.
:return: Voltage in Volts.
"""
global __i2c_dev
if channel < 0 or channel > 3:
raise ValueError("Wrong channel")
lock.acquire()
# configure
data = struct.pack(">BH",
0x01, # config register
@@ -50,6 +56,7 @@ def measure(channel):
# read result
os.write(__i2c_dev, struct.pack("B", 0x00)) # conversion register
v = struct.unpack(">h", os.read(__i2c_dev, 2))[0]
lock.release()
return v / 8000.0 # / 32768.0 * 4.096 according to specified range