Friday, November 18, 2011

Sparkfun Inventor's Kit Circ-14

/*     ---------------------------------------------------------

 *     |  Experimentation Kit for Arduino Example Code         |

 *     |  CIRC-14 .: Fancy Sensing :. (Soft Potentiometer)     |

 *     ---------------------------------------------------------

 *

 *    Will fade an RGB LED from Red-Green-Blue in relation to the

 *    soft pot value

 *

 */


// LED leads connected to PWM pins

const int RED_LED_PIN = 9;    //Red LED Pin

const int GREEN_LED_PIN = 10; //Green LED Pin

const int BLUE_LED_PIN = 11;  //Blue LED Pin





void setup() {

  //no need for any code here

}

   

void loop() {

  int sensorValue = analogRead(0);   //read the Soft Pot


  int redValue = constrain(map(sensorValue, 0, 512, 255, 0),0,255); //calculate the red Value (255-0 over the range 0-512)

  int greenValue = constrain(map(sensorValue, 0, 512, 0, 255),0,255)-constrain(map(sensorValue, 512, 1023, 0, 255),0,255);  //calculate the green value (0-255 over 0-512 & 255-0 over 512-1023)

  int blueValue = constrain(map(sensorValue, 512, 1023, 0, 255),0,255); //calculate the blue value 0-255 over 512-1023


  // Display the requested color

  analogWrite(RED_LED_PIN, redValue);

  analogWrite(GREEN_LED_PIN, greenValue);

  analogWrite(BLUE_LED_PIN, blueValue);

}
"http://ardx.org/HSB
To convert from RGB to HSB all that is required is some slightly complicated math. Visit http://ardx.org/CODE14MB based on www.kasperkamperman.com's original code: http://ardx.org/KASP

Faux buttons:
 Define a range of values corresponding to a discrete button.
if(analogRead(0) > minValue && 
analogRead(0) < maxValue) {
buttonAction()
}

Then cover the soft pot with a drawn/printed button pattern."

Sparkfun Inventor's Kit Circuit-13

// Based on File > Examples > Servo > Knob
// Controlling a servo position using a potentiometer (variable resistor)
// by Michal Rinott <http://people.interaction-ivrea.it/m.rinott>

#include <Servo.h>

Servo myservo;  // create servo object to control a servo

int potpin = 0;  // analog pin used to connect the potentiometer
int val;    // variable to read the value from the analog pin

void setup()
{
  Serial.begin(9600);
  myservo.attach(9);  // attaches the servo on pin 9 to the servo object
}

void loop()

{
  val = analogRead(potpin);            // reads the value of the potentiometer (value between 0 and 1023)
  Serial.println(val); 
  val = map(val, 50, 300, 0, 179);     // scale it to use it with the servo (value between 0 and 180)
  myservo.write(val);                  // sets the servo position according to the scaled value
  delay(15);                           // waits for the servo to get there
}


map(value, fromLow, fromHigh, toLow, toHigh)
For full details on how it works: http://ardx.org/MAP
To calibrate the sensor we use the debug window (like in CIRC-11). Open the debug window then replace the fromLow value (default 50) with the value displayed when the sensor is unbent. Then replace the fromHigh (default 300) value with the fully bent value.
                  
void loop()

