Controlling Arduino Uno from NetBeans

You probably could just send a character like a, b, c, , and e to represent the four directions and reset. Then capture the characters individually and apply them to the servos similar to your cases. If you use delays in your arduino code, then you will need to limit the spew from the netbeans in order not to overflow the serial buffer and lose data. Below is some simple button incremental servo code that may be somewhat similar to yours.

#include <Servo.h> 
 
Servo myservo; 
#define leftPin 2    //Active Low
#define rightPin 3   //Active Low
int pos = 90;
int delayPeriod = 50;  // increasing this slows down the servo movement

 
 
void setup() 
{ 
  myservo.attach(9);  // attaches the servo on pin 9 to the servo object 
  myservo.write(pos); // center the servo
  pinMode(leftPin, HIGH);   // turn on pullup resistors
  pinMode(rightPin, HIGH);
} 
 
 
void loop() 
{ 
  if(digitalRead(leftPin) == LOW)  
  {                              
   // in steps of 1 degree 
   if( pos > 0)
      --pos;
    myservo.write(pos);              // tell servo to go to position in variable 'pos' 
    delay(delayPeriod);                      
  } 
  if(digitalRead(rightPin) == LOW)  
  {                              
   if( pos < 180)
       ++pos;
    myservo.write(pos);              // tell servo to go to position in variable 'pos' 
    delay(delayPeriod);        
  }
}

It’s not quite clear to me if your problem is with case 6 or not. Regardless of that, why do you
1)
position myservo
2)
wait 15 milliseconds
3)
position myservo2
4)
wait 15 milliseconds
5)
wait an additional 5 milliseconds

In my view, you can position both servos and next wait for a while if needed.

That would look like

         // palielinām / samazinām servo leņķi ar xSpeed (kad būs otrais servo - tad tam ySpeed jāizmanto)
          if (xSpeed < - 1 || xSpeed > 1) {
            int oldPosition = myservo.read();
            myservo.write(oldPosition + (xSpeed / 20));          // tell servo to go to position in variable 'pos'
          }

          //MAKSIMSMADE
          if (ySpeed < - 1 || ySpeed > 1) {
            int oldPositionY = myservo2.read();
            myservo2.write(oldPositionY + (ySpeed / 20));          // tell servo to go to position in variable 'pos'
          }

          delay(15); // one delay for both servos
          
          delay(5); // 1ms aizkave starp mērījumiem

It’s also my understanding that if you send 6, you switch to a manual mode using joysticks connected to the Arduino. And you send every 20 ms while the execution of stage 6 takes 35 ms. A buffer overflow will indeed be the result; but it should actually not slow down as long as sixes are sent.

A better approach would be to use a ‘joystick’ mode that’s activated when 6 is received and only switch back from ‘joystick mode’ once another value is received. Example code below

Start by adding a flag that indicates the mode

void loop()
{
  // a flag to indicate if we're in joystick mode or not
  static bool joystickMode = false;

Once you receive a character, check if it’s 6 or not

 //Trying to communicate with NetBeans
  //myservo - vertical
  //myservo2 - horizontal
  byte incomingByte;
  incomingByte = Serial.read();
  if (incomingByte != -1) {

    if (incomingByte == 6)
    {
      joystickMode = true;
    }
    else
    {
      joystickMode = false;
    }

Your switch statement will stay the same except for case 6 which will be empty

   switch (incomingByte) {
      case 1: {
        ...
        ...
        }
        break;
      case 2: {
        ...
        ...
        }
        break;
      case 3: {
        ...
        ...
        }
        break;
      case 4: {
        ...
        ...
        }
        break;
      case 5: {
        ...
        ...
        }
        break;
      case 6: {}
        // replaced by the if below
        }
        break;
      default: {

        }
        break;
    } // end_of switch
  }  // end of if (incomingByte != -1)

