@@ -82,16 +82,44 @@ static void machine_timer_print(const mp_print_t *print, mp_obj_t self_in, mp_pr
8282 #endif
8383}
8484
85- machine_timer_obj_t * machine_timer_create (mp_uint_t timer ) {
85+ static bool find_free_timer (mp_int_t * group , mp_int_t * index ) {
86+ // from highest to lowest id
87+ for (* group = SOC_TIMER_GROUPS - 1 ; * group >= 0 ; -- (* group )) {
88+ for (* index = SOC_TIMER_GROUP_TIMERS_PER_GROUP - 1 ; * index >= 0 ; -- (* index )) {
89+ bool free = true;
90+ // Check whether the timer is already initialized, if so skip it
91+ for (machine_timer_obj_t * t = MP_STATE_PORT (machine_timer_obj_head ); t ; t = t -> next ) {
92+ if (t -> group == * group && t -> index == * index ) {
93+ free = false;
94+ break ;
95+ }
96+ }
97+ if (free ) {
98+ return true;
99+ }
100+ }
101+ }
102+ return false;
103+ }
104+
105+ machine_timer_obj_t * machine_timer_create (mp_int_t timer ) {
86106
87107 machine_timer_obj_t * self = NULL ;
88- #if SOC_TIMER_GROUP_TIMERS_PER_GROUP == 1
89- mp_uint_t group = timer & 1 ;
90- mp_uint_t index = 0 ;
91- #else
92- mp_uint_t group = (timer >> 1 ) & 1 ;
93- mp_uint_t index = timer & 1 ;
94- #endif
108+ mp_int_t group ;
109+ mp_int_t index ;
110+ if (timer == -2 ) {
111+ if (!find_free_timer (& group , & index )) {
112+ mp_raise_msg_varg (& mp_type_RuntimeError , MP_ERROR_TEXT ("out of Timers:%d" ), SOC_TIMER_GROUP_TOTAL_TIMERS );
113+ }
114+ } else {
115+ #if SOC_TIMER_GROUP_TIMERS_PER_GROUP == 1
116+ group = timer & 1 ;
117+ index = 0 ;
118+ #else
119+ group = (timer >> 1 ) & 1 ;
120+ index = timer & 1 ;
121+ #endif
122+ }
95123
96124 // Check whether the timer is already initialized, if so use it
97125 for (machine_timer_obj_t * t = MP_STATE_PORT (machine_timer_obj_head ); t ; t = t -> next ) {
@@ -118,7 +146,7 @@ static mp_obj_t machine_timer_make_new(const mp_obj_type_t *type, size_t n_args,
118146 mp_arg_check_num (n_args , n_kw , 1 , MP_OBJ_FUN_ARGS_MAX , true);
119147
120148 // Create the new timer.
121- uint32_t timer_number = mp_obj_get_int (args [0 ]);
149+ mp_int_t timer_number = mp_obj_get_int (args [0 ]);
122150 if (timer_number >= SOC_TIMER_GROUP_TOTAL_TIMERS ) {
123151 mp_raise_ValueError (MP_ERROR_TEXT ("invalid Timer number" ));
124152 }
0 commit comments