PWM question

Why pwm change the brightness?

In analogwrite you give the pin and the cycle duty. By default arduino has 500Hz frequency. If i make a code that does a digitalWrite to a digital pin and i use it to set the pin to High and Low with delay of 1 mil between i can make a pulse of 500Hz with duty cycle of 50%. But if i do it with PWM and set analogwrite to 177 i can see that the led is not steady.

#include <Arduino.h>

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

int analogPin = 3;   // potentiometer connected to analog pin 3

int val = 0;         // variable to store the read value



void setup() {                

  Serial.begin(9600);
  pinMode(ledPin, OUTPUT);
  pinMode(a1, OUTPUT);
}

void loop() {


	 val = analogRead(analogPin); // read the input pin
	 Serial.println(val);
	 int x=val/4;
	 analogWrite(ledPin, x);  // analogRead values go from 0 to 1023, analogWrite values from 0 to 255
	 Serial.println(x);


	 digitalWrite(ledPin,HIGH);
	 delay(1);
	 digitalWrite(ledPin,LOW);
	 delay(1);
	 digitalWrite(ledPin,HIGH);
	 delay(1);
	 digitalWrite(ledPin,LOW);
	 delay(1);

why is this happening it is the same frequncy and duty cicle the led should be steady.

In that snippet of code your software synthesized PWM will not be steady. You will get 2 pulses that are with a nice 2ms period and 50% duty cycle, then a big gap while you do your analog read, calculations, and analog write.

Why pwm change the brightness?

http://www.thebox.myzen.co.uk/Tutorial/PWM.html

But if i do it with PWM and set analogwrite to 177 i can see that the led is not steady.

No you can't.

That code is not doing what you think. There is a serial print in there, that takes time. Then you are using the same pin as a PWM output and then a digital output. The loop function runs very fast and what you are doing is all messed up.