analogWrite broken?

here's my code

int h;

void setup()
{
      Serial.begin(9600);
      pinMode(A0,INPUT);
      pinMode(5,OUTPUT);    
      pinMode(7,OUTPUT);
      digitalWrite(7,HIGH);
      
}


void loop()
{
     analogWrite(5,150);
      h = analogRead(A0);
  
       Serial.println(h);
   
        delay(500);    
     
     
}

i essentially shorted pin5 to input A0. What's wrong?? why is it intermittent?

0
994
0
994
0
995
0
994
0
994
0
994
0
994
0

when i made pin9 the input pin, this printed:

229
232
233
236
239
243
247
250
253
252
253
253
253
251
247
245
241
239
236

i set analogWrite to a constant level why's it fluxuating so much?

In the first case you are reading a PWM signal, have a search for PWM and you'll see that the results are as expected. In the second case pin 9 is a digital pin, so I don't know how you're getting those values.

on my arduino uno pin 9 is labelled as a PWM pin.

another strange thing, when i set pinmodes to INPUT, and short that pin with ground, console should display 0 but i still get random numbers. thoughts?

bmarconi: when i made pin9 the input pin, this printed:

What board? An UNO doesn't have a 9 that can do analog input.

Look up how PWM works and see if you don't understand. I'll give you a hint, the voltage on the pin is either 5V or 0V and never anything in between. If you truly want a steady voltage between 0 and 5 then you need a DAC, not PWM.

[quote author=bmarconi ]

i essentially shorted pin5 to input A0. What's wrong?? why is it intermittent? [/quote]

It's PWM. It's either on or off.

analogWrite is a silly name for it. PWMwrite would be better.

In my opinion yes, analogWrite() is broken, and was broken from the very beginning. It does work "as documented"; however, analogWrite() does not create an analog output voltage so you can't read the output from analogWrite() with analogRead(). analogWrite() creates a PWM output frequency that when used with something like an LED will trick the human eye to see a variable brightness.

analogWrite() was a horrible name for a function that outputs a digital pwm signal. Also, analogWrite() uses a digital pin# while analogRread() uses an analog pin# the two numbering spaces are different and represent different pins. i.e. analog pin #2 is not the same as digital pin #2.

And this is why in my opinion analogWrite() was broken from the very beginning......

What would have been better, in my opinion would have been to have digitalWrite() also do pwm. It could have been done, by using LOW to mean set output to GND and HIGH to mean set output to Vcc, and then as long as HIGH was defined properly, (255, instead of the 1 that it currently is), then any value between low and HIGH could have been a pwm output.

--- bill