global variables... i guess

Hi all.
this is my very first message in the community.
I quit C++ programming a while ago...

I am trying to implement a very simple routine, to control a servomotor pressing the button of the joystick.

basically I want to start and stop the motor by clicking the joystick button.

i made a routine to check the button and toggle a boolean if the button is pressed; I call the routine at every loop of both "for loops" and use the boolean to control the loops.

the behavoir is quite dodgy; I had to put a delay(10) in the routine and it's still not working properly.

This is my code (I omitted the includes and stuff):

static boolean domotor=true;
const int SW_pin = 2;
void setup() {
  pinMode(SW_pin, INPUT);
  digitalWrite(SW_pin, HIGH);
  myservo.attach(9);
  myservo.write(0);
  Serial.begin(9600);
}

void check(){
  int pin = digitalRead(SW_pin);
  if(pin==0) {
    domotor=!domotor;
    delay(10);
  }
  Serial.print(pin);Serial.print(" ");Serial.print(domotor?"TRUE":"FALSE");
  Serial.print("\n");
}

void loop() {
    check();
    for (pos = 0; domotor && pos <= 180; pos += 1) {

      myservo.write(pos);             
      delay(15);
      check();
    }
    for (pos = 180; domotor && pos >= 0; pos -= 1) { 
      myservo.write(pos);         
      delay(15);                       
      check();
    }
  
}

Is it correct?

thanks a million
Marcello

it's still not working properly.

You do not say what is wrong. It is likely that the switch contacts are bouncing and producing multiple changes of input state

By the way. Using for loops, delay() and multiple calls to check() is quite a clumsy way of programming a responsive system. It would be better to let loop() do the looping and use millis() for timing so as not to introduce blocking code as you have at the moment. For instance, as it stands, each step of the servo takes 25 milliseconds so there are 25 milliseconds between reads of the input pin

Describe "dodgy".

Are you using a pull-up resistor?

Hello sterretje

sterretje:
Describe "dodgy".

Are you using a pull-up resistor?

  pinMode(SW_pin, INPUT);
  digitalWrite(SW_pin, HIGH);

enables the internal pull-up?

Regards,
bidouilleelec

Hello sterretje

  pinMode(SW_pin, INPUT);

digitalWrite(SW_pin, HIGH);




enables the internal pull-up?

You're right, at least on AVR based boards. Missed that.