Interrupt with Servos

Hi,

Would greatly appreciate some help on my code.
I’m trying to introduce a interrupt, whereby my servo moves at a greater increment than when running normally.
However, whenever I run this program, my interrupt goes crazy and the servo randomly jumps around.

Thanks in advance! =)

#include <Servo.h>

Servo myservo; // create servo object to control a servo
volatile int pos; //position of servo

void setup()
{
myservo.attach(9); // attaches the servo on pin 9 to the servo object
attachInterrupt(0, adjustment, RISING); //creating interrupt on rising edge, pin 2
}

void loop()
{
for(pos = 0; pos <= 180; pos++) // min, max range of servo
{
myservo.write(pos);
delay(10000);
}
}

void adjustment()
{
pos=pos+15;
myservo.write(pos);
}

What triggers an interrupt? A button? How is it wired?

Hi,

Yes. A tactile button. I'm using a single pole normally open. (Grounded when open circuit. Upon closed, connects to Vcc) I've tried push buttons as well but I'm having similar results

Look in the IDE examples (File, Examples, Digital) for the state change example. What is happening is that when you push the button you are generating thousands of interrupts. You need to get it to only generate an interrupt when the button is pushed (goes from off to on). Ton tell the truth I would never use an interrupt to sense a switch. Polling would be better and easier. If set up right, the switch would be polled (checked) several thousand times a second. No way you will miss a press.

In your code you might set your increment (15) as a variable and then change that variable value if a button is pressed. Below is some basic servo button code. You might change the “if” part to determine which size increment you use when the button is pressed prior to the sweep part of the code.

//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);
  }
  else {
    servo1.write(20);
  }
}

Read up on delay function and how it “works” while using interrupts.
Cheers
Vaclav

However, whenever I run this program, my interrupt goes crazy and the servo randomly jumps around.

The pos variable doesn't need to be in int, does it?

Accessing an int outside of an interrupt handler requires more than one machine statement. The interrupt can happen in the middle of accessing the value in loop, resulting in strange values in pos when the interrupt handler ends.

Changing the type to byte will help, since byte access is atomic (takes one machine statement).

Also, a much better description of the actual behavior is necessary.

It would also be necessary to know how your switch is wired.