Arnemi

esp_adc_dac_isr_ino

Dec 14th, 2023
1,214
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /*
  2.  * INFO:
  3.  * This code demonstrates how to use the ESP32 DAC and ADC in an interrupt based configuration.
  4.  * The code samples a signal with the ADC and converts the signal back to analog values with the DAC,
  5.  * allowing it to be processed digitally.
  6.  *
  7.  * The sampling frequency and resolution of the ADC and the DAC can be adjusted and experimented with
  8.  *
  9.  * Note: the ESP32 DAC has a fixed resolution of 8 bits, so the possibility for varying
  10.  * DAC resolution is simulated by representing the desired resolution within an 8 bit range.
  11.  */
  12.  
  13. // Variable for storing the timer properties. Leave it be.
  14. hw_timer_t *timer = NULL;
  15.  
  16. //Change these parameters in order to change the sampling properties of the system
  17. #define SAMPLING_PERIOD 50  //In microseconds, should be at least 50.
  18. #define ADC_RESOLUTION 12   //Resolution of the ADC. Must be between 9 and 12 bits.
  19. #define DAC_RESOLUTION 8    //Resolution of the DAC. Must be between 1 and 8 bits.
  20.  
  21. //Hardware configuration
  22. #define ADC_PIN 27
  23. #define DAC_PIN 26
  24.  
  25. /*
  26.  * Interrupt service routine that runs every with a period SAMPLING_PERIOD.
  27.  * Used for sampling, signal processing and digital to analog conversion.
  28.  */
  29. void ARDUINO_ISR_ATTR onTimer() {
  30.   /*
  31.    * Variables for storing the samples from the ADC and the sample to be written to the DAC.
  32.    * Defined as
  33.    */
  34.   static int sampleADC;
  35.   static int sampleDAC;
  36.  
  37.   //Sampling with the ADC from the ADC_PIN
  38.   sampleADC = analogRead(ADC_PIN);
  39.  
  40.   //Changing the resolution of the ADC sample to the resolution of the DAC.
  41.   sampleDAC = sampleADC >> ADC_RESOLUTION - DAC_RESOLUTION;
  42.  
  43.   //Your signal processing code here
  44.   sampleDAC *= 1.2;
  45.  
  46.   //Using the DAC to convert and write the sampleDAC variable on DAC_PIN, while making sure the sample is 8 bits.
  47.   dacWrite(DAC_PIN, (sampleDAC << 8 - DAC_RESOLUTION));
  48. }
  49.  
  50. //--------The code below this point can be left alone--------
  51.  
  52. void setup() {
  53.   // put your setup code here, to run once:
  54.  
  55.   analogReadResolution(ADC_RESOLUTION);
  56.  
  57.   //Initializing timer with 1Mhz frequency
  58.   timer = timerBegin(1000000);
  59.   timerAttachInterrupt(timer, &onTimer);
  60.  
  61.   //Call the onTimer function with the given period (in microseconds), repeating te timer and with unlimited count.
  62.   timerAlarm(timer, SAMPLING_PERIOD, true, 0);
  63. }
  64.  
  65. void loop() {
  66.   //empty loop
  67. }
  68.  
Advertisement