Pages: [1]   Go Down
Author Topic: Single Frequency, variable Duty cycle PWM  (Read 1380 times)
0 Members and 1 Guest are viewing this topic.
0
Offline Offline
Newbie
*
Karma: 0
Posts: 1
Arduino rocks
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

I'm in the process of creating an LED array of 12 red LED's and 76 white LED's  (switched), with the hopes of varying the brightness. I've tried creating a 555 timer circuit (which I can never get working) to no avail. I wrote some code that will vary the Duty Cycle directly with the input analog value (ie resistor). Can anybody point out any problems or shortcuts that can be used?

Code:
int potPin=  5;
int ledPin = 11;
int val = 0;


void setup()
{
pinMode(ledPin, OUTPUT);   // sets the pin as output
TCCR2A = _BV(COM2A1) | _BV(COM2B1) | _BV(WGM20);
TCCR2B = _BV(CS22);    
}



void loop()
{
val = analogRead(potPin);    // read the value from the sensor
OCR2A = val;                 //Value of sensor denotes PWM duty cycle
analogWrite(ledPin, HIGH);   //Pulse LED pin with the OCR2A value
}

END
Logged

Offline Offline
Edison Member
*
Karma: 3
Posts: 1001
Arduino rocks
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

If all you need is a PWM output on pin 11, analogWrite will handle all the low level configuration for you. The first argument to analogWrite is the port pin and the second argument is the duty cycle (range 0 to 255). That's all there is to it.

The analogRead function returns values in the range 0 to 1023 so in order to pass this to analogWrite, you can divide the value by 4 to get it into the 0 to 255 range.

Your code should then look something like this:

Code:
byte potPin =  5;
byte ledPin = 11;

void setup()
{
  pinMode(ledPin, OUTPUT);   // sets the pin as output
}

void loop()
{
  byte val = analogRead(potPin) / 4;    // read the value from the sensor
  analogWrite(ledPin, val);   // Start PWM on LED pin with pulse width from potPin
}
« Last Edit: May 23, 2010, 02:20:19 pm by borref » Logged

Pages: [1]   Go Up
Jump to: