I am encountering a weird error. My program is meant to rotate my servo to 90 degrees when I flick a switch one way, and rotate back up when I flick it the other way. I am doing this by running the arduino's 5 volts through the switch and into the 7th digital pin. When I turn it off, it waits around 8 seconds and then turns and it also grinds the gears. It rotates back when I flip the switch back. I am using a Generic (Sub-Micro) Servo from SparkFun.
Here is my code:
#include<Servo.h>
Servo my_servo;
int servo_state = 0;
int pos = 0;
void setup()
{
my_servo.attach(12);
pinMode(7,INPUT);
my_servo.write(0);
Serial.begin(9600);
}
void loop()
{
if (digitalRead(7) == HIGH && servo_state == 0)
{
my_servo.write(90);
delay(5);
servo_state = 1;
}
if (digitalRead(7) == LOW && servo_state == 1)
{
my_servo.write(0);
delay(5);
servo_state = 0;
}
if (digitalRead(7) == HIGH)
{
Serial.print('high');
}
if (digitalRead(7) == LOW)
{
Serial.print('low');
}
}
Is there anything in there that would be causing the servo delay? Or is this something to do with the hardware?
No. The problem is a floating pin. Wire your switch correctly to prevent it. One leg to the digital pin and one leg to ground, and turn on the internal pullup resistor (INPUT_PULLUP).
Serial.print('high');
Would you post a picture of your keyboard, with the ONE key that you pressed to get the ONE character in single quotes there?
//zoomkat servo button test 7-30-2011
//Powering a servo from the arduino usually *DOES NOT WORK*.
#include <Servo.h>
int button1 = 4; //button pin, connect to ground to move servo
int press1 = 0;
Servo servo1;
void setup()
{
pinMode(button1, INPUT);
servo1.attach(7);
digitalWrite(4, HIGH); //enable pullups to make pin high
}
void loop()
{
press1 = digitalRead(button1);
if (press1 == LOW)
{
servo1.write(160);
}
else {
servo1.write(20);
}
}
//zoomkat servo button test 7-30-2011
#include <Servo.h>
int button1 = 4; //button pin, connect to ground to move servo
int press1 = 0;
Servo servo1;
void setup()
{
pinMode(button1, INPUT);
servo1.attach(7);
digitalWrite(4, HIGH); //enable pullups to make pin high
}
void loop()
{
press1 = digitalRead(button1);
if (press1 == LOW)
{
servo1.write(160);
delay(2000);
servo1.write(20);
}
}