|
Explore TEAMS!
|
THS /
Controlling servos; Using PWM for dimming lights and DC motor speed controlUsing a servo is really easy--it only takes 3 wires + 4 lines of code!Connecting Your Servo to the Arduino
Controlling (programming) your servo in three easy steps1. Include the servo library at the top of your code (next to the #define statements, above the "main" program). The extra line of code you need is shown in green below. Note that I am plugging the LEDs into pins 3 and 11, which will allow me to use PWM to dim them if I choose to do so! (see really easy PWM dimming instructions at the bottom of the page)
// Definitions and Included Libraries...
#define GreenLED 11
#define RedLED 3
#define button_pressed 0
#include <Servo.h>
2. Declare servo variables in the same place you declare other (int, long, float, etc.) variables. Then initialize (attach) the servo variable to work with a particular digital I/O pin (extra line of code is shown in blue below). Note that you can control up to 12 servos at once (each would need a declared variable and attach statement).
//Main Program Variable Declarations and Initialization
int counter = 1;
float Sharp_distance;
Servo prettyservo_9; //declare a new variable of type Servo
prettyservo_9.attach(9); //I'm plugging into PWM I/O pin 9
Serial.begin(9600);
Note: if you plan to control your servo in any functions that you call, you should move the type declaration statement (in green above) just above the void setup() line
3. Control your servo (tell it what position to go to useing a servoname.write(degrees); command). You can send an input in degrees from 0 to 180, but don't expect the degree positions to be 100% accurate. I you want to be picky and fine tune your servo to move exacatly from 0 - 180 degrees, you can use the two optional paramters in the servo.attach(a,b,c) function to do so (I wouldn't waste my time). See sample line of code in green below. Note that you only need to tell a servo to go to a position once, and it will stay in that position until your tell it otherwise! Example in green...
prettyservo_9.write(180); //moves servo to "180 degree" position
//la-ti-da I'm doing some other stuff...but the servo stays locked into 180 degrees
//Now suppose it's time to move my servo to a different postion...
prettyservo_9.write(45); //moves servo to "45 degree" position
//la-ti-da, now I'll go off and do some other stuff, but my servo will stay locked in place!
4. Now try running these demo programs. Cut & paste into the Arduino IDE, save, compile, download, and watch it run. You should read the comments to see what to attach for hardware.
Using PWM for DC motors and lights--it's even easier!!This is even easier to use than the servo commands. Remember, pulse width modulation can be used as a "dimmer" for lights/LEDs and as a speed controller for motors (without sacrificing power or torque) To control the device using PWM, you use the analogWrite(pin_number,PWM_setting) function
|