Newbie: Interrutp/Volatile access to Servo

I am trying to build a robot for my son.

The way it works is: he sends a string via serial port. The robot moves.

I want to add an interrupt that stops the servos when a drop-off is sensed.

How is the easiest way to access the servos in volatile/interrupt way?

Thanks a lot!!

Depends on what your current code looks like.

thanks!

It doesn't look like much:

Globals:

Motion m = Motion(0, 0, false); <-our library
volatile Motion * m_interrupt = &m;

Setup:

void setup(){
attachInterrupt(0, freeFalling, FALLING);
Serial.begin(9600);
}

ISR:

void freeFalling(){
m_interrupt->dettach();
}

Our user defined type:

class Motion{
private:
Servo left;
Servo right;
....

public:
void dettach() volatile;
....
}

void Motion::dettach() volatile{
left.detach();
right.detach();
}

And it doesn't compile of course :-}

Using m instead of m_interrupt:

void freeFalling(){
m.dettach();
}

Compiles. But would this provide the behavior we need? At first sight it seems so...

Why do you want to detach the servo if the interrupt is triggered? What good is an unpowered servo? Shouldn't you stop the servo, instead? Perhaps back up, even, and change direction?

Good question :-}

I also found out that by themselves the sensors do not provide meaningful info :-}

Half-baked thoughts.

So instead of interrupts I will write microseconds to the servos after checking the sensors..

bichito:
I want to add an interrupt that stops the servos when a drop-off is sensed.

If you mean that you want your robot to sense when it is reaching the edge of a surface, this is not a problem that calls for using interrupts. It is just a case of dealing with events from two (or more) sources. You can achieve that using the non-blocking approach demonstrated in the 'blink without delay' example, although that example doesn't make it at all obvious how important this non-blocking approach is.

The approach would be to write some code that tests for input available on the serial port. If it's available, it reads it. If the message is complete and ready to be processed, it processes it. It does this without waiting - if there is no input, or the input message isn't complete, the code just carries on. Call this code from loop() so that it runs repeatedly.

Add another piece of code that reads the state of your 'edge detection' sensor inputs and decides whether the 'bot needs to stop. If it does, stop the bot. Call this from loop() too, so that it runs repeatedly.

Now that your loop() function is running repeatedly without stopping, you can also use it to do other things such as making LEDs blink, using the code demonstrated in 'blink without delay'. You can add as many independent features as you want, subject to the Arduino's limited memory and processing power, without any of them needing to know about each other.