Using PWM and DAC in the same sketch

Status
Not open for further replies.

tulanthoar

New member
I am trying to use a PWM output and DAC in the same sketch. When I run my code, pin A22 outputs a PWM signal instead of the desired DAC output. I am using the Teensy 3.6.

#include <ADC.h>
#include <ADC_util.h>

const int readPin = A12; // adc1 or ADC1
const int dacPin = A22;
ADC *adc = new ADC(); // adc object
volatile uint32_t value = 0;
double d_value = 0.0;
int is_set = 0;
double err[4];
double mod[3];
double Vin = 0;
double vset = 2.0;
double Gpwm = 1.2500;
double kfb = 0.1600;
double cn[4] = {1.0965, -1.0583, -1.0961, 1.0586};
double cd[4] = {1.0000, -2.4776, 2.0235, -0.5458};

void setup() {
pinMode(LED_BUILTIN, OUTPUT);
analogWriteResolution(10);
analogWriteFrequency(2, 100000);
pinMode(readPin, INPUT_PULLUP);
adc->adc1->setAveraging(4); // set number of averages
adc->adc1->setResolution(12); // set bits of resolution
adc->adc1->setConversionSpeed(ADC_CONVERSION_SPEED::MED_SPEED); // change the conversion speed
adc->adc1->setSamplingSpeed(ADC_SAMPLING_SPEED::VERY_HIGH_SPEED);
adc->adc1->enableInterrupts(adc1_isr);
adc->adc1->wait_for_cal();
adc->adc1->startContinuous(readPin);
}

void loop() {

}

void adc1_isr(void) {
err[3] = err[2];
err[2] = err[1];
err[1] = err[0];
value = (uint16_t)adc->adc1->analogReadContinuous();
double d_value = 5.0 * value / 4096.0;
err[0] = vset * kfb - d_value * kfb;
double uterms = cn[0] * err[0] + cn[1] * err[1] + cn[2] * err[2] + cn[3] * err[3];
double yterms = cd[1] * mod[0] + cd[2] * mod[1] + cd[3] * mod[2];
mod[2] = mod[1];
mod[1] = mod[0];
mod[0] = uterms - yterms;
uint16_t w_value = round(mod[0] * Gpwm * 1024);
analogWrite(2, w_value);
analogWrite(dacPin, w_value);
}
 
Last edited:
your sketch didn't compile -- spaces in "MED_SPEE D" and "VERY_HIGH_SP EED"

that ISR is firing every 11 us -- not sure what settle time is for DAC ... You might print out w_delay (with delay(1000)) in loop()) and confirm number is in range 0-1023

if i just use a constant analogWrite(dacPin,512) I see a nice 1.64 v with scope on A22, so DAC seems to be working in "analog" mode

i have no way to reproduce what your hardware is providing in the ADC read's on A14. if i pull A14 to GND, w_value is 2870. If i pull A14 to 3v3, w_value is 61233

if i toggle dacPin analogwrite between 0 and 512 each time through the isr, i have a nice 45khz square wave on A22 (with scope).
 
Last edited:
Status
Not open for further replies.
Back
Top