Please excuse me if this subject has been aired before, I did find an answer in this forum but I only wish to clarify this in my own mind.
As you will have guessed I'm new here, so please excuse my ignorance.
I've attached a servo and a switch to the mega using the code below, I've also attached a 12 supply to the mega to reduce the load on the USB port, which I understand can't handle the current needeed to drive the servo. This seems to work but the mega keeps resetting randomly when I throw the switch. Do I need to supply independant power to the servo and simply join the grounds?
Thanks in advance for your patience.
// Switch
// by Caspajack
// part of this example code taken from sweeep
#include <Servo.h>
Servo myservo; // create servo object to control a servo
int pos = 0; // variable to store the servo position
int pos1 = 170;
void setup()
{
myservo.attach(9); // attaches the servo on pin 9 to the servo object
pinMode(4,INPUT); // attach the switch between pin 4 and ground
pinMode (9,OUTPUT);
digitalWrite(4,HIGH); // initialise resistor on pin 4
}
void loop()
{
if (digitalRead(4)==HIGH)
{myservo.write(pos); // If switch thrown move servo to 'pos'
delay(15);}
else
{myservo.write(pos1); // tell servo to go to position in variable 'pos1'
delay(15);} // waits 15ms for the servo to reach the position
}