Skip to content

Commit 5abf5d8

Browse files
committed
reduce the number of allocations
1 parent b084041 commit 5abf5d8

File tree

1 file changed

+14
-9
lines changed

1 file changed

+14
-9
lines changed

adafruit_apds9960/apds9960.py

Lines changed: 14 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -112,6 +112,9 @@ def __init__(self,
112112
integration_time=0x01,
113113
gain=0x01):
114114

115+
self.buf129 = None
116+
self.buf2 = bytearray(2)
117+
115118
self.i2c_device = I2CDevice(i2c, address)
116119
self._interrupt_pin = interrupt_pin
117120
if interrupt_pin:
@@ -142,7 +145,6 @@ def __init__(self,
142145
# gesture pulse length=0x2 pulse count=0x3
143146
self._write8(APDS9960_GPULSE, (0x2 << 6) | 0x3)
144147

145-
146148
## BOARD
147149
def _reset_counts(self):
148150
"""Gesture detection internal counts"""
@@ -187,7 +189,10 @@ def gesture(self): #pylint: disable-msg=too-many-branches
187189
=1 if an UP, =2 if a DOWN, =3 if an LEFT, =4 if a RIGHT
188190
"""
189191
# buffer to read of contents of device FIFO buffer
190-
buffer = bytearray(129)
192+
if self.buf129:
193+
self.buf129 = bytearray(129)
194+
195+
buffer = self.buf129
191196
buffer[0] = APDS9960_GFIFO_U
192197
if not self._gesture_valid:
193198
return 0
@@ -331,32 +336,32 @@ def integration_time(self, int_time):
331336
# method for reading and writing to I2C
332337
def _write8(self, command, abyte):
333338
"""Write a command and 1 byte of data to the I2C device"""
334-
buf = bytearray(2)
339+
buf = self.buf2
335340
buf[0] = command
336341
buf[1] = abyte
337342
with self.i2c_device as i2c:
338343
i2c.write(buf)
339344

340345
def _writecmdonly(self, command):
341346
"""Writes a command and 0 bytes of data to the I2C device"""
342-
buf = bytearray(1)
347+
buf = self.buf2
343348
buf[0] = command
344349
with self.i2c_device as i2c:
345-
i2c.write(buf)
350+
i2c.write(buf, end=1)
346351

347352
def _read8(self, command):
348353
"""Sends a command and reads 1 byte of data from the I2C device"""
349-
buf = bytearray(1)
354+
buf = self.buf2
350355
buf[0] = command
351356
with self.i2c_device as i2c:
352-
i2c.write(buf)
353-
i2c.readinto(buf)
357+
i2c.write(buf, end=1)
358+
i2c.readinto(buf, end=1)
354359
return buf[0]
355360

356361
def _color_data16(self, command):
357362
"""Sends a command and reads 2 bytes of data from the I2C device
358363
The returned data is low byte first followed by high byte"""
359-
buf = bytearray(2)
364+
buf = self.buf2
360365
buf[0] = command
361366
with self.i2c_device as i2c:
362367
i2c.write(buf, end=1, stop=False)

0 commit comments

Comments
 (0)