]> defiant.homedns.org Git - pyshared.git/commitdiff
updated i2c.py
authorErik Andresen <erik@vontaene.de>
Tue, 27 Dec 2016 15:27:45 +0000 (16:27 +0100)
committerErik Andresen <erik@vontaene.de>
Tue, 27 Dec 2016 15:27:45 +0000 (16:27 +0100)
i2c.py

diff --git a/i2c.py b/i2c.py
index 2e9a109e0fe2891175726af4e6d739958e032208..2bb9f94026849106394d92e9f3210d7feff14de6 100755 (executable)
--- a/i2c.py
+++ b/i2c.py
@@ -5,10 +5,13 @@ import threading
 import inspect
 import os
 import logging
+import struct
+import fcntl
 from ctypes import *
 from time import sleep
 
 DEBUG=0
+I2C_FILENAME = "/dev/i2c-2"
 logger = logging.getLogger(__name__)
 
 class i2c:
@@ -31,9 +34,10 @@ class i2c:
                                        logger.warning("Error: (%s) I2C blocked %fs by %s!", parent, count*0.001, parent_owner)
                                i2c.__parent_owner = inspect.stack()[1]
                        i2c.__single = True
-               self.dev = i2c.libc.open("/dev/i2c-2", os.O_RDWR)
+               self.dev = i2c.libc.open(I2C_FILENAME, os.O_RDWR)
                if self.dev < 0:
                        raise IOError("open")
+               fcntl.flock(self.dev, fcntl.LOCK_EX)
                err = i2c.libc.ioctl(self.dev, i2c.I2C_SLAVE, addr>>1)
                if err < 0:
                        raise IOError("ioctl")
@@ -62,6 +66,23 @@ class i2c:
        def __del__(self):
                self.close()
 
+
+def i2c_write_reg(addr, reg, buf):
+       dev = i2c(addr)
+       s = struct.pack(">B", reg) + buf
+       dev.write(s)
+       dev.close()
+
+
+def i2c_read_reg(addr, reg, num=1):
+       dev = i2c(addr)
+       s = struct.pack(">B", reg)
+       dev.write(s)
+       s = dev.read(num)
+       dev.close()
+       return s
+
+
 if __name__ == "__main__":
        import struct
        import sys