/* * JoystickSerialServo * -------------- * Servo control with a PC and Joystick * * Created 19 December 2007 * copyleft 2007 Brian D. Wendt * http://principialabs.com/ * * Adapted from code by Tom Igoe * http://itp.nyu.edu/physcomp/Labs/Servo */ /** Adjust these values for your servo and setup, if necessary **/ int servoPin = 3; // control pin for servo motor int minPulse = 600; // minimum servo position int maxPulse = 2400; // maximum servo position int refreshTime = 20; // time (ms) between pulses (50Hz) /** The Arduino will calculate these values for you **/ int centerServo; // center servo position int pulseWidth; // servo pulse width int servoPosition; // commanded servo position, 0-180 degrees int pulseRange; // max pulse - min pulse long lastPulse = 0; // recorded time (ms) of the last pulse void setup() { pinMode(servoPin, OUTPUT); // Set servo pin as an output pin pulseRange = maxPulse - minPulse; centerServo = maxPulse - ((pulseRange)/2); pulseWidth = centerServo; // Give the servo a starting point (or it floats) Serial.begin(9600); } void loop() { // wait for serial input if (Serial.available() > 0) { // read the incoming byte: servoPosition = Serial.read(); // compute pulseWidth from servoPosition pulseWidth = minPulse + (servoPosition * (pulseRange/180)); // stop servo pulse at min and max if (pulseWidth > maxPulse) { pulseWidth = maxPulse; } if (pulseWidth < minPulse) { pulseWidth = minPulse; } // debug //Serial.println(servoPosition); } // pulse the servo every 20 ms (refreshTime) with current pulseWidth // this will hold the servo's position if unchanged, or move it if changed if (millis() - lastPulse >= refreshTime) { digitalWrite(servoPin, HIGH); // start the pulse delayMicroseconds(pulseWidth); // pulse width digitalWrite(servoPin, LOW); // stop the pulse lastPulse = millis(); // save the time of the last pulse } }