Skip to content

Commit 34c9e00

Browse files
committed
try (re)using the buffer in neopixel_write
1 parent 28c1e4f commit 34c9e00

File tree

1 file changed

+24
-13
lines changed

1 file changed

+24
-13
lines changed

ports/nrf/common-hal/neopixel_write/__init__.c

Lines changed: 24 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -116,6 +116,8 @@ void common_hal_neopixel_write (const digitalio_digitalinout_obj_t* digitalinout
116116

117117
uint32_t pattern_size = PATTERN_SIZE(numBytes);
118118
uint16_t* pixels_pattern = NULL;
119+
static uint16_t* pixels_pattern_heap = NULL;
120+
static size_t pixels_pattern_heap_size = 0;
119121
bool pattern_on_heap = false;
120122

121123
// Use the stack to store 1 pixels worth of PWM data for the status led. uint32_t to ensure alignment.
@@ -132,16 +134,29 @@ void common_hal_neopixel_write (const digitalio_digitalinout_obj_t* digitalinout
132134
} else {
133135
uint8_t sd_en = 0;
134136
(void) sd_softdevice_is_enabled(&sd_en);
135-
if (sd_en) {
136-
// If the soft device is enabled then we must use PWM to
137-
// transmit. This takes a bunch of memory to do so raise an
138-
// exception if we can't.
139-
pixels_pattern = (uint16_t *) m_malloc(pattern_size, false);
140-
} else {
141-
pixels_pattern = (uint16_t *) m_malloc_maybe(pattern_size, false);
142-
}
143137

144-
pattern_on_heap = true;
138+
if (!pattern_on_heap || pixels_pattern_heap_size < pattern_size) {
139+
if (pattern_on_heap) {
140+
m_free(pixels_pattern_heap);
141+
pixels_pattern = NULL;
142+
pixels_pattern_heap = NULL;
143+
pixels_pattern_heap_size = 0;
144+
}
145+
146+
if (sd_en) {
147+
// If the soft device is enabled then we must use PWM to
148+
// transmit. This takes a bunch of memory to do so raise an
149+
// exception if we can't.
150+
pixels_pattern_heap = (uint16_t *) m_malloc(pattern_size, false);
151+
} else {
152+
pixels_pattern_heap = (uint16_t *) m_malloc_maybe(pattern_size, false);
153+
}
154+
if (pixels_pattern_heap) {
155+
pattern_on_heap = true;
156+
pixels_pattern_heap_size = pattern_size;
157+
}
158+
}
159+
pixels_pattern = pixels_pattern_heap;
145160
}
146161
}
147162

@@ -223,10 +238,6 @@ void common_hal_neopixel_write (const digitalio_digitalinout_obj_t* digitalinout
223238
nrf_pwm_disable(pwm);
224239
nrf_pwm_pins_set(pwm, (uint32_t[]) {0xFFFFFFFFUL, 0xFFFFFFFFUL, 0xFFFFFFFFUL, 0xFFFFFFFFUL} );
225240

226-
if (pattern_on_heap) {
227-
m_free(pixels_pattern);
228-
}
229-
230241
} // End of DMA implementation
231242
// ---------------------------------------------------------------------
232243
else {

0 commit comments

Comments
 (0)