Skip to content

Commit a87e00b

Browse files
committed
features/unit/ultrasonic: I2C interface ultrasonic distance sensor
1 parent 75faefd commit a87e00b

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

m5stack/libs/unit/ultrasonic_i2c.py

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
from machine import I2C
2+
from .pahub import PAHUB
3+
from .unit_helper import UnitError
4+
import time
5+
6+
try:
7+
from typing import Union
8+
except ImportError:
9+
pass
10+
11+
class ULTRASONIC_I2C:
12+
13+
def __init__(self, i2c: Union[I2C, PAHUB], addr=0x57):
14+
self.i2c = i2c
15+
self.i2c_addr = addr
16+
self._distance = 0
17+
self._available()
18+
19+
def _available(self):
20+
if not (self.i2c_addr in self.i2c.scan()):
21+
raise UnitError("Ultrasonic unit maybe not connect")
22+
23+
def get_target_distance(self, mode=1):
24+
try:
25+
self.i2c.writeto(self.i2c_addr, bytearray([0x01]))
26+
time.sleep_ms(150)
27+
data = self.i2c.readfrom(self.i2c_addr, 3)
28+
self._distance = ((data[0] << 16) | (data[1] << 8) | data[2]) / 1000
29+
except OSError:
30+
pass
31+
if mode == 2:
32+
self._distance = self._distance / 10
33+
return round(self._distance, 2)
34+

0 commit comments

Comments
 (0)