bhi160.py 1.73 KB
Newer Older
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
import sys_bhi160
import interrupt


class BHI160Accelerometer:
    def __init__(
        self, sample_rate=4, dynamic_range=2, callback=None, sample_buffer_len=200
    ):
        interrupt.disable_callback(interrupt.BHI160_ACCELEROMETER)
        interrupt.set_callback(
            interrupt.BHI160_ACCELEROMETER, self._accelerometer_interrupt
        )
        self.acc_sd = sys_bhi160.enable_sensor(
            0, sample_buffer_len, sample_rate, dynamic_range
        )
        self._callback = callback
        if callback:
            interrupt.enable_callback(interrupt.BHI160_ACCELEROMETER)

    def __enter__(self):
        return self

    def __exit__(self, _et, _ev, _t):
        self.close()

    def close(self):
        if self.acc_sd is not None:
            self.acc_sd = None
            self.acc_sd = sys_bhi160.disable_sensor(0)
            interrupt.disable_callback(interrupt.BHI160_ACCELEROMETER)
            interrupt.set_callback(interrupt.BHI160_ACCELEROMETER, None)

33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
    def convert(self, value):
        return 2 * value / 32768.0

    def read(self):
        result = []
        if self.acc_sd is not None:
            for sample in sys_bhi160.read_sensor(self.acc_sd):
                result.append(
                    dict(
                        {
                            "x": self.convert(sample.x()),
                            "y": self.convert(sample.y()),
                            "z": self.convert(sample.z()),
                        }
                    )
                )
        return result

51
52
53
54
55
56
    def _accelerometer_interrupt(self, _):
        if self.acc_sd is not None:
            data = sys_bhi160.read_sensor(self.acc_sd)
            print(data)
            if self._callback:
                self._callback(data)