October 6, 2008

Week 4 - Servos and Photocells

So, this simple lab was incredibly useful to me.  Even though we had spent several classes talking about the importance of resistors in the analog pipeline, I conveniently forgot where and how to implement them.  I wired my breadboard just fine and made sure to get my hands on the proper code, it wasn’t until I dropped a resistor on the same bus as the analog in and connected it to ground did I realize exaclt why it was necessary.  My understanding might be limited but I am going to attempt to explain why I think it worked.  If I understand it correctly it’s because the electricity in the circuit needs a bumper of sorts from dissipating through the board.  Or to put it another way the resistor linking it to ground creates a closed system so electricity moving through the photocell has another discreet channel to move through.  I hope someone who understands this can either correct me or tell me why I’m wrong.

Anyway, once the wiring was good and I realized the value range coming off of the photocell was consistent within a certain range I just adjusted the code accordigly so the values were mapped properly.  I think my next step will be to throw a potentiometer on there and see if I can control the motor with more precision.


Servo and a photocell

Here’s my code:

int servoPin = 2;     // Control pin for servo motor
int minPulse = 500;   // Minimum servo position
int maxPulse = 2500;  // Maximum servo position
int pulse = 0;        // Amount to pulse the servo

long lastPulse = 0;    // the time in milliseconds of the last pulse
int refreshTime = 20; // the time needed in between pulses

int analogValue = 0;  // the value returned from the analog sensor
int analogPin = 0;    // the analog pin that the sensor’s on

void setup() {
pinMode(servoPin, OUTPUT);  // Set servo pin as an output pin
pulse = minPulse;           // Set the motor position value to the minimum
Serial.begin(9600);
}

void loop() {
analogValue = analogRead(analogPin);      // read the analog input
pulse = map(analogValue,50,500,minPulse,maxPulse);    // convert the analog value
// to a range between minPulse
// and maxPulse.

// pulse the servo again if rhe refresh time (20 ms) have passed:
if (millis() - lastPulse >= refreshTime) {
digitalWrite(servoPin, HIGH);   // Turn the motor on
delayMicroseconds(pulse);       // Length of the pulse sets the motor position
digitalWrite(servoPin, LOW);    // Turn the motor off
lastPulse = millis();           // save the time of the last pulse
}
}