Paso 3: El código
El código también es mínimo. Sólo consiste en una sola sentencia condicional if-else. Constructor deberá ajustar la posición del servo según su modelo específico. Ajustar el movimiento del servo se llevará mucho trucaje!
/* Richard Solomon<br> MAKE course Spring 2015 */
#include //import Servo library
Servo myServo; //naming the servo int toggleSwitch = 8; //declaring toggleSwitch as a variable
void setup() { myServo.attach(9); //attaches servo to pin 9 to receive servo position Serial.begin(9600); // initialize serial communication at 9600 bits per second: pinMode(toggleSwitch, INPUT); //attach toggleswitch to pin 8 to receive serial data }
// the loop routine runs over and over again forever: void loop() { int switchState = digitalRead(toggleSwitch); //reads binary position of digital pin input #8, toggleSwitch, //and assigns to variable "switchState" where 0=OFF, 1=ON int pos=20; // "OFF" position for servo if (switchState==0) //if switch is turned OFF { delay(150); //wait 150ms //delays are for stability Serial.println("OFF"); //print "OFF" to serial monitor myServo.write(115); //ensure servo is in initial OFF position Serial.println(115); //writes servo position to serial monitor delay(25); //wait 25ms } else if (switchState==1) //if switch is turned ON { delay(150); //wait 150ms Serial.println("ON"); //print "ON" to serial monitor myServo.write(35); //extends servo arm by rotating 80° Serial.println(35); //writes servo position to serial monitor delay(25); //wait 25ms } }