With the Tilt Sensing Servo Motor Controller circuit built on the full-size clear breadboard, it’s time to upload the sketch:
- Attach the Arduino to your computer using a USB cable.
- Open the Arduino software and type Example 3-1 into the software’s text editor.
- Upload the sketch to the Arduino.
- Rotate the tilt control switch back and forth. The servo motor will spin in the same direction as the tilt control switch orientation.
TROUBLESHOOTING TIP
Rotate the tilt control switch slowly and smoothly to get the best response from the servo motor.
Example 3-1. Tilt Control Switch sketch
/* This sketch controls a servo motor using a tilt control switch!
*
* 12 December 2012
* by Don Wilcher
*
*/
#include<Servo.h> // include Servo library
int inPin = 2; // the tilt control switch is wired to Arduino D2 pin
int reading; // the current reading from the input pin
Servo myservo; // create servo motor object
void setup()
{
myservo.attach(9); // attach servo motor to pin 9 of Arduino
pinMode(inPin, INPUT); // make pin 2 an input
}
void loop()
{
reading = digitalRead(inPin); // store digital data in variable
if(reading == HIGH) { // check digital data with target value
myservo.write(180); // if digital data equals target value,
// servo motor rotates 180 degrees
delay(15); // wait 15ms for rotation
}
else { // if reading is not equal to target value,
myservo.write(0); // rotate servo motor to 0 degrees
delay(15); // wait 15ms for rotation
}
}
Leave a Reply