hi, I'm pretty new here, so please, if this is in the wrong section please point this out, but I'm trying tio make an led turn on when I press a button and also at the same time I'm trying to move a servo. I'm having a problem though, I seem to nopt be able to turn the damn thing off, servo turns but ld just stays lit, any ideas where I'm going wrong?
I have rewrite your code using an interrupt (more information about interrupts). I don't understand your servo code, but I think it isn't hard to add it yourself. I haven't tested the code... but it should work
#include <Servo.h>
const int buttonPin = 8;
const int servoPin = 9;
const int ledPin = 13;
bool btnState = 0;
int previous = LOW;
int directionState=0;
Servo servoOne;
int pos = 0;
void setup()
{
servoOne.attach(9);
servoOne.write(directionState);
pinMode(buttonPin, INPUT_PULLUP);
pinMode(ledPin, OUTPUT);
attachInterrupt(buttonPin,btnPressed, RISING);
}
void loop()
{
if (btnState) {
btnState=LOW;
if(previous) {
previous=LOW;
digitalWrite(ledPin, LOW);
//YOUR SERVO CODE HERE
}
else {
previous=HIGH;
digitalWrite(ledPin, HIGH);
//YOUR SERVO CODE HERE
}
}
}
void btnPressed() {
btnState = HIGH;
}
If your polling is fast enough, then you won't miss it. Also, depending on the switch, then the bounce may cause some problems.
If you add a RC debounce circuit, then you will end up with a long duration signal, longer than necessary for the arduino but much shorter than a persons reaction time.
I do agree that there are many cases where using an interrupt may be a better idea.