0

I'm working on a Bluetooth controlled Arduino robotic arm. I want that when I send an integer, a servo moves, and when I send another Int, it stops. All I have found on forums are systems where the servo moves to a specific position, but I want it to really rotate, by incrementing its angle. Here is my code, which doesn't work:

#include <Servo.h>

int val;
int angle;
int charsRead;
char buffer[10];
Servo servo;

void setup() {
  Serial.begin(9600);
  servo.attach(6);
  angle = servo.read();
}

void loop() {
    servo.write(170);
    serialCheck();
   if(val == 4021){
       servo.write(angle++);
       delay(50);
       }
      }
      else if(val == 4022){
        servo.write(angle);
        }
        serialCheck();
}

void serialCheck(){
  while(Serial.available() > 0){
    charsRead = Serial.readBytesUntil('\n', buffer, sizeof(buffer) - 1);
    buffer[charsRead] = '\0';
    val = atoi(buffer);
    Serial.println(val);
    }
  }

The app I use basically sends '4021' when I long press a button, and sends '4022' when I release it.

I've been working on this for hours and I haven't found anyone on any forum who has had the same issue...

Please help.

Hugo Trombert
  • 25
  • 1
  • 8

1 Answers1

0

Your problem lies here:

void loop() {
    servo.write(170);
...
}

What this piece of code does is set servo angle to 170 at every iteration of loop. As this will happen thousands times per second, it will essentially overwrite any servo settings introduced via serial commands. What you should do is to move servo.write(170); to setup(), before servo.read(), which I think will yield middle position currently, or even some undefined result. According to Arduino documentation it will:

Read the current angle of the servo (the value passed to the last call to write()).

And BTW: servo has limited range of movement, so you should check if the desired angle doesn't exceed servo limits.

mactro
  • 518
  • 7
  • 13
  • Thank you so much! I was working on this project for more than a month now and it was my last problem to solve! It works! – Hugo Trombert Aug 10 '16 at 09:09
  • @HugoTrombert: You probably fixed more issues around the manipulation of the angle variable. And If you don't send anything, val remains at ist last value, repeating the previous movement over and over ... – datafiddler Aug 10 '16 at 13:21
  • @HugoTrombert I would also use the second command to rotate servo in opposite direction. As datafiddler said, when you don't send anything, the servo will remain in the last position. – mactro Aug 10 '16 at 14:02
  • @mactro Yeah I just did this. – Hugo Trombert Aug 10 '16 at 16:37