make ads111x threadsafe

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