My intention was to use a servo motor to rattle a snake tail necklace that I have. I envisioned a shoe-box marked “DANGER” that hid an ultra-sonic sensor, which upon detecting the close proximity of a curious ITP student, would rattle the tail.
I couldn’t find my snake necklace, so I fashioned a rattle from some plastic tubing, lamp chain & wood scraps (oops, Sara I still have your green screwdriver). This fabrication took abnormally long since the screw for the servo attachments does not like to thread tightly, and after a very long series of trials and errors, I just hot-glued the dang thing.
Here is the code for the prototype with a potentiometer instead of the ultrasound.
int servoPin = 5; // 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 minValue;
long maxValue;
int midValue=1400;
// flag to determine if we should be constantly moving
long lastSensorReading = 0;
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 = midValue; // Set the motor position value to the minimum
Serial.begin(9600);
}
void loop() {
analogValue = analogRead(analogPin); // read the analog input
minValue = 1300 - ((700*analogValue)/1023);
maxValue = 1500 + ((700*analogValue)/1023);
Serial.print("minVal: ");
Serial.print(minValue, DEC);
Serial.print(" maxVal: ");
Serial.println(maxValue, DEC);
// pulse the servo again if the refresh time of 20 ms has passed:
if (millis() - lastPulse >= refreshTime) {
// check the force sensor every second
int accel = map(analogValue, 0, 1023, 100, 500);
if (millis() - lastSensorReading >= accel) { //SPEED
Serial.println(analogValue);
// if we are still reading a high value from the pressure sensor,
// determine the next position of the servo motor
// if (analogValue > 400) {
// if (pulse >= 2200)
// { pulse = 600; } // TWO POSITIONS
// else { pulse = 2200; }
if (pulse >= maxValue) { pulse = minValue; } // TWO POSITIONS
else { pulse = maxValue; }
// }
lastSensorReading = millis();
}
//Serial.println(pulse);
// tell the servo motor to move to it's new position
digitalWrite(servoPin, HIGH); // Turn the motor on
delayMicroseconds(pulse); // servo moves to new locale
digitalWrite(servoPin, LOW); // Turn the motor off
lastPulse = millis(); // save the time of the last pulse
}
}
Add your comment below, or trackback from your own site.
Subscribe to these comments.
Be nice. Keep it clean. Stay on topic. No spam.
You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>