loading

Please help with my Arduino program (controlling servo)?

I started trying the Arduino programming 1 days ago so I'm not sure what is wrong with my program (also, sorry for the messy look)

const int buttonPin = 2;    
int buttonState = 0;        
#include <Servo.h>
Servo myservo; 
int n = 0;
int pos;
int lc = 0;

void setup() {
  myservo.attach(9);
  pinMode(buttonPin, INPUT);
  myservo.write(pos);
}

void loop() {
  buttonState = digitalRead(buttonPin);
  if (buttonPin == HIGH)  {
    if (lc == 0) {
    for(pos = n; pos <= 180; pos++) {
    myservo.write(pos);              
    buttonState = digitalRead(buttonPin);
    if (buttonPin == LOW){
      n = pos;
      break; }
    if (pos == 180) {
      n=pos;
      lc = 1;}
     delay(15);
  } }
    else {
  for(pos = n; pos>=0; pos--)     
  {                               
    myservo.write(pos);              
    buttonState = digitalRead(buttonPin);
    if (buttonPin == LOW){
      n = pos;
      break; }
    if (n == 0) {
      n = pos;
      lc = 0;} 
    delay(15); 
  } }
  }
}

Basically, it's to use a button to control the servo, if the button is press, the servo will spin (0 to 180 then 180 back to 0), if the button is released, it will stop the servo, and pressing the button will continues the servo movement (not resetting it). The "lc" int is used to show if the servo was moving from 0 to 180 (lc = 0) or 180 back to 0 (lc = 1). I only studied Pascal before so I have a bit trouble understand it so if there was big mistake in my program, please let me know.
Thanks for your help.

First, make sure you can move the servo AT ALL from your code. Try setting its position to 180, and 0 depending on the state of the pin.

Have you got a pull up on your input pin ?

In your code, don't use a for loop and a break, its not good style, just use a while loop. Its also easier to do the sweep if you use a boolean for the state of the ramp, when its time to change direction, you just invert ic

if (ramp>=180) ic=!ic

if (ramp<=0) ic=!ic

If ic ramp-- else ramp++

Shizen (author)  steveastrouk2 years ago

I found the error in my code, it's a stupid mistake:

What I wrote:

buttonState = digitalRead(buttonPin);

if (buttonPin == HIGH)

I messed up the State and the Pin ¬¬"

Anyway, my code work now, I'll still gonna try your suggestion, thanks again

Describe what it ISN'T doing.

Shizen (author)  steveastrouk2 years ago

It doesn't do anything. When I press the button, it doesn't sweep