1

I`m trying to blink led with PWM on Arduino, and I dont know whats wrong. But my LED is not fadeing. What is wrong? I think that I have bad registers settings, but Im not sure. Led is connected on arduino pin 11. Thank you.

#include <avr/io.h>
#include <util/delay.h>
const int delay=1000; 
void initialize_PWM()
{
    TCCR0A|=(1<<WGM00)|(1<<WGM01)|(1<<COM0A1);
    TCCR0B=1;
    DDRB|=(1<<PB3); 
}

void set_pwm(uint8_t data)
{
    OCR0A=data;
}

int main (void)
{
initialize_PWM();
uint8_t brightness=200;
while(1)
{
  for(brightness=0;brightness<255;brightness++)
  {
    set_pwm(brightness);
     _delay_ms(1);
  }

  for(brightness=255;brightness>0;brightness--)
  {
     set_pwm(brightness);
     _delay_ms(1);
 }
}
 return 0;
}
4
  • What arduino are you using? And why don't you just use the arduino sdk, and APIs (i.e. analogWrite)? Commented Jun 15, 2014 at 11:21
  • You pervert! Why You are using pure AVRC? Imho You should use Arduino methods instead AVRC. Commented Jun 15, 2014 at 12:12
  • I am using arduino Uno, and it is more beautiful when I am using pure AVRC. Commented Jun 15, 2014 at 16:14
  • Hi guys, I also ended up with the same issue and in my case also we could not use Arduino API, we had to use AVRC. Isn't there any good answer to do this using pure C AVR library. Commented Nov 7, 2021 at 8:08

2 Answers 2

1

Have you looked at the 'Fade' example program?

/*
 Fade

 This example shows how to fade an LED on pin 9
 using the analogWrite() function.

 This example code is in the public domain.
 */

int led = 9;           // the pin that the LED is attached to
int brightness = 0;    // how bright the LED is
int fadeAmount = 5;    // how many points to fade the LED by

// the setup routine runs once when you press reset:
void setup()  { 
  // declare pin 9 to be an output:
  pinMode(led, OUTPUT);
} 

// the loop routine runs over and over again forever:
void loop()  { 
  // set the brightness of pin 9:
  analogWrite(led, brightness);    

  // change the brightness for next time through the loop:
  brightness = brightness + fadeAmount;

  // reverse the direction of the fading at the ends of the fade: 
  if (brightness == 0 || brightness == 255) {
    fadeAmount = -fadeAmount ; 
  }     
  // wait for 30 milliseconds to see the dimming effect    
  delay(30);                            
}

See http://arduino.cc/en/Tutorial/Fade

Sign up to request clarification or add additional context in comments.

Comments

1

Your code seems correct, but you are using timer0, that can generate pwm on Arduino UNO's pin 5 and 6, as shown in the datasheet. So you should set the ddrd bit 6 with a DDRD |= (1 << PD6) , that is pin 6 on Arduino, not pin 11. If you want pwm on pin 11 you should use timer2 instead.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.