Skip to content

Instantly share code, notes, and snippets.

@ElectricImpSampleCode
Last active August 29, 2015 14:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ElectricImpSampleCode/2431c93ed9f95cc7e8bb to your computer and use it in GitHub Desktop.
Save ElectricImpSampleCode/2431c93ed9f95cc7e8bb to your computer and use it in GitHub Desktop.
Example code to control a servo motor connected to an imp. It makes use of the imp’s PWM_OUT GPIO pin setting.
// These constants may be different for your servo
const SERVO_MIN = 0.03;
const SERVO_MAX = 0.1;
// Create global variable for the pin to which the servo is connected
// then configure the pin for PWM
servo <- hardware.pin7;
servo.configure(PWM_OUT, 0.02, SERVO_MIN);
// Define a function to control the servo.
// It expects a value between 0.0 and 1.0 to be passed to it
function setServo(value) {
local scaledValue = value * (SERVO_MAX - SERVO_MIN) + SERVO_MIN;
servo.write(scaledValue);
}
// Define a function to control the servo.
// It expects an angle value between -80.0 and 80.0
function setServoDegrees(value) {
local scaledValue = (value + 81) / 161.0 * (SERVO_MAX - SERVO_MIN) + SERVO_MIN;
servo.write(scaledValue);
}
// Set the initial position (we'll flip between 0 and 1)
position <- 0;
// Define a function to loop through the servo position values
function sweep() {
// Write the current position
setServo(position);
// Invert the position
position = 1.0 - position;
// Call the function again (ie. loop) in half a second:
imp.wakeup(1.0, sweep);
}
// Start the ball rolling by calling the loop function
sweep();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment