Skip to content

Commit d4e9986

Browse files
authored
Merge pull request #201 from mutesplash/patch-2
Add movement counter to WeDo 2.0 Motion Sensor
2 parents af1bfd7 + e2b9a79 commit d4e9986

File tree

1 file changed

+38
-2
lines changed

1 file changed

+38
-2
lines changed

buildhat/wedo.py

+38-2
Original file line numberDiff line numberDiff line change
@@ -36,14 +36,28 @@ class MotionSensor(Device):
3636
:raises DeviceError: Occurs if there is no motion sensor attached to port
3737
"""
3838

39+
default_mode = 0
40+
3941
def __init__(self, port):
4042
"""
4143
Initialise motion sensor
4244
4345
:param port: Port of device
4446
"""
4547
super().__init__(port)
46-
self.mode(0)
48+
self.mode(self.default_mode)
49+
50+
def set_default_data_mode(self, mode):
51+
"""
52+
Set the mode most often queried from this device.
53+
54+
This significantly improves performance when repeatedly accessing data
55+
56+
:param mode: 0 for distance (default), 1 for movement count
57+
"""
58+
if mode == 1 or mode == 0:
59+
self.default_mode = mode
60+
self.mode(mode)
4761

4862
def get_distance(self):
4963
"""
@@ -52,4 +66,26 @@ def get_distance(self):
5266
:return: Distance from motion sensor
5367
:rtype: int
5468
"""
55-
return self.get()[0]
69+
return self._get_data_from_mode(0)
70+
71+
def get_movement_count(self):
72+
"""
73+
Return the movement counter
74+
75+
This is the count of how many times the sensor has detected an object
76+
that moved within 4 blocks of the sensor since the sensor has been
77+
plugged in or the BuildHAT reset
78+
79+
:return: Count of objects detected
80+
:rtype: int
81+
"""
82+
return self._get_data_from_mode(1)
83+
84+
def _get_data_from_mode(self, mode):
85+
if self.default_mode == mode:
86+
return self.get()[0]
87+
else:
88+
self.mode(mode)
89+
retval = self.get()[0]
90+
self.mode(self.default_mode)
91+
return retval

0 commit comments

Comments
 (0)