2828#include "shared-bindings/neopixel_write/__init__.h"
2929
3030#include "tick.h"
31+ #include "py/mperrno.h"
32+ #include "py/runtime.h"
3133#include "common-hal/microcontroller/Pin.h"
3234#include "stm32f4xx_hal.h"
3335#include "stm32f4xx_ll_gpio.h"
@@ -40,6 +42,9 @@ uint32_t next_start_tick_us = 1000;
4042#define MAGIC_800_T0H 2800000 // ~0.36 us -> 0.44 field
4143#define MAGIC_800_T1H 1350000 // ~0.74 us -> 0.84 field
4244
45+ #pragma GCC push_options
46+ #pragma GCC optimize ("Os")
47+
4348void common_hal_neopixel_write (const digitalio_digitalinout_obj_t * digitalinout , uint8_t * pixels ,
4449 uint32_t numBytes ) {
4550 uint8_t * p = pixels , * end = p + numBytes , pix = * p ++ , mask = 0x80 ;
@@ -48,7 +53,7 @@ void common_hal_neopixel_write (const digitalio_digitalinout_obj_t* digitalinout
4853
4954 //assumes 800_000Hz frequency
5055 //Theoretical values here are 800_000 -> 1.25us, 2500000->0.4us, 1250000->0.8us
51- //But they don't work, possibly due to bad optimization? Use tested magic values instead
56+ //TODO: try to get dynamic weighting working again
5257 uint32_t sys_freq = HAL_RCC_GetSysClockFreq ();
5358 uint32_t interval = sys_freq /MAGIC_800_INT ;
5459 uint32_t t0 = (sys_freq /MAGIC_800_T0H );
@@ -63,23 +68,22 @@ void common_hal_neopixel_write (const digitalio_digitalinout_obj_t* digitalinout
6368
6469 __disable_irq ();
6570 // Enable DWT in debug core. Useable when interrupts disabled, as opposed to Systick->VAL
66- //ITM->LAR = 0xC5ACCE55; //this should be required but isn't
6771 CoreDebug -> DEMCR |= CoreDebug_DEMCR_TRCENA_Msk ;
6872 DWT -> CTRL |= DWT_CTRL_CYCCNTENA_Msk ;
6973 DWT -> CYCCNT = 0 ;
7074
7175 for (;;) {
76+ cyc = (pix & mask ) ? t1 : t0 ;
7277 start = DWT -> CYCCNT ;
7378 LL_GPIO_SetOutputPin (p_port , p_mask );
74- cyc = (pix & mask ) ? t1 : t0 ;
75- while (DWT -> CYCCNT - start < cyc );
79+ while ((DWT -> CYCCNT - start ) < cyc );
7680 LL_GPIO_ResetOutputPin (p_port , p_mask );
81+ while ((DWT -> CYCCNT - start ) < interval );
7782 if (!(mask >>= 1 )) {
7883 if (p >= end ) break ;
7984 pix = * p ++ ;
8085 mask = 0x80 ;
8186 }
82- while (DWT -> CYCCNT - start < interval ); //wait for interval to finish
8387 }
8488
8589 // Enable interrupts again
@@ -94,3 +98,5 @@ void common_hal_neopixel_write (const digitalio_digitalinout_obj_t* digitalinout
9498 next_start_tick_us -= 100 ;
9599 }
96100}
101+
102+ #pragma GCC pop_options
0 commit comments