PWM Programming Help

Hi,

I'm trying to do PWM using an RGB LED connected to digital pins (I cannot change the wiring). I'm basically trying to turn the LED on and off very quickly, slowly increasing the time in-between on and off stages with a for loop. Here's what I've got so far:

int redPin = 4;
int greenPin = 3;
int bluePin = 2;

void setup(){
  Serial.begin(9600);
  
   pinMode(redPin, OUTPUT);
   pinMode(greenPin, OUTPUT);
   pinMode(bluePin, OUTPUT);
 }

void loop() {
  
  
 for(float i = 0; i <= 10; i += .1) {
  digitalWrite(bluePin, HIGH);
  delayMicroseconds(i);
  digitalWrite(bluePin, LOW);
  delayMicroseconds(i);
 }
  
}

Right now the LED is not changing in brightness. How might I get this PWM method to work?

Thanks for the help

That for loop is over with in around 100ms. I think it is way too fast for you to ever see what's going on.

It is also always a 50% duty cycle since the on time and off time are always the same, so it will be the same brightness all the time.

Why don't you use one of the built in PWM outputs?

Why don't you use one of the built in PWM outputs?

Bingo, he should be using analogWrite commands on the pins that support pwm outputs rather then trying to 'roll his own' PWM outputs.

Lefty

Hey Guys,

Here's the arduino.cc example code I tried out originally:

int ledPin = 2;    // LED connected to digital pin 2

void setup()  { 
  pinMode(2, OUTPUT);
} 

void loop()  { 
  // fade in from min to max in increments of 5 points:
  for(int fadeValue = 0 ; fadeValue <= 255; fadeValue +=5) { 
    // sets the value (range from 0 to 255):
    analogWrite(ledPin, fadeValue);         
    // wait for 30 milliseconds to see the dimming effect    
    delay(100);                            
  } 

  // fade out from max to min in increments of 5 points:
  for(int fadeValue = 255 ; fadeValue >= 0; fadeValue -=5) { 
    // sets the value (range from 0 to 255):
    analogWrite(ledPin, fadeValue);         
    // wait for 30 milliseconds to see the dimming effect    
    delay(100);                            
  } 
}

The LED turns on for a couple seconds than off for about twice as long. Since I'm using digital pins I tried the same with digitalWrite to no avail. Any tips?

There's nothing in the code that would cause that. How is the LED connected?

int ledPin = 2;    // LED connected to digital pin 2

Pin 2 is not a PWM pin. Only 3, 5, 6, 9, 10, and 11 on the UNO. There is a little '~' next to the PWM pins on the board.

If you use analogWrite() on a non-PWM pin you get LOW for values below 512 and HIGH for higher values.

johnwasser:
If you use analogWrite() on a non-PWM pin you get LOW for values below 512 and HIGH for higher values.

128, not 512.

			case NOT_ON_TIMER:
			default:
				if (val < 128) {
					digitalWrite(pin, LOW);
				} else {
					digitalWrite(pin, HIGH);
				}

Oops. I got analogWrite (0-255) and analogRead (0-1023) confused in my brain. Sorry. 128 is the correct cut-off.