Skip to content

Commit 2bced65

Browse files
committed
Merge pull request gpiozero#324 from lurch/pwm_float
Always make PWMOutputDevice operate on floats.
2 parents 92cb735 + da9b0bb commit 2bced65

File tree

2 files changed

+15
-20
lines changed

2 files changed

+15
-20
lines changed

gpiozero/devices.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -376,9 +376,12 @@ def __init__(self, pin=None):
376376
self._active_state = True
377377
self._inactive_state = False
378378

379+
def _state_to_value(self, state):
380+
return bool(state == self._active_state)
381+
379382
def _read(self):
380383
try:
381-
return self.pin.state == self._active_state
384+
return self._state_to_value(self.pin.state)
382385
except (AttributeError, TypeError):
383386
self._check_open()
384387
raise

gpiozero/output_devices.py

Lines changed: 11 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -43,16 +43,15 @@ def __init__(self, pin=None, active_high=True, initial_value=False):
4343
self.active_high = active_high
4444
if initial_value is None:
4545
self.pin.function = 'output'
46-
elif initial_value:
47-
self.pin.output_with_state(self._active_state)
4846
else:
49-
self.pin.output_with_state(self._inactive_state)
47+
self.pin.output_with_state(self._value_to_state(initial_value))
48+
49+
def _value_to_state(self, value):
50+
return bool(self._active_state if value else self._inactive_state)
5051

5152
def _write(self, value):
52-
if not self.active_high:
53-
value = not value
5453
try:
55-
self.pin.state = bool(value)
54+
self.pin.state = self._value_to_state(value)
5655
except AttributeError:
5756
self._check_open()
5857
raise
@@ -318,23 +317,16 @@ def close(self):
318317
pass
319318
super(PWMOutputDevice, self).close()
320319

321-
def _read(self):
322-
self._check_open()
323-
if self.active_high:
324-
return self.pin.state
325-
else:
326-
return 1 - self.pin.state
320+
def _state_to_value(self, state):
321+
return float(state if self.active_high else 1 - state)
322+
323+
def _value_to_state(self, value):
324+
return float(value if self.active_high else 1 - value)
327325

328326
def _write(self, value):
329-
if not self.active_high:
330-
value = 1 - value
331327
if not 0 <= value <= 1:
332328
raise OutputDeviceBadValue("PWM value must be between 0 and 1")
333-
try:
334-
self.pin.state = value
335-
except AttributeError:
336-
self._check_open()
337-
raise
329+
super(PWMOutputDevice, self)._write(value)
338330

339331
@property
340332
def value(self):

0 commit comments

Comments
 (0)