{
  val = analogRead(potpin);            // reads the value of the potentiometer (value between 0 and 1023)
  Serial.println(val); 
  val = map(val, 269, 140, 0, 179);     // scale it to use it with the servo (value between 0 and 180)
  myservo.write(val);                  // sets the servo position according to the scaled value
  delay(15);                           // waits for the servo to get there


One player rock paper scissors glove:  http://ardx.org/RPS
Electronic plant brace: monitor if your plant is bending towards light and fix it: http://ardg.org/BRACE


Sparkfun Inventor's Kit Circuit-12

/*

  RGB_LED_Color_Fade_Cycle.pde
 
  Cycles through the colors of a RGB LED

  Written for SparkFun Arduino Inventor's Kit CIRC-RGB

*/

// LED leads connected to PWM pins
const int RED_LED_PIN = 9;
const int GREEN_LED_PIN = 10;
const int BLUE_LED_PIN = 11;

// Used to store the current intensity level of the individual LEDs
int redIntensity = 0;
int greenIntensity = 0;
int blueIntensity = 0;

// Length of time we spend showing each color
const int DISPLAY_TIME = 100; // In milliseconds


void setup() {
  // No setup required.
}

void loop() {
  // Cycle color from red through to green
  // (In this loop we move from 100% red, 0% green to 0% red, 100% green)
  for (greenIntensity = 0; greenIntensity <= 255; greenIntensity+=5) {
        redIntensity = 255-greenIntensity;
        analogWrite(GREEN_LED_PIN, greenIntensity);
        analogWrite(RED_LED_PIN, redIntensity);
        delay(DISPLAY_TIME);
  }

  // Cycle color from green through to blue
  // (In this loop we move from 100% green, 0% blue to 0% green, 100% blue) 
  for (blueIntensity = 0; blueIntensity <= 255; blueIntensity+=5) {
        greenIntensity = 255-blueIntensity;
        analogWrite(BLUE_LED_PIN, blueIntensity);
        analogWrite(GREEN_LED_PIN, greenIntensity);
        delay(DISPLAY_TIME);
  }

  // Cycle cycle from blue through to red
  // (In this loop we move from 100% blue, 0% red to 0% blue, 100% red)   
  for (redIntensity = 0; redIntensity <= 255; redIntensity+=5) {
        blueIntensity = 255-redIntensity;
        analogWrite(RED_LED_PIN, redIntensity);
        analogWrite(BLUE_LED_PIN, blueIntensity);
        delay(DISPLAY_TIME);
  }
}


http://ardx.org/HEXCOL

for hexadecimal colors
http://ardx.org/RGBMB

analogWrite(RED_LED_PIN, redIntensity); to analogWrite(RED_LED_PIN, redIntensity/3);

Sparkfun Inventor's Kit CIRCUIT-11

Ever sat in your car with the blinkers on, listening to that metronome like clicking sound as the lights flash on an off and wondered about the programming and mechanics of that simple behavior? Or watched traffic lights flash from color to color and thought about what goes into that?
This is the world of relays, a land of electrically controlled mechanical switches.  The clicking sound is caused by an electromagnet inside the a little plastic box. When it is energized the coil of wire that makes up the electromagnet becomes magnetic and is attracted to the other side of the switch, pulling it towards the magnet and closing a circuit path, kind of like a train track switching device.  When the current stops the switch goes back to its original position, sending the current down a different track.

When you power this circuit up before loading the code, the yellow LED is lit.  Once you load the circuit it starts switching between the yellow and the red LED with that satisfying blinker click (makes me want to compose a song to its measured tick tock beat...!).

The set up involved 1 10k Ohm Resistor, 1 330 Ohm resistor, 1 P2N2222AG (T092) transistor, one 1N4001 Diode (acting as a "flyback diode -- se http://ardx.org/4001), a yellow LED, a red LED and a Relay (Single Pole, Double Throw or "SPDT").  The wiring looks a bit bird's nest intimidating and the pattern didn't quite line up on the breadboard so I had to be careful to hook up all the wires in the right position, but I got it to work.
This is a case where it helps to look at the schematic at http://ardx.org/CIRC11 , where you will also find the code, to see that the 10K resistor (shown as a 2.2kohm resistor on the website and a 10K in the booklet) connects to Arduino pin 2 and to the base of the transistor, with the emitter going to ground and the collector going to the flyback diode and to the relay pin whose other side is connected to the 5V source which picks up the other side (the negative side) of the diode. The middle pin on the part of the relay facing ground in the schematic, which is actually the pin on the LED side of the physical relay,  is connected to +5 volts while the two pins that are parts of the "different train tracks" (and which the middle 5 volt pin switches between) are each connected to the LEDs through their positive sides, with the negative sides going to ground.








/*
  Blink
  Turns on an LED on for one second, then off for one second, repeatedly.
  The circuit:
* LED connected from digital pin 13 to ground.
  * Note: On most Arduino boards, there is already an LED on the board
connected to pin 13, so you don’t need any extra components for this example.
 
Created 1 June 2005
By David Cuartielles

http://arduino.cc/en/Tutorial/Blink

based on an orginal by H. Barragan for the Wiring i/o board
*/

int ledPin =  2;    // Relay connected to digital pin 2 <-----Change this to pin 2

// The setup() method runs once, when the sketch starts

void setup()   {               
  // initialize the digital pin as an output:
  pinMode(ledPin, OUTPUT);   
}

// the loop() method runs over and over again,
// as long as the Arduino has power

void loop()                   
{
  digitalWrite(ledPin, HIGH);   // set the LED on
  delay(1000);                  // wait for a second
  digitalWrite(ledPin, LOW);    // set the LED off
  delay(1000);                  // wait for a second
}



The code here is desperately simple; it is simply the "blink" code used through a relay.  Digital pin 2 is used instead of pin 13 and the rest is exactly what one would use for blinking one LED. The difference is that when pin 2  is powered on (ledPin, HIGH) it makes the relay flip to the "train track" that gives the current to the red LED and when off it reverts to a state where the yellow LED is given current.

The use of a flyback diode is interesting. The wikipedia links tells us, "A flyback diode (sometimes called a snubber diode, freewheeling diode, suppressor diode, or catch diode[1]) is a diode used to eliminate flyback, the sudden voltage spike seen across an inductive load when its supply voltage is suddenly reduced or removed.".

Ever since I started working with Joule Thief circuits I've become fascinated with inductors, wherein a magnetic field is created which, when power is shut off, collapses and creates a voltage.  In the case of a relay this can cause arc-ing so the diode here protects from that.
The book suggests replacing the fly-back diode with a light emitting diode.

Thursday, November 17, 2011

Sparkfun Inventor's Kit Circuit-10: Measuring Temperature

The MIT Sea Perch Sensor Suite that we will be using with the students of Venice High School and the Washington Math Science Technology Public Charter School as we "pimp our Perches" to give them autonomy, will use an Arduino board to measure water temperature, depth, light and conductivity.  In the previous Sparkfun Inventor's Kit Circuit Tutorial they showed us how to measure light and use its intensity to control an LED and a servo using a Photo Resistor.  In Circuit-10 we get to play around with a Precision Temperature Sensor.

The temperature sensor looks identical to a transistor.  It fact it looks so much like the two transistors supplied in the Inventor's Kit that you have to be really careful not to confuse them.  Use a magnifying glass and you can see that the temperature sensor has the tiny letters TMP inscribed on the flat side. The other two say P2N2 222A.  So use the one that doesn't say P2N2 222A. Use the one that says TMP (if you can see it, it is so tiny).

This is "a rather complicated IC (integrated circuit) hidden in a package identical to our P2N2222AG transistors. It has three pins, ground signal and +5 volts and it is easy to use. It outputs 10 millvolts per degree centigrade on the signal pin (to allow measuring temps below freezing there is a 500 mV offet, e.g. 25 C = 750 mV so 0 C = 500 mV)." So sayeth the manual.

This tutorial uses the Arduino IDE's serial monitor so that we can see how it converts the millivolts to degrees.
The TMP36 Datasheet can be found at http://ardx.org/TMP36. The code can be downloaded from http://ardx.org/CODE10

The build on this one is really simple; you just plug in the temp IC and connect the right lead to ground, the middle lead to Arduino's Analog 0 pin and the left lead to 5 Volts. Then you paste the code in the sketch and upload it and open the serial monitor (the icon is a square with an antenna).

Mine starts spitting out data saying it is between 21.78  and 22.27 degrees C in the room.
When I hold the black casing of the IC between my fingers it quickly starts to rise in temperature; after a couple of seconds it is over 26 degrees.

The manual says if you want to see the voltage instead of the temperature, delete the line (or comment it out) that says temperature = (temperature - .5) * 100;

Now when I run it the serial monitor shows the room temperature as .73 which must be 730 mV.  When I touch the sensor with my fingers it goes up to .8 within a few seconds.
We can make the serial monitor display the temperature in Fahrenheit by recalling the formula
F = (C * 1.8) +32).  We add a line that says "temperature = (((temperature - .5) * 100) * 1.8) + 32;" and stick it before Serial.println(temperature);

Instead of doing that, because I'm getting more and more confident hacking the code myself, I wrote
void loop()                     // run over and over again
{
 float temperature = getVoltage(temperaturePin);
 //getting the voltage reading from the temperature sensor

  float temperatureC = (temperature - .5) * 100;          //converting from 10 mv per degree wit 500 mV offset
  float temperatureF = (((temperature - .5) * 100) * 1.8) + 32;                                                //to degrees ((voltage - 500mV) times 100)
 Serial.println(temperatureC);
  Serial.println(temperatureF);
 //printing the result
 delay(1000);                                     //waiting a second
}


That way I got a display that showed me both Celsius and Fahrenheit (and note, I had to declare new floats for my new variables temperatureC and temperatureF which I defined with the math.)

The manual says we can create more informative output by changing Serial.println(temperature); to read  Serial.print(temperature);Serial.println(" degrees centigrade"); and it says "the change to the first line means when we next output it will appear on the same line, then we add the informative text and a new line."

I made my code read the following:

void loop()                     // run over and over again
{
 float temperature = getVoltage(temperaturePin);
 //getting the voltage reading from the temperature sensor

  float temperatureC = (temperature - .5) * 100;          //converting from 10 mv per degree wit 500 mV offset
  float temperatureF = (((temperature - .5) * 100) * 1.8) + 32;                                                //to degrees ((volatge - 500mV) times 100)
 Serial.print(temperatureC);
 Serial.println(" degrees Centigrade");
  Serial.print(temperatureF); Serial.println(" degrees Fahrenheit");
 //printing the result
 delay(1000);                                     //waiting a second
}


Now my serial monitor tells me the room is at "22.7 degrees Centigrade" and "72.08 degrees Fahrenheit." Cool... er...warm!

Finally the manual shows us how to make the data transmission to the serial monitor 12 times faster by changing the baud rate from 9600 to 115200.  Change Serial.begin(9600) to Serial.begin(115200) or any value you want and watch the serial monitor fly!
Oops, when I run it I get garbage output, but that is because I haven't changed the speed in the pull down menu at the bottom of the serial montor to 115200.  So I do that and... voila!






Sparkfun Inventor's Kit Circuit-09: Photo Resistors

Most of the robotics that goes on in the military involves what is called "man in the loop", that is, the presence of a human being controlling the ultimate decisions the robot makes.  And that makes sense, particularly when lethality is involved.  Still, there is an important place for fully autonomous robots, robots that can make critical decisions on their own, and the challenge of creating such "artificial intelligence" is seen by many as the apogee of robotics education.

The Sea Perch program, sponsored by the Office of Naval Research, started out with an underwater rover that was "tethered" through a CAT 5 Ethernet cable and the students, usually middle school age kids, learned to build and solder together the controller, small box like unit that had toggle switches to control the three propeller motors on the submersible.   Going to RC (Radio control) was not considered a viable option because of the difficulty of transmitting radio waves under water, so the next step in "hacking your Sea Perch" (what Daryl Davidson, the hip robotics education specialist and executive director  of the AUVSI (Association for Unmanned Vehicle Systems International) appropriately calls "pimping your Perch") is to "take the man out of the loop" and, through the application of sensors and a micro-controller, give some autonomy to the submersible robot craft.

MIT has been working on exactly that with their Sea Perch Sensor Suite, a kit based on an Arduino board.  It is described as, "a microcontroller-based platform that can be fabricated with minimal tools in a few hours, for under $200. When first fabricated, the sensor monitors:
- Water Temperature
- Depth
- Light
- Conductivity
And can be expanded with basic electronic and computing skills to monitor an assortment of other variables."

If you are working with the Sparkfun Inventor's Kit, Circuit-09 gives you an introduction to the world of autonomy with the introduction of a photo-resistor.  The manual says, "Whilst getting input from a potentiometer can be useful for human controlled experiments, what do we use when we want an environmentally controlled experiment? We use exactly the same principles but instead of a potentiometer (twist based resistance) we us a photo resistor (light based resistance)."

This is the first step in creating a robot that can sense its environment and respond to it.  From the perspective of a marine robotics program, the use of a photoresistor is appropriate since light sensitive organs evolved in the ocean very early on, giving organisms the capability for "phototaxis" or "movement toward or away from light".  This simple behavior can be rather easily done with the arduino, and might be one of the first one should attempt when "pimping the perch" -- i.e. use a photoresistor to make the Sea Perch move up or down,  toward or away from the surface,  based on the amount of light shining down on it (something many squid and plankton do in the ocean!).

The Sparkfun manual tells us that Arduinos cannot directly sense resistance.  They sense voltage, so what is needed is a voltage divider (http://ardx.org/VODI). We don't need to calculate the exact voltage at the sensing pin at this point so this experiment is about sensing relative light values and see what works.  We won't be driving a Sea Perch with this, but using an LED instead of a motor, we will see how the variable amount of light falling on the photoresistor affects the brightness of the LED.  Low voltages (high resistance to the current)  will be produced when the light is shining strongly, and high voltages (less resistance to the current) when it is dark; for a Sea Perch this could be useful so that the robot dives in the day and returns to the surface at night.  For this example daylight will shut off the LED and darkness turn it on, and this is exactly what people use for security lights.

The wiring isn't complex -- just one 330 Ohm resistor and one 10 K resistor, the LED and the Photoresistor, and the code is here:
http://ardx.org/CIRC09:

 /*
* A simple programme that will change the intensity of
* an LED based  * on the amount of light incident on
* the photo resistor.
*
*/

//PhotoResistor Pin
int lightPin = 0; //the analog pin the photoresistor is
                  //connected to
                  //the photoresistor is not calibrated to any units so
                  //this is simply a raw sensor value (relative light)
//LED Pin
int ledPin = 9;   //the pin the LED is connected to
                  //we are controlling brightness so
                  //we use one of the PWM (pulse width
                  // modulation pins)
void setup()
{
  pinMode(ledPin, OUTPUT); //sets the led pin to output
}
/*
* loop() – this function will start after setup
* finishes and then repeat
*/
void loop()
{
int lightLevel = analogRead(lightPin); //Read the
                                        // lightlevel
lightLevel = map(lightLevel, 0, 900, 0, 255);
         //adjust the value 0 to 900 to
         //span 0 to 255

lightLevel = constrain(lightLevel, 0, 255);//make sure the
                                           //value is betwween
                                           //0 and 255
analogWrite(ledPin, lightLevel);  //write the value
}


The code  uses digital pin 9 so that we can use PWM (pulse width modulation) to simulate analog light levels.

When you upload the circuit and put your hand around the photoresistor the LED goes on. If you want the opposite effect, the manual tells us to change the code from analogWrite(ledPin, lightLevel); to analogWrite(ledPin, 255 - lightLevel);
When I try it the light now stays on, even when I put my hand around it or dim the room.  I changed it then to  analogWrite(ledPin, 100 - lightLevel); and I get a dimmer LED but it still won't go out when I cup my hand around it to darken the photoresistor.  Changing the span to span 0 to 100 and constraining the light level to 0,100 and then writing 100 - lightLevel doesn't do much except make the constant LED dimmer. But it works the other way around, with your hand causing the light to go on by blocking light from the Photoresistor.

The next suggestion the manual has is creating a "night light" that turns on based on a threshold value using this code:

void loop() {
int threshold = 300;
if(analogRead(lightPin) > threshold) {
digitalWrite(ledPin, HIGH);
}else {
digitalWrite(ledPin, LOW);
}
}

This unfortunately doesn't work for me; I had to set the int threshold to around 10 to get the light to turn on when I cupped my hand around it.  Nonetheless, it does work with a low enough threshold. Your task is to find out what that threshold is for your environment.

And now we can begin to think about running a Sea Perch motor or a servo based on this principle.
I wire up the servo the way I did in Circuit-08, connecting the white servo wire to the positive lead of the LED which is connected to digital pin 9 on the Arduino, and the red and black servo wires to 5V and ground respectively. Now when I put my thumb over the photoresistor the servo spins and the light goes on, but of course then the servo gets stuck in one position.  I reverse the HIGH and LOW commands and the servo spins in the other direction.  But I can't quite control it yet.

The manual says to load up File>Examples>Servo>Knob from the Arduino sketch library like we did in the last circuit.  When I upload that it makes the light go on and the servo spin to the end of its range and then it just sits and vibrates.  The manual says,
"You'll notice that the servo will only operate over a limited portion of its range. This is because with the voltage dividing circuit we use the voltage on analog pin 0 will not range from 0 to 5 volts but instead between two lesser values (these values will change based on your setup). To fix this play with the val = map(val,0,1023,0,179); line. Hints on what to do are found at: http://arduino.cc/en/Reference/Map."
The manual says we are engaging in "a little bit of Arduino code hacking".  I try messing with the values but can't get much to happen.

It doesn't seem intuitive to me, so I decide to give up and move on; one of the nice things about this field is that you can always circle back later when things seem clearer.  If you get stymied, don't stop, just keep working through different examples!









Sparkfun Inventor's Kit Circuit-08: Potentiometer








Today we look at the use of Potentiometers, a.k.a "variable resistors".  Whats fun about these is that they are provide a window into more natural robotics, in other words, a way to start thinking of sensors that mimic the way we sense the world -- not in binary black and white on off terms, but on a continuum. To mimic analog behavior (where "shades of grey" or "values between 0 and 1" can be interpreted) the Arduino has not just the 14 digital pins (on the left side of the board when the power connector  is facing you) but 6 analog pins (on the right side, top).  They are inputs and they take voltages from 0 to 5V and convert them into digital numbers from 0 to 1024 (the manual says this is 10 bits of resolution). 

When the potentiometer is connected to one of these inputs via its middle lead, and the outer leads are connected to ground and 5 Volts on the board, you can dial it from 0 on one side to 5 Volts on the other, with 2.5 V being the voltage when the arrow is in the center, and use the returned values as variables in the program.

The code from http://ardx.org/CIRC08 is here:

/*
  Analog Input
Demonstrates analog input by reading an analog sensor on analog pin 0 and
turning on and off a light emitting diode(LED)  connected to digital pin 13.
The amount of time the LED will be on and off depends on
the value obtained by analogRead().

The circuit:
* Potentiometer attached to analog input 0
* center pin of the potentiometer to the analog pin
* one side pin (either one) to ground
* the other side pin to +5V
* LED anode (long leg) attached to digital output 13
* LED cathode (short leg) attached to ground

* Note: because most Arduinos have a built-in LED attached
to pin 13 on the board, the LED is optional.

Created by David Cuartielles
Modified 16 Jun 2009
By Tom Igoe

http://arduino.cc/en/Tutorial/AnalogInput

*/

int sensorPin = 0;    // select the input pin for the potentiometer
int ledPin = 13;      // select the pin for the LED
int sensorValue = 0;  // variable to store the value coming from the sensor

void setup() {
  // declare the ledPin as an OUTPUT:
  pinMode(ledPin, OUTPUT); 
}

void loop() {
  // read the value from the sensor:
  sensorValue = analogRead(sensorPin);   
  // turn the ledPin on
  digitalWrite(ledPin, HIGH); 
  // stop the program for milliseconds:
  delay(sensorValue);         
  // turn the ledPin off:       
  digitalWrite(ledPin, LOW); 
  // stop the program for for milliseconds:
  delay(sensorValue);                 
}


What this program does is simply set the delay between turning the LED on and off to whatever the potentiometer is putting out. When you turn it hard left the delay is zero, when you the delay appears to be 1024 or about 1 second (since 1000 milliseconds  is 1 second).


The manual provides a way to make the LED start flashing only when the voltage reaches a certain threshold.  They provide this code to start the flashing when it reaches 512 ms (i.e. half way):

void loop() {
int threshold = 512;
if(analogRead(sensorPin) > threshold) {
digitalWrite(ledPin, HIGH); }
else{digitalWrite(ledPin, LOW);}
}

(I highlight the old void loop() code and comment it out, then paste the above code underneath it).
When you upload this the LED will remain off when the potentiometer arrow angle is anywhere between 0 and the middle and then it turns on when it is in the middle or below.  As they say, "you can adjust the sensitivity by changing the threshold value."

You can also make it fade, controlling the brightness of the LED directly from the potentiometer (you are familiar with this effect from volume knobs on guitars and stereos and amplifiers -- these are examples of potentiometers used to fade sound). To make the LED fade we change the Digital pin connecting the LED to the board from 13 to 9, i.e. int ledPin = 9;      // select the pin for the LED

The manual says to use the following for your void loop():

void loop() {
int value = analogRead(potPin) / 4;
analogWrite(ledPin, value);
}

When you try to compile this, of course, you'll get the error "potPin was not declared in this scope" This is obviously a typo (or a way to test how well we are now understanding programming at this point!).

Change it to sensorPin and you are golden! (int value = analogRead(sensorPin) / 4;)

void loop() {
int value = analogRead(sensorPin) / 4;
analogWrite(ledPin, value);
}
Why divide by 4? The manual says, "the analogRead() function returns a value from 0 to 1024 (10 bits) while the analogWrite() takes a value from 0 to 255 (8 bits)." So a lot of what one does to get one thing talking to another is to do conversion math so the scales match up.  As Einstein pointed out, everything is relative!

Now that we can control the brightness of an LED, the implication is that we can control a lot of variable elements. The book suggests combining lessons and control a servo with a potentiometer.

What I did, for fun, was to add the servo to CIRC-08 by putting my three-pin header down on the breadboard at holes 22, 23 and 24. Then I connected my servo and used a white wire to connect the Servo's white signal wire  to the hole  next to the positive pin of the LED on the board. Then I connected a red wire next to the Servo's red wire to the positive +5 V rail of my breadboard, and a black wire next to the Servo's black wire and then to the negative (gnd) rail of the breadboard. Then, without uploading any additional code, keeping the void loop() above,  I was able to use the potentiometer to control both the brightness of the LED and the position of the Servo.

The manual says to wire up the servo as we did in CIRC-04, and use the code from the example program in Arduino called "Knob" (File>Examples>Servo>Knob) and change one line of code:
int potpin = 0; ---> int potpin = 2; (be careful, potpin has all small p's, while  the usual convention is that the second work gets a cap! Misspelling can cause an error!)
Now your Servo should turn as you turn the potentiometer!

So I went ahead and uploaded the Example Knob file:

// Controlling a servo position using a potentiometer (variable resistor)
// by Michal Rinott <http://people.interaction-ivrea.it/m.rinott>

#include <Servo.h>

Servo myservo;  // create servo object to control a servo

int potpin = 0;  // analog pin used to connect the potentiometer
int val;    // variable to read the value from the analog pin

void setup()
{
  myservo.attach(9);  // attaches the servo on pin 9 to the servo object
}

void loop()
{
  val = analogRead(potpin);            // reads the value of the potentiometer (value between 0 and 1023)
  val = map(val, 0, 1023, 0, 179);     // scale it to use it with the servo (value between 0 and 180)
  myservo.write(val);                  // sets the servo position according to the scaled value
  delay(15);                           // waits for the servo to get there
}


and then changed int potpin  = 0;  to int potpin =2; .

But nothing happened.  So I looked at the code and looked at my board and realized there was no need to change int potpin = 0; to intpotpin = 2; because the center lead of my potentiometer was already connected to analog input 0, not 2.  So there are some discrepancies in the manual. The schematic for CIRC-08 shows the potentiometer connecting to Arduino analog pin 0 and the code says int sensorPin = 0;  but then in the "Not Working" section they say "make sure you haven't accidentally connected the potentiometer's wiper to digital pin 2 rather than analog pin 2 (the row of pins beneath the power pins).  So from then they seem to be assuming you are hooked up to pin 2. Just be consistent and everything should work out fine!

The thing is, you don't really need this example sketch, which calls a library called "Servo.h" since you can use the potentiometer sketch above as well. But it is great to play with all this.