Skip to content

Commit a0981fc

Browse files
authored
Add movement counter to WeDo 2.0 Motion Sensor
1 parent eeffd9d commit a0981fc

File tree

1 file changed

+34
-2
lines changed

1 file changed

+34
-2
lines changed

buildhat/wedo.py

Lines changed: 34 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@ class MotionSensor(Device):
3535
:param port: Port of device
3636
:raises DeviceError: Occurs if there is no motion sensor attached to port
3737
"""
38+
default_mode = 0
3839

3940
def __init__(self, port):
4041
"""
@@ -43,7 +44,18 @@ def __init__(self, port):
4344
:param port: Port of device
4445
"""
4546
super().__init__(port)
46-
self.mode(0)
47+
self.mode(self.default_mode)
48+
49+
def set_default_data_mode(self, mode):
50+
"""
51+
Set the mode most often queried from this device to significantly
52+
improve performance when repeatedly accessing data
53+
54+
:param mode: 0 for distance (default), 1 for movement count
55+
"""
56+
if mode == 1 or mode == 0:
57+
self.default_mode = mode
58+
self.mode(mode)
4759

4860
def get_distance(self):
4961
"""
@@ -52,4 +64,24 @@ def get_distance(self):
5264
:return: Distance from motion sensor
5365
:rtype: int
5466
"""
55-
return self.get()[0]
67+
return self._get_data_from_mode(0)
68+
69+
def get_movement_count(self):
70+
"""
71+
Return the movement counter: The count of how many times the sensor has
72+
detected an object that moved within 4 blocks of the sensor since the
73+
sensor has been plugged in or the BuildHAT reset
74+
75+
:return: Count of objects detected
76+
:rtype: int
77+
"""
78+
return self._get_data_from_mode(1)
79+
80+
def _get_data_from_mode(self, mode):
81+
if self.default_mode == mode:
82+
return self.get()[0]
83+
else:
84+
self.mode(mode)
85+
retval = self.get()[0]
86+
self.mode(self.default_mode)
87+
return retval

0 commit comments

Comments
 (0)