Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * INFO:
- * This code demonstrates how to use the ESP32 DAC and ADC in an interrupt based configuration.
- * The code samples a signal with the ADC and converts the signal back to analog values with the DAC,
- * allowing it to be processed digitally.
- *
- * The sampling frequency and resolution of the ADC and the DAC can be adjusted and experimented with
- *
- * Note: the ESP32 DAC has a fixed resolution of 8 bits, so the possibility for varying
- * DAC resolution is simulated by representing the desired resolution within an 8 bit range.
- */
- // Variable for storing the timer properties. Leave it be.
- hw_timer_t *timer = NULL;
- //Change these parameters in order to change the sampling properties of the system
- #define SAMPLING_PERIOD 50 //In microseconds, should be at least 50.
- #define ADC_RESOLUTION 12 //Resolution of the ADC. Must be between 9 and 12 bits.
- #define DAC_RESOLUTION 8 //Resolution of the DAC. Must be between 1 and 8 bits.
- //Hardware configuration
- #define ADC_PIN 27
- #define DAC_PIN 26
- /*
- * Interrupt service routine that runs every with a period SAMPLING_PERIOD.
- * Used for sampling, signal processing and digital to analog conversion.
- */
- void ARDUINO_ISR_ATTR onTimer() {
- /*
- * Variables for storing the samples from the ADC and the sample to be written to the DAC.
- * Defined as
- */
- static int sampleADC;
- static int sampleDAC;
- //Sampling with the ADC from the ADC_PIN
- sampleADC = analogRead(ADC_PIN);
- //Changing the resolution of the ADC sample to the resolution of the DAC.
- sampleDAC = sampleADC >> ADC_RESOLUTION - DAC_RESOLUTION;
- //Your signal processing code here
- sampleDAC *= 1.2;
- //Using the DAC to convert and write the sampleDAC variable on DAC_PIN, while making sure the sample is 8 bits.
- dacWrite(DAC_PIN, (sampleDAC << 8 - DAC_RESOLUTION));
- }
- //--------The code below this point can be left alone--------
- void setup() {
- // put your setup code here, to run once:
- analogReadResolution(ADC_RESOLUTION);
- //Initializing timer with 1Mhz frequency
- timer = timerBegin(1000000);
- timerAttachInterrupt(timer, &onTimer);
- //Call the onTimer function with the given period (in microseconds), repeating te timer and with unlimited count.
- timerAlarm(timer, SAMPLING_PERIOD, true, 0);
- }
- void loop() {
- //empty loop
- }
Advertisement