Skip to content

Commit cc696b8

Browse files
authored
Merge pull request #29 from tcfranks/main
Add missing type annotations
2 parents 1b1f7f4 + 42a2866 commit cc696b8

File tree

1 file changed

+20
-6
lines changed

1 file changed

+20
-6
lines changed

adafruit_hcsr04.py

Lines changed: 20 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,13 @@
3232
import time
3333
from digitalio import DigitalInOut, Direction
3434

35+
try:
36+
from typing import Optional, Type
37+
from types import TracebackType
38+
from microcontroller import Pin
39+
except ImportError:
40+
pass
41+
3542
_USE_PULSEIO = False
3643
try:
3744
from pulseio import PulseIn
@@ -68,7 +75,9 @@ class HCSR04:
6875
time.sleep(0.1)
6976
"""
7077

71-
def __init__(self, trigger_pin, echo_pin, *, timeout=0.1):
78+
def __init__(
79+
self, trigger_pin: Pin, echo_pin: Pin, *, timeout: float = 0.1
80+
) -> None:
7281
"""
7382
:param trigger_pin: The pin on the microcontroller that's connected to the
7483
``Trig`` pin on the HC-SR04.
@@ -92,21 +101,26 @@ def __init__(self, trigger_pin, echo_pin, *, timeout=0.1):
92101
self._echo = DigitalInOut(echo_pin)
93102
self._echo.direction = Direction.INPUT
94103

95-
def __enter__(self):
104+
def __enter__(self) -> "HCSR04":
96105
"""Allows for use in context managers."""
97106
return self
98107

99-
def __exit__(self, exc_type, exc_val, exc_tb):
108+
def __exit__(
109+
self,
110+
exc_type: Optional[Type[BaseException]],
111+
exc_val: Optional[BaseException],
112+
exc_tb: Optional[TracebackType],
113+
) -> None:
100114
"""Automatically de-initialize after a context manager."""
101115
self.deinit()
102116

103-
def deinit(self):
117+
def deinit(self) -> None:
104118
"""De-initialize the trigger and echo pins."""
105119
self._trig.deinit()
106120
self._echo.deinit()
107121

108122
@property
109-
def distance(self):
123+
def distance(self) -> float:
110124
"""Return the distance measured by the sensor in cm.
111125
112126
This is the function that will be called most often in user code. The
@@ -126,7 +140,7 @@ def distance(self):
126140
"""
127141
return self._dist_two_wire() # at this time we only support 2-wire meausre
128142

129-
def _dist_two_wire(self):
143+
def _dist_two_wire(self) -> float:
130144
if _USE_PULSEIO:
131145
self._echo.clear() # Discard any previous pulse values
132146
self._trig.value = True # Set trig high

0 commit comments

Comments
 (0)