[Arduino and LED wired for analog output]

Analog output

You can write analog values, too -- but only on certain pins. Use digital 9, 10, and 11. (That seems confusing, I know.)

Try moving your LED lead from pin 13 to pin 9. Keep everything else the same.

Now open a new sketch: File->Examples->03.Analog->AnalogInOutSerial

Now what happens when you twist the dial?

How does it work?

In the AnalogInOutSerial sketch, you'll see a line like this:

  analogWrite(analogOutPin, outputValue);

So what is analogOutPin? If you look earlier in the sketch, you'll see:

const int analogOutPin = 9;

But you'll also see these lines:

  // read the analog in value:
  sensorValue = analogRead(analogInPin);            
  // map it to the range of the analog out:
  outputValue = map(sensorValue, 0, 1023, 0, 255);  

[Map from 1023 to 255]

Those are because analogRead gives you values between 0 and 1023, but analogWrite can only take values between 0 and 255. So map takes the values you read, from 0 to 1023, and shrinks them down to make sure they aren't too big to write.

Debugging with the serial console

When you're writing a program, it can be really useful to print out the values you're reading, in case they're not what you expect.

To print something out, first do this inside setup():

  Serial.begin(9600);

Then you can print things out inside loop() like this:

  Serial.print("sensor = ");
  Serial.println(sensorValue);

print means print something without a new line after it, while println means print something and end the line.