I am trying to do a code using mega 2560 arduino to generate Pulse Width Modulation(PWM) with 4 KHZ and also I want to be able to change the duty cycle of PWM through the code. could you please help with that. This is my code. I feel it is not the write code. please let me know if there is a simpler way to do the code.
boolean toggle2 = 0;
void setup()
{
int LedPin = 11;
// put your setup code here, to run once:
pinMode (LedPin, OUTPUT); // set pin 11 as output (the LED pin)
Serial.begin(9600);
//int myprescaler = 6;
// initialize timer1
noInterrupts(); // disable all interrupts
TCCR2A = 0;
TCCR2B = 0;
TCNT2 = 0;
OCR2A = 249; // compare match register
TCCR2A |= (1 << WGM21); // CTC mode
//TCCR1B |= myprescaler;
TCCR2B |= (1 << CS11);
TIMSK2 |= (1 << OCIE2A); // enable timer compare interrupt
interrupts(); // enable all interrupts
}
ISR(TIMER2_COMPA_vect){//timer1 interrupt 8kHz toggles pin 9
//generates pulse wave of frequency 8kHz/2 = 4kHz (takes two cycles for full wave- toggle high then toggle low)
if (toggle2){
digitalWrite(11,HIGH);
toggle2 = 0;
}
else{
digitalWrite(11,LOW);
toggle2 = 1;
}
}
void loop() {
// put your main code here, to run repeatedly:
int LedPin = 11;
//analogWrite (LedPin,127); // sets brightness (voltage) to i
for (int i=10; i<=204; i=i+2) // increasing i value ()
{
// 204 in PWM represents 4V (max volts to get me Imax = 8mA)
// 51 in PWM represents 1V (min volts i want... Imin = 2mA)
// Serial.println (analogRead(LedPin));
delay (1);
}
for (int j=204; j>=25; j=j-2) // decreasing j value
{
analogWrite (LedPin,j);
//Serial.println (analogRead(LedPin));
delay (1);
}
}