diff --git a/main/esp32-sequencer.c b/main/esp32-sequencer.c index 5f6a878..8f75c7c 100644 --- a/main/esp32-sequencer.c +++ b/main/esp32-sequencer.c @@ -9,6 +9,7 @@ #include "esp_log.h" #include "esp_random.h" #include "freertos/FreeRTOS.h" +#include "freertos/portmacro.h" #include "freertos/queue.h" #include "freertos/task.h" #include "hal/gpio_types.h" @@ -37,11 +38,14 @@ static QueueHandle_t control_event_queue = NULL; static gptimer_handle_t tap_tempo_timer = NULL; static gptimer_handle_t gate_timer = NULL; -static const uint16_t DEBOUNCE_TIMEOUT = 20; // polling period length when debouncing in ms +static const uint16_t DEBOUNCE_TIMEOUT = 10; // polling period length when debouncing in ms static uint64_t debounce_time = 0; // system time of last intterupt static uint8_t btn_state = 1; // state of gpio last recorded +portMUX_TYPE mux = portMUX_INITIALIZER_UNLOCKED; + static const uint32_t DEFAULT_BPM = 120; +static uint16_t current_bpm = DEFAULT_BPM; #define SEQ_MAX_LEN 8 static uint8_t sequence[SEQ_MAX_LEN] = {0}; @@ -85,14 +89,18 @@ static void tap_tempo_handler(){ ESP_LOGI(TAG, "Starting tap tempo monitoring"); } else { // stop the timer and calc bpm ESP_ERROR_CHECK(gptimer_stop(tap_tempo_timer)); - ESP_LOGI(TAG, "Stopping tap tempo monitoring at %" PRIu64 "µs", count); + ESP_ERROR_CHECK(gptimer_set_raw_count(tap_tempo_timer, 0)); + current_bpm = ms_to_bpm(count / 1000); + ESP_LOGI(TAG, "Stopping tap tempo monitoring at %" PRIu64 "ms", count / 1000); } } static void IRAM_ATTR gpio_isr_handler(void* arg) { - debounce_time = xTaskGetTickCount(); // set time of interrupt uint32_t gpio_num = (uint32_t)arg; + portENTER_CRITICAL_ISR(&mux); + debounce_time = xTaskGetTickCount(); // set time of interrupt btn_state = gpio_get_level(gpio_num); // set state + portEXIT_CRITICAL_ISR(&mux); xQueueSendFromISR(control_event_queue, &gpio_num, NULL); } @@ -102,8 +110,10 @@ static void control_event_handler(void* arg) { uint64_t last_debounce_time; while (1) { // save these so we can make comparisons + portENTER_CRITICAL_ISR(&mux); last_btn_state = btn_state; last_debounce_time = debounce_time; + portEXIT_CRITICAL_ISR(&mux); uint8_t current_state = gpio_get_level(gpio_num); if (xQueueReceive(control_event_queue, &gpio_num, portMAX_DELAY)) { // Check if interrupt triggered stays the same for long enough @@ -264,7 +274,7 @@ void app_main(void) { pulse_cv(false); } printf("%i", sequence[step]); - vTaskDelay(bpm_to_ms(DEFAULT_BPM)/ portTICK_PERIOD_MS); + vTaskDelay(bpm_to_ms(current_bpm)/ portTICK_PERIOD_MS); } printf("\n");