LFO with Depth control

Hey guys!
I’m trying to do an LFO with Arduino. Basically, the LFO is working and rate (speed control) too.
Could anyone help me how I can add a Depth control (Variable duty cycle)?
Thanks guys!

int rate;
bool b;
int i;
int Wave;

void setup() {
  cli();
  pinMode(9, OUTPUT);
  //TIMER 1 SETUP
  TCCR1A = 1010000001;
  TCCR1B = 0b00001001;
  // TIMER 2 SETUP
  TCCR2A = 0b10100010;
  TCCR2B = 0b00000111;
  TCNT2  = 0;
  OCR2A  = 0;
  TIMSK2 = 0b00000010;
  sei();
}

ISR(TIMER2_COMPA_vect) {
  if (i == 255) i = 0;
  i++;
  analogWrite(9, triangle(i));
}
void loop() {
  rate  = analogRead(A0);
  rate  = map(rate,  0, 1023, 125, 1);
  OCR2A = rate;
}

int triangle(int i) {
  if (Wave >= 255) b = LOW;
  if (Wave <=   0) b = HIGH;
  if (b == HIGH) Wave++;
  if (b == LOW) Wave--;
  return Wave;
}

when creating an LFO with duty cycle, you will have to separate the first half of the wave from the second, but first have a look at this little snag you created.

ISR(TIMER2_COMPA_vect) {
  if (i == 255) i = 0;
  i++;
  analogWrite(9, triangle(i));
}

you pass ‘i’ to function triangle, but do nothing with the variable within that function.

int triangle(int i) {
  if (Wave >= 255) b = LOW;
  if (Wave <=   0) b = HIGH;
  if (b == HIGH) Wave++;
  if (b == LOW) Wave--;
  return Wave;
}

you do modify ‘Wave’ within the ISR (or function called by it) so int Wave;should be declared volatile, though since this global variable is not used anywhere outside of the ISR you get away with it.
Anyway, clean this up first, let the ISR counter directly refer to a point within the wave cycle, then determine if the wave is in it’s upper or lower part and use the map() function to recalculate it’s value.

allfreitas:
Could anyone help me how I can add a Depth control (Variable duty cycle)?

I think by "Depth" you mean "Amplitude"... adjusting the height of the peaks and depth of the valleys. To do that, change "analogWrite(9, triangle(i));" to:

 int val = triangle(i) - 128; // map 0..255 to -128..+127
  val = (val * Depth) / 256;  // Depth = 0 to 255
  analogWrite(9, val + 128);

I corrected these parts as Deva told me and added John's equation to control the amplitude (Depth is a common name in guitar pedals and I'm a guitarist :smiley: :sweat_smile: ).

Deva_Rishi and johnwasser... Thanks a lot, guys. You're amazing!