diff --git a/CMakeLists.txt b/CMakeLists.txt index 775baecf412..d952d51474e 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -57,6 +57,7 @@ set(CORE_SRCS cores/esp32/stdlib_noniso.c cores/esp32/Stream.cpp cores/esp32/StreamString.cpp + cores/esp32/Tone.cpp cores/esp32/HWCDC.cpp cores/esp32/USB.cpp cores/esp32/USBCDC.cpp diff --git a/cores/esp32/Arduino.h b/cores/esp32/Arduino.h index b1e8f7cd7de..1e621146a5a 100644 --- a/cores/esp32/Arduino.h +++ b/cores/esp32/Arduino.h @@ -195,6 +195,9 @@ extern "C" void configTime(long gmtOffset_sec, int daylightOffset_sec, extern "C" void configTzTime(const char* tz, const char* server1, const char* server2 = nullptr, const char* server3 = nullptr); +void tone(uint8_t _pin, unsigned int frequency, unsigned long duration = 0, unsigned long duty = 50); +void noTone(uint8_t _pin); + // WMath prototypes long random(long); #endif /* __cplusplus */ diff --git a/cores/esp32/Tone.cpp b/cores/esp32/Tone.cpp new file mode 100644 index 00000000000..01058dc24ff --- /dev/null +++ b/cores/esp32/Tone.cpp @@ -0,0 +1,49 @@ +#include +#include "driver/ledc.h" + +#define BITS LEDC_TIMER_11_BIT // up to more than 25 kHz + +void noTone(uint8_t _pin){ + ledc_stop(LEDC_LOW_SPEED_MODE, LEDC_CHANNEL_0, 0); +} + +// duty in % +void tone(uint8_t _pin, unsigned int frequency, unsigned long duration, unsigned long duty){ + if(duty > 100){ + log_e("Invalid duty parameter (%u) - must be between 0 and 100; Duty is in percents!", duty); + return; + } + ledc_timer_config_t ledc_timer = { + .speed_mode = LEDC_LOW_SPEED_MODE, // timer mode + .duty_resolution = BITS, // resolution of PWM duty + .timer_num = LEDC_TIMER_0, // timer index + .freq_hz = frequency, // frequency of PWM signal + .clk_cfg = LEDC_AUTO_CLK // Auto select the source clock + }; + esp_err_t ret = ledc_timer_config(&ledc_timer); + if(ret){ + log_e("Could not start tone; ledc_timer_config returned %d", ret); + return; + } + + ledc_channel_config_t ledc_channel = { + .gpio_num = _pin, /*!< the LEDC output gpio_num, if you want to use gpio16, gpio_num = 16 */ + .speed_mode = LEDC_LOW_SPEED_MODE, /*!< LEDC speed speed_mode, high-speed mode or low-speed mode */ + .channel = LEDC_CHANNEL_0, /*!< LEDC channel (0 - 7) */ + .intr_type = LEDC_INTR_DISABLE, /*!< configure interrupt, Fade interrupt enable or Fade interrupt disable */ + .timer_sel = LEDC_TIMER_0, /*!< Select the timer source of channel (0 - 3) */ + .duty = duty * ((1<