And add an if statement to test joystickMode after the closing } of if (incomingByte != -1)

 if (joystickMode == true)
  {
    //Izvadam X,Y koordinātes:
    x = analogRead(X_pin); //nolasām joystika X vērtību
    Serial.print("X: ");
    Serial.print(x);

    y = analogRead(Y_pin); //nolasām joystika Yvērtību
    Serial.print(", Y: ");
    Serial.print(analogRead(Y_pin));

    xDeg = map(x, 0, 1023, 0, 180); // remapping values of joystick reading to servo angles (https://www.arduino.cc/reference/en/language/functions/math/map/)
    yDeg = map(y, 0, 1023, 0, 180);

    xSpeed = map(x, 0, 1023, -100, 100); // remapping values of joystick reading to servo speed (https://www.arduino.cc/reference/en/language/functions/math/map/)
    ySpeed = map(y, 0, 1023, -100, 100);

    Serial.print(", xDeg: ");
    Serial.print(xDeg);
    Serial.print(", yDeg: ");
    Serial.print(yDeg);

    Serial.print(", xSpeed: ");
    Serial.print(xSpeed / 20);
    Serial.print(", ySpeed: ");
    Serial.print(ySpeed / 20);

    // palielinām / samazinām servo leņķi ar xSpeed (kad būs otrais servo - tad tam ySpeed jāizmanto)
    if (xSpeed < - 1 || xSpeed > 1) {
      int oldPosition = myservo.read();
      myservo.write(oldPosition + (xSpeed / 20));          // tell servo to go to position in variable 'pos'
    }

    //MAKSIMSMADE
    if (ySpeed < - 1 || ySpeed > 1) {
      int oldPositionY = myservo2.read();
      myservo2.write(oldPositionY + (ySpeed / 20));          // tell servo to go to position in variable 'pos'
    }

    delay(15);

    delay(5); // 1ms aizkave starp mērījumiem
  }
}

Your joystick control will no longer be depending on the incoming data. Even if you keep on pumping data from your app to the Arduino, it will stay in ‘joystick mode’ till it receives a character to indicate to get out of it; that will be any character, including those that are not in the switch/case (7, 8, …)

If this still does not achieve what you need, your Java app should not send data at the high rate when in ‘joystick mode’; you only need to send 6 once to switch to ‘joystick mode’ with the above Arduino approach.

sterretje:
It’s not quite clear to me if your problem is with case 6 or not. Regardless of that, why do you
1)
position myservo
2)
wait 15 milliseconds
3)
position myservo2
4)
wait 15 milliseconds
5)
wait an additional 5 milliseconds

In my view, you can position both servos and next wait for a while if needed.

That would look like

         // palielinām / samazinām servo leņķi ar xSpeed (kad būs otrais servo - tad tam ySpeed jāizmanto)

if (xSpeed < - 1 || xSpeed > 1) {
            int oldPosition = myservo.read();
            myservo.write(oldPosition + (xSpeed / 20));          // tell servo to go to position in variable ‘pos’
          }

//MAKSIMSMADE
          if (ySpeed < - 1 || ySpeed > 1) {
            int oldPositionY = myservo2.read();
            myservo2.write(oldPositionY + (ySpeed / 20));          // tell servo to go to position in variable ‘pos’
          }

delay(15); // one delay for both servos
         
          delay(5); // 1ms aizkave starp mērījumiem



It's also my understanding that if you send 6, you switch to a manual mode using joysticks connected to the Arduino. And you send every 20 ms while the execution of stage 6 takes 35 ms. A buffer overflow will indeed be the result; but it should actually not slow down as long as sixes are sent.

A better approach would be to use a 'joystick' mode that's activated when 6 is received and only switch back from 'joystick mode' once another value is received. Example code below

Start by adding a flag that indicates the mode


void loop()
{
  // a flag to indicate if we’re in joystick mode or not
  static bool joystickMode = false;




Once you receive a character, check if it's 6 or not


//Trying to communicate with NetBeans
  //myservo - vertical
  //myservo2 - horizontal
  byte incomingByte;
  incomingByte = Serial.read();
  if (incomingByte != -1) {

if (incomingByte == 6)
    {
      joystickMode = true;
    }
    else
    {
      joystickMode = false;
    }



Your switch statement will stay the same except for case 6 which will be empty


switch (incomingByte) {
      case 1: {
        …
        …
        }
        break;
      case 2: {
        …
        …
        }
        break;
      case 3: {
        …
        …
        }
        break;
      case 4: {
        …
        …
        }
        break;
      case 5: {
        …
        …
        }
        break;
      case 6: {}
        // replaced by the if below
        }
        break;
      default: {

}
        break;
    } // end_of switch
  }  // end of if (incomingByte != -1)



And add an if statement to test joystickMode after the closing } of if (incomingByte != -1)



