0
votes

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.

1

1 Answers

0
votes

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.