High frequency analog output

I’m developing an electrophysiological stimulation system in our Uni. I’ve created a UI where different kind of complex stimulation patterns can be created and this is sent to arduino. The stimulation speed should be 10 kHz.

My solution:
As Arduino Due has not enogh analog output I use PWM. I need 12 bit resolution. I set the PWM frequency to a high value like 50.000 Hz in the variants.h as somebody advised on this forum. Using the DueTimer (https://github.com/ivanseidel/DueTimer) library I call interrupts in every 100 microsec. In every interrupt I call the analogWrite() function with the proper values. The output goes through low pass filtering and in the end I get an alaog output.

Problem:
Although it seems to work I get some noise on the descending part of the signal. Sometmes it is there sometimes it is not, sometimes bigger and also changes it’s place. I’m quite convinced that it is because of combining PWM with interrupts.

Question:
Is it a good idea to use analogWrite() in an interrupt? I searched forums and pages but I did not see this combination ever.
Is there a better way to achieve high frequency analog output in Arduino Due?

This is a code to illustrate my solution

#include “DueTimer.h”
//PWM frequency set to 50.000 in variants.h !

int res=1;
int counter=0;

void handler()
{
if(counter>4095){
counter=4095;
res=-1res;
}
if(counter<0){
counter=0;
res=-1
res;
}
analogWrite(10,counter);
counter=counter+res;
}

void setup(){
analogWriteResolution(12);
Timer3.attachInterrupt(handler).start(100);
}
void loop() {
}

Hi,

Arent variables that are modified inside the ISR supposed to be declared as "volatile" ?

For example:

volatile int res=1;
volatile int counter=0;

If you are worried about putting digitalWrite() inside the ISR then try putting it in the loop() function so that when the interrupt returns it updates whatever needs to be updated. That's if there is time for that of course.