if (joystickMode == true)
  {
    //Izvadam X,Y koordinātes:
    x = analogRead(X_pin); //nolasām joystika X vērtību
    Serial.print("X: ");
    Serial.print(x);

y = analogRead(Y_pin); //nolasām joystika Yvērtību
    Serial.print(", Y: ");
    Serial.print(analogRead(Y_pin));

xDeg = map(x, 0, 1023, 0, 180); // remapping values of joystick reading to servo angles (map() - Arduino Reference)
    yDeg = map(y, 0, 1023, 0, 180);

xSpeed = map(x, 0, 1023, -100, 100); // remapping values of joystick reading to servo speed (map() - Arduino Reference)
    ySpeed = map(y, 0, 1023, -100, 100);

Serial.print(", xDeg: “);
    Serial.print(xDeg);
    Serial.print(”, yDeg: ");
    Serial.print(yDeg);

Serial.print(", xSpeed: “);
    Serial.print(xSpeed / 20);
    Serial.print(”, ySpeed: ");
    Serial.print(ySpeed / 20);

// palielinām / samazinām servo leņķi ar xSpeed (kad būs otrais servo - tad tam ySpeed jāizmanto)
    if (xSpeed < - 1 || xSpeed > 1) {
      int oldPosition = myservo.read();
      myservo.write(oldPosition + (xSpeed / 20));          // tell servo to go to position in variable ‘pos’
    }

//MAKSIMSMADE
    if (ySpeed < - 1 || ySpeed > 1) {
      int oldPositionY = myservo2.read();
      myservo2.write(oldPositionY + (ySpeed / 20));          // tell servo to go to position in variable ‘pos’
    }

delay(15);

delay(5); // 1ms aizkave starp mērījumiem
  }
}



Your joystick control will no longer be depending on the incoming data. Even if you keep on pumping data from your app to the Arduino, it will stay in 'joystick mode' till it receives a character to indicate to get out of it; that will be any character, including those that are not in the switch/case (7, 8, ...)

If this still does not achieve what you need, your Java app should not send data at the high rate when in 'joystick mode'; you only need to send 6 once to switch to 'joystick mode' with the above Arduino approach.

For the first 3 “questions” - as said before, if i don’t have a delay at all, the servo will, in stead of moving at a decent and smooth speed, insantly move to the end position, so the 15ms delay is there to add artifical smoothness to it. The 5ms delay is there to wait for the next joystick input, though the 5ms delay might not be necessary.
As for the joystick mode, that’s what I’m currently trying to do, but for every single movement. If i send press down on the Up button, it sends the value 1 once, which makes a while loop slowly increase the angle and check if the incoming value has changed. When i let go of it, it sends the value 0 once, which will be used as the reset value in every function. I plan to do this for every case, maybe that will make my app more stable.

"the 15ms delay is there to add artifical smoothness to it"

Put that on the netbean sending side, not on the arduino receiving side. Just wait 15ms before sending the next move character, that way the arduino code does not need the delays for that "smoothing" function, and can read the serial buffer more efficiently.

It also appears that you are sending a 0 from your java application if the type of button press is not recognised. Why send anything at all in that case ?

If you have an additional USBTTL device example , you could use software serial say for the java/PC connection and use the standard hardware serial (at a much higher baud rate) for your debug output, then you can see what is going on.

sterretje:
It’s not quite clear to me if your problem is with case 6 or not. Regardless of that, why do you…

So, after trying to get it to work with the boolean values, nothing works. If i work with just submitting 1 or 0, the commented code with writing to 180 or 0 directly works.
I tried using both bool and boolean, since google said they’re the same, but neither worked.
I tried initializing and declaring valuables on start and outside of start, below the import, but that didn’t change anything either.

#include <Servo.h>

Servo myservo;  // create servo object to control a servo
Servo myservo2; //MAKSIMSMADE
// twelve servo objects can be created on most boards

int pos = 0;    // variable to store the servo position



// Arduino pin numbers
const int BTN_pin = 13; // digital pin connected to button output
const int SERVO_pin = 3; // digital pin connected to button output
const int SERVO_pin2 = 6; // MAKSIMSMADE
const int X_pin = 0; // analog pin connected to X output
const int Y_pin = 1; // analog pin connected to Y output

int flagBtnPressedOnce = 0;

int x, y = 0; // for joystick readings
int xDeg, yDeg = 0; // for servo angle control
int xSpeed, ySpeed = 0; // for servo speed control

void setup() {

  pinMode(BTN_pin, INPUT); // INPUT is Sensor (e.g. button, motion sensor, mic, etc.)
  pinMode(SERVO_pin, OUTPUT); // OUTPUT is Actuator (e.g. any motor, LED bulb, etc.)
  pinMode(SERVO_pin2, OUTPUT); //MAKSIMSMADE
  digitalWrite(BTN_pin, HIGH); // default state



  myservo.attach(SERVO_pin);  // attaches the servo on pin 9 to the servo object
  myservo2.attach(SERVO_pin2); //MAKSIMSMADE
  //myservo.write(90);  // default position 90 degrees
  //myservo2.write(90); //MAKSIMSMADE
  Serial.begin(9600);
}

void loop() {

  //Trying to communicate with NetBeans

  byte incomingByte;
  static boolean goUp;
  static boolean goDown;
  //myservo - vertical
  //myservo2 - horizontal

  incomingByte = Serial.read();
  //Both of the checks below work. If i hold down the mouse button, it sends 1 once, and the servos rotate
  //to 180 degrees. Upon letting go of the button, it sends 0 once, and the servos rotate to 0 degrees.
  /*
    if(incomingByte == 1) {
    myservo.write(180);
    myservo2.write(180);
    }
    if(incomingByte == 0) {
    myservo.write(0);
    myservo2.write(0);
    }
  */
  if (incomingByte != -1) {
    if (incomingByte == 1) {
      boolean goUp = true;
    } else {
      boolean goUp = false;
    }
    if (incomingByte == 2) {
      boolean goDown = true;
    } else {
      boolean goDown = false;
    }

    switch (incomingByte) {
      case 1: {
          if (goUp == true) {
            while (true) {
              myservo.write(myservo.read() + 1);
              delay(15);
              //break;
            }
          }
        }
        break;
      case 2: {
          if (goDown == true) {
            while (true) {
              myservo.write(myservo.read() - 1);
              delay(15);
              //break;
            }
          }
        }
        break;
    }

    if (goUp == true) {
      while (true) {
        myservo.write(myservo.read() + 1);
        delay(15);
        //break;
      }
    }

  }



}

6v6gt:
It also appears that you are sending a 0 from your java application if the type of button press is not recognised. Why send anything at all in that case ?

If you have an additional USBTTL device example , you could use software serial say for the java/PC connection and use the standard hardware serial (at a much higher baud rate) for your debug output, then you can see what is going on.

Sadly, I don't have one, though I might try to get one from my college on Monday, since this entire setup is from there.
The 0 sending was just something I wanted to continue, but accidentally left in. After removal nothing changed.
Any clue what could be wrong with the code I added in the reply before this one is? As a Java focused programmer, it was a surprise from me, that if i simply declare a boolean or a byte, they will have a default value of true and 0 respectively.
I manage to send the byte 1 once, on pressing down on mouse button, and to send the byte 0 on letting go of the mouse button, yet I think that the loop function resets their values back to default, or the booleans don't get changed. Trying to fiddle with it to create the "isJoystickEnabled" functionality, yet it still hasn't worked...

wildbill:
It depends on what your PC code is sending on serial. If it’s sending a continuous stream of bytes that you’re not reading for two seconds as mentioned earlier, you have a problem with delay.

What are you seeing that makes you think you have an SRAM issue?

After mucking around a bit, both removing the delays, exchanging them for the alternative delay system, then adding them back, I tried just “calmly” moving the servos, the way I would actually be using them, and I managed to use the servos for about 3 minutes straight, without crashing, so I guess that holding down the buttons really did send too many bytes, which made the buffer overflow (which, as mentioned by someone, isn’t possible, those values would just go “poof”, in stead of breaking anything) or fill up faster than it could be read.
Sadly the problem still persists with the current joystick setup, and I haven’t gotten the one proposed by sterretje (which makes perfect sense) to work, probably due to now knowing interactions between loop, variables both in and outside of it.

I cut and pasted the below code together which seems pretty simple. You can test with the serial monitor by sending character strings like aaaaaaaaaaabbbbbbbccccccccccdddddddddddd and an r to reset. You should be able to control the movement speed of the servos by using delays in the netbean code by delaying the speed the characters are sent.

#include <Servo.h>

Servo myservo1;
Servo myservo2;

int pos = 90;
int delayPeriod = 50;  // increasing this slows down the servo movement
char c;


void setup()
{
  Serial.begin(9600);
  myservo1.attach(8);  // attaches the servo on pin 8 to the servo object
  myservo2.attach(9);  // attaches the servo on pin 9 to the servo object
  myservo1.write(pos); // center the servo1
  myservo2.write(pos); // center the servo2
}


void loop()
{
  if (Serial.available())  {

    char c = Serial.read();  //gets one byte from serial buffer
    Serial.print("received character is ");
    Serial.println(c);
    //}

    if (c == 'a')
    {
      // in steps of 1 degree
      if ( pos > 0)
        --pos;
      myservo1.write(pos);              // tell servo to go to position in variable 'pos'
      Serial.print("servo 1 is at ");
      Serial.println(pos);
      //delay(delayPeriod);
    }
    if (c == 'b')
    {
      if ( pos < 180)
        ++pos;
      myservo1.write(pos);        // tell servo to go to position in variable 'pos'
      Serial.print("servo 1 is at ");
      Serial.println(pos);
      //delay(delayPeriod);
    }

    //

    if (c == 'c')
    {
      // in steps of 1 degree
      if ( pos > 0)
        --pos;
      myservo2.write(pos);              // tell servo to go to position in variable 'pos'
      Serial.print("servo 2 is at ");
      Serial.println(pos);
      //delay(delayPeriod);
    }
    if (c == 'd')
    {
      if ( pos < 180)
        ++pos;
      myservo2.write(pos);              // tell servo to go to position in variable 'pos'
      Serial.print("servo 2 is at ");
      Serial.println(pos);
      //delay(delayPeriod);
    }

    //

    if (c == 'r')
    {
      myservo1.write(90);
      myservo2.write(90);
      Serial.println("servos reset at 90 deg.");
    }
  }
}

You can’t do this...

byte incomingByte;
. . .
incomingByte = Serial.read();
. . .
if (incomingByte != -1) { . . .

Because a byte cannot represent a negative number.

Update: corrected copy paste error to include a pos1 and a pos2, one for each servo, instead of a single pos.

#include <Servo.h>

Servo myservo1;
Servo myservo2;

int pos1 = 90;
int pos2 = 90;
int delayPeriod = 50;  // increasing this slows down the servo movement
char c;


void setup()
{
  Serial.begin(9600);
  myservo1.attach(8);  // attaches the servo on pin 8 to the servo object
  myservo2.attach(9);  // attaches the servo on pin 9 to the servo object
  myservo1.write(pos1); // center the servo1
  myservo2.write(pos2); // center the servo2
}


void loop()
{
  if (Serial.available())  {

    char c = Serial.read();  //gets one byte from serial buffer
    Serial.print("received character is ");
    Serial.println(c);
    //}

    if (c == 'a')
    {
      // in steps of 1 degree
      if ( pos1 > 0)
        --pos1;
      myservo1.write(pos1);              // tell servo to go to position in variable 'pos'
      Serial.print("servo 1 is at ");
      Serial.println(pos1);
      //delay(delayPeriod);
    }
    if (c == 'b')
    {
      if ( pos1 < 180)
        ++pos1;
      myservo1.write(pos1);        // tell servo to go to position in variable 'pos'
      Serial.print("servo 1 is at ");
      Serial.println(pos1);
      //delay(delayPeriod);
    }

    //

    if (c == 'c')
    {
      // in steps of 1 degree
      if ( pos2 > 0)
        --pos2;
      myservo2.write(pos2);              // tell servo to go to position in variable 'pos'
      Serial.print("servo 2 is at ");
      Serial.println(pos2);
      //delay(delayPeriod);
    }
    if (c == 'd')
    {
      if ( pos2 < 180)
        ++pos2;
      myservo2.write(pos2);              // tell servo to go to position in variable 'pos'
      Serial.print("servo 2 is at ");
      Serial.println(pos2);
      //delay(delayPeriod);
    }

    //

    if (c == 'r')
    {
      myservo1.write(90);
      myservo2.write(90);
      Serial.println("servos reset at 90 deg.");
    }
  }
}

suggest disassociating updates to servos depending on serial input

void loop()
{
  if (Serial.available()) {
    switch (Serial.read())  {
    case 'a':
        pos1 += pos1 > 0 ? -1 : 0;
        break;

    case 'b':
        pos1 += pos1 < 180 ?  1 : 0;
        break;

    case 'c':
        pos2 += pos2 > 0 ? -1 : 0;
        break;

    case 'd':
        pos2 += pos2 < 180 ?  1 : 0;
        break;

    case 'r':
        pos2 = pos1 = 90;
        break;

    case '?':
        Serial.print (" pos1 ");
        Serial.println (pos1);
        Serial.print (", pos2 ");
        Serial.println (pos2);
        break;
  }

  myservo1.write (pos1);
  myservo2.write (pos2);
}