Servo Code

From STEAMwiki
Revision as of 00:46, 1 March 2018 by Andy (talk | contribs)
Jump to: navigation, search

Here's a basic code snippet which make toggle the motor between two positions, based on this github project by ThaWeatherman.

Servo wiring:

Brown GND
Red Vin
Orange D0

For particle Photon, use D0, D1, D2, or D3 for the Orange signal wire for the best results. These pins can use the Particle chip's hardware timer. Connect the Red servo power wire to the VIN pin on the Particle Photon to supply the servo with 5V instead of 3.3V. Connect the Brown servo wire to GND.

Servo serv;
 
void setup() {
    serv.attach(D0);
}
 
void loop() {
    serv.write(90);
    delay(1000);
    serv.write(40);
    delay(1000);
}

Servo Code Example for Robot Claw:

#include <Servo.h>
#define clawPin 9
#define closeAngle_claw 45
Servo clawServo; 

int pos = 0;    // variable to store the servo position

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

void loop() {
  openClaw();
  delay(1000);
  closeClaw();
  delay(1000);
}








void closeClaw(){
   
  for (pos = 0; pos <= closeAngle_claw; pos += 1) { // goes from 0 degrees to 180 degrees
    // in steps of 1 degree
    clawServo.write(pos);              // tell servo to go to position in variable 'pos'
    delay(25);                       // waits 15ms for the servo to reach the position
  }
}

void openClaw(){
  for (pos = closeAngle_claw; pos >= 0; pos -= 1) { // goes from 180 degrees to 0 degrees
    clawServo.write(pos);              // tell servo to go to position in variable 'pos'
    delay(25);                       // waits 15ms for the servo to reach the position
  }
}