adc2_example_main.c 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. /* ADC2 Example
  2. This example code is in the Public Domain (or CC0 licensed, at your option.)
  3. Unless required by applicable law or agreed to in writing, this
  4. software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
  5. CONDITIONS OF ANY KIND, either express or implied.
  6. */
  7. #include <stdio.h>
  8. #include <stdlib.h>
  9. #include "freertos/FreeRTOS.h"
  10. #include "freertos/task.h"
  11. #include "freertos/queue.h"
  12. #include "driver/gpio.h"
  13. #include "driver/adc.h"
  14. #include "driver/dac.h"
  15. #include "esp_system.h"
  16. #define DAC_EXAMPLE_CHANNEL CONFIG_EXAMPLE_DAC_CHANNEL
  17. #define ADC2_EXAMPLE_CHANNEL CONFIG_EXAMPLE_ADC2_CHANNEL
  18. #if CONFIG_IDF_TARGET_ESP32
  19. static const adc_bits_width_t width = ADC_WIDTH_BIT_12;
  20. #elif CONFIG_IDF_TARGET_ESP32S2
  21. static const adc_bits_width_t width = ADC_WIDTH_BIT_13;
  22. #endif
  23. void app_main(void)
  24. {
  25. uint8_t output_data=0;
  26. int read_raw;
  27. esp_err_t r;
  28. gpio_num_t adc_gpio_num, dac_gpio_num;
  29. r = adc2_pad_get_io_num( ADC2_EXAMPLE_CHANNEL, &adc_gpio_num );
  30. assert( r == ESP_OK );
  31. r = dac_pad_get_io_num( DAC_EXAMPLE_CHANNEL, &dac_gpio_num );
  32. assert( r == ESP_OK );
  33. printf("ADC2 channel %d @ GPIO %d, DAC channel %d @ GPIO %d.\n", ADC2_EXAMPLE_CHANNEL, adc_gpio_num,
  34. DAC_EXAMPLE_CHANNEL + 1, dac_gpio_num );
  35. dac_output_enable( DAC_EXAMPLE_CHANNEL );
  36. //be sure to do the init before using adc2.
  37. printf("adc2_init...\n");
  38. adc2_config_channel_atten( ADC2_EXAMPLE_CHANNEL, ADC_ATTEN_11db );
  39. vTaskDelay(2 * portTICK_PERIOD_MS);
  40. printf("start conversion.\n");
  41. while(1) {
  42. dac_output_voltage( DAC_EXAMPLE_CHANNEL, output_data++ );
  43. r = adc2_get_raw( ADC2_EXAMPLE_CHANNEL, width, &read_raw);
  44. if ( r == ESP_OK ) {
  45. printf("%d: %d\n", output_data, read_raw );
  46. } else if ( r == ESP_ERR_INVALID_STATE ) {
  47. printf("%s: ADC2 not initialized yet.\n", esp_err_to_name(r));
  48. } else if ( r == ESP_ERR_TIMEOUT ) {
  49. //This can not happen in this example. But if WiFi is in use, such error code could be returned.
  50. printf("%s: ADC2 is in use by Wi-Fi.\n", esp_err_to_name(r));
  51. } else {
  52. printf("%s\n", esp_err_to_name(r));
  53. }
  54. vTaskDelay( 2 * portTICK_PERIOD_MS );
  55. }
  56. }