32
32
import time
33
33
from digitalio import DigitalInOut , Direction
34
34
35
+ try :
36
+ from typing import Optional , Type
37
+ from types import TracebackType
38
+ from microcontroller import Pin
39
+ except ImportError :
40
+ pass
41
+
35
42
_USE_PULSEIO = False
36
43
try :
37
44
from pulseio import PulseIn
@@ -68,7 +75,9 @@ class HCSR04:
68
75
time.sleep(0.1)
69
76
"""
70
77
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 :
72
81
"""
73
82
:param trigger_pin: The pin on the microcontroller that's connected to the
74
83
``Trig`` pin on the HC-SR04.
@@ -92,21 +101,26 @@ def __init__(self, trigger_pin, echo_pin, *, timeout=0.1):
92
101
self ._echo = DigitalInOut (echo_pin )
93
102
self ._echo .direction = Direction .INPUT
94
103
95
- def __enter__ (self ):
104
+ def __enter__ (self ) -> "HCSR04" :
96
105
"""Allows for use in context managers."""
97
106
return self
98
107
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 :
100
114
"""Automatically de-initialize after a context manager."""
101
115
self .deinit ()
102
116
103
- def deinit (self ):
117
+ def deinit (self ) -> None :
104
118
"""De-initialize the trigger and echo pins."""
105
119
self ._trig .deinit ()
106
120
self ._echo .deinit ()
107
121
108
122
@property
109
- def distance (self ):
123
+ def distance (self ) -> float :
110
124
"""Return the distance measured by the sensor in cm.
111
125
112
126
This is the function that will be called most often in user code. The
@@ -126,7 +140,7 @@ def distance(self):
126
140
"""
127
141
return self ._dist_two_wire () # at this time we only support 2-wire meausre
128
142
129
- def _dist_two_wire (self ):
143
+ def _dist_two_wire (self ) -> float :
130
144
if _USE_PULSEIO :
131
145
self ._echo .clear () # Discard any previous pulse values
132
146
self ._trig .value = True # Set trig high
0 commit comments