@@ -130,10 +130,11 @@ static lego_device_type_id_t pbdrv_counter_ev3_get_type(uint16_t adc) {
130130 return LEGO_DEVICE_TYPE_ID_NONE ;
131131}
132132
133+ #define PBDRV_COUNTER_EV3_TYPE_LOOP_TIME (10)
134+ #define PBDRV_COUNTER_EV3_TYPE_MIN_STABLE_COUNT (20)
135+
133136/**
134137 * Updates the type of all EV3 motors based on the current ADC values.
135- *
136- * This is called periodically by the ADC process.
137138 */
138139static void pbdrv_counter_ev3_update_type (void ) {
139140
@@ -155,12 +156,32 @@ static void pbdrv_counter_ev3_update_type(void) {
155156
156157 // Update stable type if we have seen enough identical detections,
157158 // including none detections.
158- if (dev -> type_id_count >= 20 ) {
159+ if (dev -> type_id_count >= PBDRV_COUNTER_EV3_TYPE_MIN_STABLE_COUNT ) {
159160 dev -> stable_type_id = type_id ;
160161 }
161162 }
162163}
163164
165+ static pbio_os_process_t pbdrv_counter_device_detect_process ;
166+
167+ /**
168+ * Background process to periodically read the ADC values to detect devices.
169+ */
170+ static pbio_error_t pbdrv_counter_device_detect_process_thread (pbio_os_state_t * state , void * context ) {
171+
172+ static pbio_os_timer_t timer ;
173+
174+ PBIO_OS_ASYNC_BEGIN (state );
175+
176+ for (;;) {
177+ pbdrv_counter_ev3_update_type ();
178+ PBIO_OS_AWAIT_MS (state , & timer , PBDRV_COUNTER_EV3_TYPE_LOOP_TIME );
179+ }
180+
181+ PBIO_OS_ASYNC_END (PBIO_SUCCESS );
182+ }
183+
184+
164185pbio_error_t pbdrv_counter_assert_type (pbdrv_counter_dev_t * dev , lego_device_type_id_t * expected_type_id ) {
165186
166187 if (dev -> stable_type_id == LEGO_DEVICE_TYPE_ID_NONE ) {
@@ -256,7 +277,8 @@ void pbdrv_counter_init(void) {
256277 HWREG (baseAddr + GPIO_SET_RIS_TRIG (3 )) = HWREG (baseAddr + GPIO_SET_RIS_TRIG (3 )) | 0x00000200 ;
257278 HWREG (baseAddr + GPIO_SET_FAL_TRIG (3 )) = HWREG (baseAddr + GPIO_SET_FAL_TRIG (3 )) | 0x00000200 ;
258279
259- pbdrv_adc_set_callback (pbdrv_counter_ev3_update_type );
280+ // Monitor attached counter devices
281+ pbio_os_process_start (& pbdrv_counter_device_detect_process , pbdrv_counter_device_detect_process_thread , NULL );
260282}
261283
262284#endif // PBDRV_CONFIG_COUNTER_EV3
0 commit comments