Serial communication help between 2 Boards SOLVED

I am trying to code a Arduino board that receives a string and stores for 10 inputs from another Arduino. When I connect the Arduino everything works great for about 30 seconds, after that the output changes and the code no longer talks to my motors and the code does not work if anyone can help me that would be great: here is my code: #include <SoftwareSerial.h>
SoftwareSerial mySerial(10,11); // RX, TX

#include <Servo.h>

Servo servo1; // create servo object to control a servo
Servo servo2; // servo 2 gripper rotation button 2 and 4
Servo servo3; // servo 3 gripper angle button 2 and 4
int servoPos1 = 130; // variable to store the current position of the servo
int servoPos2 = 160; // variable to store the current position of the servo
int servoPos3 = 10; // variable to store the current position of the servo
int increment = 1; // increment of servo position
int delayTime = 20; // delay time in milliseconds

// Define relay pins
const int relay1 = 30;
const int relay2 = 31;

// Define motor control pins
int motorAPinIN1 = 22;
int motorAPinIN2 = 23;
int motorAPinEN = 2;
int motorBPinIN3 = 24;
int motorBPinIN4 = 25;
int motorBPinEN = 3;

int motorAPinIN1LEFT = 22;
int motorAPinIN2LEFT = 23;
int motorAPinENLEFT = 2;
int motorBPinIN3LEFT = 24;
int motorBPinIN4LEFT = 25;
int motorBPinENLEFT = 3;

int motorCPinIN1 = 26;
int motorCPinIN2 = 27;
int motorCPinEN = 4;
int motorDPinIN3 = 28;
int motorDPinIN4 = 29;
int motorDPinEN = 5;
const byte numInputsExpected = 10; // Set the expected number of inputs as a constant
const byte maxNumInputs = 10; // Set the maximum number of inputs as a constant

int* parseInputs(String inputString, byte & numInputs) { // Use byte instead of int for the number of inputs
// Remove the first and last characters of the input string, which are "<" and ">"
inputString = inputString.substring(1, inputString.length() - 1);

// Remove any spaces from the input string
inputString.replace(" ", "");

// Count the number of commas to determine the number of inputs
numInputs = 1;
byte inputCounter = 1; // Initialize the input counter to 1
for (int i = 0; i < inputString.length(); i++) {
if (inputString.charAt(i) == ',') {
numInputs++;
inputCounter++; // Increment the input counter
}
if (inputCounter > maxNumInputs) { // Check if the input counter exceeds the limit
numInputs = 0;
inputCounter = 1; // Reset the input counter
break; // Exit the loop
}
}

// Check if the number of inputs is as expected
if (numInputs != numInputsExpected) {
numInputs = 0;
return NULL;
}

// Allocate an array to store the input values
int* inputs = new int[numInputs];

// Parse the input string and store the values in the array
int currentIndex = 0;
for (int i = 0; i < numInputs; i++) {
int nextIndex = inputString.indexOf(',', currentIndex);
if (nextIndex == -1) {
// If there are less inputs than expected, return an error
if (i != numInputs-1) {
numInputs = -1;
delete[] inputs;
return NULL;
}
nextIndex = inputString.length();
}
String inputValueString = inputString.substring(currentIndex, nextIndex);

// If the input value cannot be parsed as an integer, return an error
int inputValue;
if (!inputValueString.toInt() && inputValueString != "0" && inputValueString != "-0") {
  numInputs = -1;
  delete[] inputs;
  return NULL;
}
inputValue = inputValueString.toInt();
inputs[i] = inputValue;
currentIndex = nextIndex + 1;

}

// Free memory allocated for the input string
String* inputStringPtr = new String(inputString);
delete inputStringPtr;

return inputs;
}

void setup() {
Serial.begin(57600); // Initialize serial communication for debugging

// Initialize relay pins
pinMode(relay1, OUTPUT); // Relay 1 control pin
pinMode(relay2, OUTPUT); // Relay 2 control pin

// Initialize motor control pins
pinMode(motorAPinIN1, OUTPUT);
pinMode(motorAPinIN2, OUTPUT);
pinMode(motorAPinEN, OUTPUT);
pinMode(motorBPinIN3, OUTPUT);
pinMode(motorBPinIN4, OUTPUT);
pinMode(motorBPinEN, OUTPUT);

pinMode(motorAPinIN1LEFT, OUTPUT);
pinMode(motorAPinIN2LEFT, OUTPUT);
pinMode(motorAPinENLEFT, OUTPUT);
pinMode(motorBPinIN3LEFT, OUTPUT);
pinMode(motorBPinIN4LEFT, OUTPUT);
pinMode(motorBPinENLEFT, OUTPUT);

pinMode(motorCPinIN1, OUTPUT);
pinMode(motorCPinIN2, OUTPUT);
pinMode(motorCPinEN, OUTPUT);
pinMode(motorDPinIN3, OUTPUT);
pinMode(motorDPinIN4, OUTPUT);
pinMode(motorDPinEN, OUTPUT);

// Servos
servo1.attach(8); // attaches the servo1 on pin 9 to the servo object
servo1.write(servoPos1); // initialize servo to start at 90 degrees
servo2.attach(6); // attach servo 2 to pin 34 rotate gripper
servo2.write(servoPos2); // initialize servo to start at 90 degrees
servo3.attach(7); // attach servo 2 to pin 34 rotate gripper
servo3.write(servoPos3); // initialize servo to start at 90 degrees
}

void loop() {
if (Serial.available()) {
String inputString = Serial.readStringUntil('\n'); // read the string
Serial.println(inputString); // print the string for debugging

// Parse input values
byte numInputs;
int* inputs = parseInputs(inputString, numInputs);

if (numInputs == 0) {
  Serial.println("Error: Expected " + String(numInputsExpected) + " inputs, received " + String(inputs ? abs(numInputs) : 0));
} else { 

  // Extract the input values and do something with them...
  const int joystick1X = inputs[0];
  const int joystick1Y = inputs[1];
  const int joystick2X = inputs[2];
  const int joystick2Y = inputs[3];
  bool button1State = (inputs[4] == 0);
  bool button2State = (inputs[5] == 0);
  bool button3State = (inputs[6] == 0);
  bool button4State = (inputs[7] == 0 );
  bool button5State = (inputs[8] == 0);
  bool button6State = (inputs[9] == 0);
 /*
  // Print the values for debugging
  Serial.print("Joystick 1 X: ");
  Serial.println(joystick1X);
 
  Serial.print("Joystick 1 Y: ");
  Serial.println(joystick1Y);
  Serial.print("Joystick 2 X: ");
  Serial.println(joystick2X);
  Serial.print("Joystick 2 Y: ");
  Serial.println(joystick2Y);
  Serial.print("Button 1 state: ");
  Serial.println(button1State);
  Serial.print("Button 2 state: ");
  Serial.println(button2State);
  Serial.print("Button 3 state: ");
  Serial.println(button3State);
  Serial.print("Button 4 state: ");
  Serial.println(button4State);
  Serial.print("Button 5 state: ");
  Serial.println(button5State);
  Serial.print("Button 6 state: ");
  Serial.println(button6State);
  */
  
// Control the relays based on button states arm motor
if (button1State) {
  digitalWrite(relay1, HIGH); // Turn on relay 1
  digitalWrite(relay2, LOW); // Turn off relay 2
}
    else if (button3State) {
  digitalWrite(relay1, LOW); // Turn off relay 1
  digitalWrite(relay2, HIGH); // Turn on relay 2
}
    else {
  digitalWrite(relay1, LOW); // Turn off relay 1
  digitalWrite(relay2, LOW); // Turn off relay 2
}

// Set motor C and D speeds based on joystick1Y VERT MOTORS GOING UP AND DOWN
int motorSpeed = joystick1Y;
int VoltageMax = 12;
int motorMaxSpeed = 100; // set the maximum motor speed to 100
int motorPWM = map(constrain(motorSpeed, -motorMaxSpeed, motorMaxSpeed), -motorMaxSpeed, motorMaxSpeed,-VoltageMax15, VoltageMax15);

if (motorSpeed > 0) { // moving joystick up
  digitalWrite(motorCPinIN1, HIGH); // set motor C direction forward
  digitalWrite(motorCPinIN2, LOW);
  analogWrite(motorCPinEN, motorPWM); // set motor C speed forward
  digitalWrite(motorDPinIN3, HIGH); // set motor D direction reverse
  digitalWrite(motorDPinIN4, LOW);
  analogWrite(motorDPinEN, motorPWM); // set motor D speed reverse
}
  else if(motorSpeed < 0){ // moving joystick down
    digitalWrite(motorCPinIN1, LOW); // set motor C direction reverse
    digitalWrite(motorCPinIN2, HIGH);
    analogWrite(motorCPinEN, -motorPWM); // set motor C speed reverse
    digitalWrite(motorDPinIN3, LOW); // set motor D direction forward
    digitalWrite(motorDPinIN4, HIGH);
    analogWrite(motorDPinEN, -motorPWM); // set motor D speed forward
}
  else{ // joystick at rest
    digitalWrite(motorCPinIN1, LOW); // stop motor C
    digitalWrite(motorCPinIN2, LOW);
    analogWrite(motorCPinEN, 0);
    digitalWrite(motorDPinIN3, LOW); // stop motor D
    digitalWrite(motorDPinIN4, LOW);
    analogWrite(motorDPinEN, 0);
}

// HORZ MOTORS
  int motorSpeed2 = joystick2Y; // Get joystick2Y value for Foward and reverse movement 
  int motorSpeed3 = joystick2X; // Get joystick2X value for Turning left and right 
  // Check if both joystick values are zero
  if (motorSpeed2 == 0 && motorSpeed3 == 0) {
    digitalWrite(motorAPinIN1, LOW); // stop motor A
    digitalWrite(motorAPinIN2, LOW);
    analogWrite(motorAPinEN, 0);
    digitalWrite(motorBPinIN3, LOW); // stop motor B
    digitalWrite(motorBPinIN4, LOW);
    analogWrite(motorBPinEN, 0);
    digitalWrite(motorAPinIN1LEFT, LOW); // stop motor A
    digitalWrite(motorAPinIN2LEFT, LOW);
    analogWrite(motorAPinENLEFT, 0);
    digitalWrite(motorBPinIN3LEFT, LOW); // stop motor B
    digitalWrite(motorBPinIN4LEFT, LOW);
    analogWrite(motorBPinENLEFT, 0);
  }
          else if (motorSpeed2 != 0) { // If vertical joystick movement detected
        // Set motor A and B speeds based on joystick2Y value
        // HORZ MOTORS GOING FORWARD AND BACK
        int VoltageMax2 = 6;
        int motorMaxSpeed2 = 100; // set the maximum motor speed to 100
        int motorPWM2 = map(constrain(motorSpeed2, -motorMaxSpeed2, motorMaxSpeed2), -motorMaxSpeed2, motorMaxSpeed2, -VoltageMax2*15, VoltageMax2*15);
        
        if (motorSpeed2 > 0) { // moving joystick up
          digitalWrite(motorAPinIN1, HIGH); // set motor A direction forward
          digitalWrite(motorAPinIN2, LOW);
          analogWrite(motorAPinEN, motorPWM2); // set motor A speed forward
          digitalWrite(motorBPinIN3, LOW); // set motor B direction reverse
          digitalWrite(motorBPinIN4, HIGH);
          analogWrite(motorBPinEN, motorPWM2); // set motor B speed reverse
        } else { // moving joystick down
          digitalWrite(motorAPinIN1, LOW); // set motor A direction reverse
          digitalWrite(motorAPinIN2, HIGH);
          analogWrite(motorAPinEN, -motorPWM2); // set motor A speed reverse
          digitalWrite(motorBPinIN3, HIGH); // set motor B direction forward
          digitalWrite(motorBPinIN4, LOW);
          analogWrite(motorBPinEN, -motorPWM2); // set motor B speed forward
        }
      }  else if (motorSpeed3 != 0) { // If horizontal joystick movement detected
        // Set motor A and B speeds based on joystick2X value
        // HORZ MOTORS turn left or right 
        int VoltageMax3 =  6; // set the maximum voltage to 8V
        int motorMaxSpeed3 = 100; // set the maximum motor speed to 100
        int motorPWM3 = map(constrain(motorSpeed3, -motorMaxSpeed3, motorMaxSpeed3), -motorMaxSpeed3, motorMaxSpeed3,-VoltageMax3*15, VoltageMax3*15);
      
        if (motorSpeed3 > 0) { // moving joystick left
          digitalWrite(motorAPinIN1LEFT, HIGH); // set motor A direction forward
          digitalWrite(motorAPinIN2LEFT, LOW);
          analogWrite(motorAPinENLEFT, motorPWM3); // set motor A speed forward
          digitalWrite(motorBPinIN3LEFT, HIGH); // set motor B direction reverse
          digitalWrite(motorBPinIN4LEFT, LOW);
          analogWrite(motorBPinENLEFT, motorPWM3); // set motor B speed reverse
        } else { // moving joystick right
          digitalWrite(motorAPinIN1LEFT, LOW); // set motor A direction reverse
          digitalWrite(motorAPinIN2LEFT, HIGH);
          analogWrite(motorAPinENLEFT, -motorPWM3); // set motor A speed reverse
          digitalWrite(motorBPinIN3LEFT, LOW); // stop motor B
          digitalWrite(motorBPinIN4LEFT, HIGH);
          analogWrite(motorBPinENLEFT,-motorPWM3 );
        }
      }

// servo 1 open close gripper with left joystick moving in x direction
int Servo1Num = joystick1X ;

if (Servo1Num == 0) { // if joystick input is 0, servo remains in last position
// Do nothing
} else if (Servo1Num < 0) { // if joystick is pushed left (negative X-axis value)
if (servoPos1 < 160) { // rotate servo towards 180 degrees
servoPos1 += 5; // increment servo position by 1 degree
servo1.write(servoPos1); // write new servo position to servo

}

} else if (Servo1Num > 0) { // if joystick is pushed right (positive X-axis value)
if (servoPos1 > 100) { // rotate servo towards 0 degrees
servoPos1 -= 5; // decrement servo position by 1 degree
servo1.write(servoPos1); // write new servo position to servo

}

}

// servo 3 angle
// Check for button 5 and 6 state
if (button5State) {
if (servoPos3 < 100) { // rotate servo towards 180 degrees
servoPos3 += 1;
servo3.write(servoPos3);

    }
   }   else if (button6State) {
    if (servoPos3 > 20) { // rotate servo towards 0 degrees
    servoPos3 -= 1;
    servo3.write(servoPos3);
   
    }
   }

// servo 2 rotatio
// Check for button 2 and 4 state
if (button2State) {
if (servoPos2 < 160) { // rotate servo towards 180 degrees
servoPos2 += 1;
servo2.write(servoPos2);

    }
   }   else if (button4State) {
    if (servoPos2 > 95) { // rotate servo towards 0 degrees
    servoPos2 -= 1;
    servo2.write(servoPos2);
   
    }
   }
}

}
}

and here is the serial monitor output: <0,0,0,0,1,1,1,1,1,1>

<0,0,0,0,1,1,1,1,1,1>

<0,0,0,0,1,1,1,1,1,1>

<0,0,0,0,1,1,1,1,1,1>

<0,0,0,0,1,1,1,1,1,1>

<0,0,0,0,1,1,1,1,1,1>

<0,0,0,0,1,1,1,1,1,1>

<0,0,0,0,1,1,1,1,1,1>

<0,0,0,0,1,1,1,1,1,1>

<0,0,0,0,1,1,1,1,1,1>

<0,0,0,0,1,1,1,1,1,1>

<0,0,0,0,1,1,1,1,1,1>

<0,0,0,0,1,1,1,1,1,1>

<0,0,0,0,1,1,1,1,1,1>

Please read the forum guide in the sticky post at the top of most forum sections to find out how to post correctly. Then fix your post above. Thanks.

@westfootball99 please re-edit your post to use code tags.

You will likely get very little help until you do.

Hello westfootball99

The ussage of the String data type is´nt a good idea.

To use char[] arrays is a better way.

Hi @westfootball99 welcome to one of the best arduino community
Request you to kindly read the following

And re-edit your post

You really should re-edit your initial posting to put your entire code into a code-section.

Then you should post a desription what functionality your code shall have.
from a very quick cross-reading my assumption is that you want to control a number of servos

Well for that you don't need variables of type Strings at all

best regards Stefan

im trying to fix my code I have to read a Arduino controller that outputs a string command that I can not edit so I can't change anything about the controller code. When I start the code it reads the string correct and does what it need to do but after about 30 seconds it out puts the string and then a single 0 and the controller starts to not work.
here is my code:

#include <SoftwareSerial.h>
SoftwareSerial mySerial(10,11); // RX, TX

#include <Servo.h>

Servo servo1;  // create servo object to control a servo
Servo servo2; // servo 2 gripper rotation button 2 and 4
Servo servo3; // servo 3 gripper angle  button 2 and 4
int servoPos1 = 130;  // variable to store the current position of the servo
int servoPos2 = 160;  // variable to store the current position of the servo
int servoPos3 = 10;  // variable to store the current position of the servo
int increment = 1; // increment of servo position
int delayTime = 20; // delay time in milliseconds


// Define relay pins
const int relay1 = 30;
const int relay2 = 31;

// Define motor control pins
 int motorAPinIN1 = 22;
 int motorAPinIN2 = 23;
 int motorAPinEN = 2;
 int motorBPinIN3 = 24;
 int motorBPinIN4 = 25;
 int motorBPinEN = 3;

int motorAPinIN1LEFT = 22;
int motorAPinIN2LEFT = 23;
int motorAPinENLEFT = 2;
int motorBPinIN3LEFT = 24;
int motorBPinIN4LEFT = 25;
int motorBPinENLEFT = 3;

int motorCPinIN1 = 26;
 int motorCPinIN2 = 27;
 int motorCPinEN = 4;
 int motorDPinIN3 = 28;
 int motorDPinIN4 = 29;
 int motorDPinEN = 5;
const byte numInputsExpected = 10; // Set the expected number of inputs as a constant
const byte maxNumInputs = 10; // Set the maximum number of inputs as a constant

int* parseInputs(String inputString, byte & numInputs) { // Use byte instead of int for the number of inputs
  // Remove the first and last characters of the input string, which are "<" and ">"
  inputString = inputString.substring(1, inputString.length() - 1);

  // Remove any spaces from the input string
  inputString.replace(" ", "");

  // Count the number of commas to determine the number of inputs
  numInputs = 1;
  byte inputCounter = 1; // Initialize the input counter to 1
  for (int i = 0; i < inputString.length(); i++) {
    if (inputString.charAt(i) == ',') {
      numInputs++;
      inputCounter++; // Increment the input counter
    }
    if (inputCounter > maxNumInputs) { // Check if the input counter exceeds the limit
      numInputs = 0;
      inputCounter = 1; // Reset the input counter
      break; // Exit the loop
    }
  }

  // Check if the number of inputs is as expected
  if (numInputs != numInputsExpected) {
    numInputs = 0;
    return NULL;
  }

  // Allocate an array to store the input values
  int* inputs = new int[numInputs];

  // Parse the input string and store the values in the array
  int currentIndex = 0;
  for (int i = 0; i < numInputs; i++) {
    int nextIndex = inputString.indexOf(',', currentIndex);
    if (nextIndex == -1) {
      // If there are less inputs than expected, return an error
      if (i != numInputs-1) {
        numInputs = -1;
        delete[] inputs;
        return NULL;
      }
      nextIndex = inputString.length();
    }
    String inputValueString = inputString.substring(currentIndex, nextIndex);

    // If the input value cannot be parsed as an integer, return an error
    int inputValue;
    if (!inputValueString.toInt() && inputValueString != "0" && inputValueString != "-0") {
      numInputs = -1;
      delete[] inputs;
      return NULL;
    }
    inputValue = inputValueString.toInt();
    inputs[i] = inputValue;
    currentIndex = nextIndex + 1;
  }

  // Free memory allocated for the input string
  String* inputStringPtr = new String(inputString);
  delete inputStringPtr;

  return inputs;
}

void setup() {
  Serial.begin(57600); // Initialize serial communication for debugging

  // Initialize relay pins
  pinMode(relay1, OUTPUT); // Relay 1 control pin
  pinMode(relay2, OUTPUT); // Relay 2 control pin

 

  // Initialize motor control pins
  pinMode(motorAPinIN1, OUTPUT);
  pinMode(motorAPinIN2, OUTPUT);
  pinMode(motorAPinEN,  OUTPUT);
  pinMode(motorBPinIN3, OUTPUT);
  pinMode(motorBPinIN4, OUTPUT);
  pinMode(motorBPinEN,  OUTPUT);
 
  pinMode(motorAPinIN1LEFT, OUTPUT);
  pinMode(motorAPinIN2LEFT, OUTPUT);
  pinMode(motorAPinENLEFT,  OUTPUT);
  pinMode(motorBPinIN3LEFT, OUTPUT);
  pinMode(motorBPinIN4LEFT, OUTPUT);
  pinMode(motorBPinENLEFT,  OUTPUT);
 
  pinMode(motorCPinIN1, OUTPUT);
  pinMode(motorCPinIN2, OUTPUT);
  pinMode(motorCPinEN,  OUTPUT);
  pinMode(motorDPinIN3, OUTPUT);
  pinMode(motorDPinIN4, OUTPUT);
  pinMode(motorDPinEN,  OUTPUT);

// Servos
  servo1.attach(8);  // attaches the servo1 on pin 9 to the servo object
  servo1.write(servoPos1);  // initialize servo to start at 90 degrees
  servo2.attach(6); // attach servo 2 to pin 34 rotate gripper
  servo2.write(servoPos2);  // initialize servo to start at 90 degrees
  servo3.attach(7); // attach servo 2 to pin 34 rotate gripper
  servo3.write(servoPos3);  // initialize servo to start at 90 degrees
}

void loop() {
   if (Serial.available()) {
    String inputString = Serial.readStringUntil('\n'); // read the string
    Serial.println(inputString); // print the string for debugging
   
    
  
    // Parse input values
    byte numInputs;
    int* inputs = parseInputs(inputString, numInputs);

    if (numInputs == 0) {
      Serial.println("Error: Expected " + String(numInputsExpected) + " inputs, received " + String(inputs ? abs(numInputs) : 0));
    } else { 
    
      // Extract the input values and do something with them...
      const int joystick1X = inputs[0];
      const int joystick1Y = inputs[1];
      const int joystick2X = inputs[2];
      const int joystick2Y = inputs[3];
      bool button1State = (inputs[4] == 0);
      bool button2State = (inputs[5] == 0);
      bool button3State = (inputs[6] == 0);
      bool button4State = (inputs[7] == 0 );
      bool button5State = (inputs[8] == 0);
      bool button6State = (inputs[9] == 0);
     /*
      // Print the values for debugging
      Serial.print("Joystick 1 X: ");
      Serial.println(joystick1X);
     
      Serial.print("Joystick 1 Y: ");
      Serial.println(joystick1Y);
      Serial.print("Joystick 2 X: ");
      Serial.println(joystick2X);
      Serial.print("Joystick 2 Y: ");
      Serial.println(joystick2Y);
      Serial.print("Button 1 state: ");
      Serial.println(button1State);
      Serial.print("Button 2 state: ");
      Serial.println(button2State);
      Serial.print("Button 3 state: ");
      Serial.println(button3State);
      Serial.print("Button 4 state: ");
      Serial.println(button4State);
      Serial.print("Button 5 state: ");
      Serial.println(button5State);
      Serial.print("Button 6 state: ");
      Serial.println(button6State);
      */
      
    // Control the relays based on button states arm motor
    if (button1State) {
      digitalWrite(relay1, HIGH); // Turn on relay 1
      digitalWrite(relay2, LOW); // Turn off relay 2
    }
        else if (button3State) {
      digitalWrite(relay1, LOW); // Turn off relay 1
      digitalWrite(relay2, HIGH); // Turn on relay 2
    }
        else {
      digitalWrite(relay1, LOW); // Turn off relay 1
      digitalWrite(relay2, LOW); // Turn off relay 2
    }

 // Set motor C and D speeds based on joystick1Y VERT MOTORS GOING UP AND DOWN
    int motorSpeed = joystick1Y;
    int VoltageMax = 12;
    int motorMaxSpeed = 100; // set the maximum motor speed to 100
    int motorPWM = map(constrain(motorSpeed, -motorMaxSpeed, motorMaxSpeed), -motorMaxSpeed, motorMaxSpeed,-VoltageMax*15, VoltageMax*15);

    if (motorSpeed > 0) { // moving joystick up
      digitalWrite(motorCPinIN1, HIGH); // set motor C direction forward
      digitalWrite(motorCPinIN2, LOW);
      analogWrite(motorCPinEN, motorPWM); // set motor C speed forward
      digitalWrite(motorDPinIN3, HIGH); // set motor D direction reverse
      digitalWrite(motorDPinIN4, LOW);
      analogWrite(motorDPinEN, motorPWM); // set motor D speed reverse
    }
      else if(motorSpeed < 0){ // moving joystick down
        digitalWrite(motorCPinIN1, LOW); // set motor C direction reverse
        digitalWrite(motorCPinIN2, HIGH);
        analogWrite(motorCPinEN, -motorPWM); // set motor C speed reverse
        digitalWrite(motorDPinIN3, LOW); // set motor D direction forward
        digitalWrite(motorDPinIN4, HIGH);
        analogWrite(motorDPinEN, -motorPWM); // set motor D speed forward
    }
      else{ // joystick at rest
        digitalWrite(motorCPinIN1, LOW); // stop motor C
        digitalWrite(motorCPinIN2, LOW);
        analogWrite(motorCPinEN, 0);
        digitalWrite(motorDPinIN3, LOW); // stop motor D
        digitalWrite(motorDPinIN4, LOW);
        analogWrite(motorDPinEN, 0);
    }
    
    // HORZ MOTORS
      int motorSpeed2 = joystick2Y; // Get joystick2Y value for Foward and reverse movement 
      int motorSpeed3 = joystick2X; // Get joystick2X value for Turning left and right 
      // Check if both joystick values are zero
      if (motorSpeed2 == 0 && motorSpeed3 == 0) {
        digitalWrite(motorAPinIN1, LOW); // stop motor A
        digitalWrite(motorAPinIN2, LOW);
        analogWrite(motorAPinEN, 0);
        digitalWrite(motorBPinIN3, LOW); // stop motor B
        digitalWrite(motorBPinIN4, LOW);
        analogWrite(motorBPinEN, 0);
        digitalWrite(motorAPinIN1LEFT, LOW); // stop motor A
        digitalWrite(motorAPinIN2LEFT, LOW);
        analogWrite(motorAPinENLEFT, 0);
        digitalWrite(motorBPinIN3LEFT, LOW); // stop motor B
        digitalWrite(motorBPinIN4LEFT, LOW);
        analogWrite(motorBPinENLEFT, 0);
      }
              else if (motorSpeed2 != 0) { // If vertical joystick movement detected
            // Set motor A and B speeds based on joystick2Y value
            // HORZ MOTORS GOING FORWARD AND BACK
            int VoltageMax2 = 6;
            int motorMaxSpeed2 = 100; // set the maximum motor speed to 100
            int motorPWM2 = map(constrain(motorSpeed2, -motorMaxSpeed2, motorMaxSpeed2), -motorMaxSpeed2, motorMaxSpeed2, -VoltageMax2*15, VoltageMax2*15);
            
            if (motorSpeed2 > 0) { // moving joystick up
              digitalWrite(motorAPinIN1, HIGH); // set motor A direction forward
              digitalWrite(motorAPinIN2, LOW);
              analogWrite(motorAPinEN, motorPWM2); // set motor A speed forward
              digitalWrite(motorBPinIN3, LOW); // set motor B direction reverse
              digitalWrite(motorBPinIN4, HIGH);
              analogWrite(motorBPinEN, motorPWM2); // set motor B speed reverse
            } else { // moving joystick down
              digitalWrite(motorAPinIN1, LOW); // set motor A direction reverse
              digitalWrite(motorAPinIN2, HIGH);
              analogWrite(motorAPinEN, -motorPWM2); // set motor A speed reverse
              digitalWrite(motorBPinIN3, HIGH); // set motor B direction forward
              digitalWrite(motorBPinIN4, LOW);
              analogWrite(motorBPinEN, -motorPWM2); // set motor B speed forward
            }
          }  else if (motorSpeed3 != 0) { // If horizontal joystick movement detected
            // Set motor A and B speeds based on joystick2X value
            // HORZ MOTORS turn left or right 
            int VoltageMax3 =  6; // set the maximum voltage to 8V
            int motorMaxSpeed3 = 100; // set the maximum motor speed to 100
            int motorPWM3 = map(constrain(motorSpeed3, -motorMaxSpeed3, motorMaxSpeed3), -motorMaxSpeed3, motorMaxSpeed3,-VoltageMax3*15, VoltageMax3*15);
          
            if (motorSpeed3 > 0) { // moving joystick left
              digitalWrite(motorAPinIN1LEFT, HIGH); // set motor A direction forward
              digitalWrite(motorAPinIN2LEFT, LOW);
              analogWrite(motorAPinENLEFT, motorPWM3); // set motor A speed forward
              digitalWrite(motorBPinIN3LEFT, HIGH); // set motor B direction reverse
              digitalWrite(motorBPinIN4LEFT, LOW);
              analogWrite(motorBPinENLEFT, motorPWM3); // set motor B speed reverse
            } else { // moving joystick right
              digitalWrite(motorAPinIN1LEFT, LOW); // set motor A direction reverse
              digitalWrite(motorAPinIN2LEFT, HIGH);
              analogWrite(motorAPinENLEFT, -motorPWM3); // set motor A speed reverse
              digitalWrite(motorBPinIN3LEFT, LOW); // stop motor B
              digitalWrite(motorBPinIN4LEFT, HIGH);
              analogWrite(motorBPinENLEFT,-motorPWM3 );
            }
          }
      
  // servo 1 open close gripper with left joystick moving in x direction
  int Servo1Num = joystick1X ;

  if (Servo1Num == 0) { // if joystick input is 0, servo remains in last position
    // Do nothing
  } else if (Servo1Num < 0) {  // if joystick is pushed left (negative X-axis value)
    if (servoPos1 < 160) {  // rotate servo towards 180 degrees
        servoPos1 += 5;  // increment servo position by 1 degree
        servo1.write(servoPos1);  // write new servo position to servo
        
    }
  } else if (Servo1Num > 0) {  // if joystick is pushed right (positive X-axis value)
    if (servoPos1 > 100) {  // rotate servo towards 0 degrees
        servoPos1 -= 5;  // decrement servo position by 1 degree
        servo1.write(servoPos1);  // write new servo position to servo
        
    }
  }

  // servo 3 angle
  // Check for button 5 and 6 state
      if (button5State) {
      if (servoPos3 < 100) { // rotate servo towards 180 degrees
      servoPos3 += 1;
      servo3.write(servoPos3);
    
        }
       }   else if (button6State) {
        if (servoPos3 > 20) { // rotate servo towards 0 degrees
        servoPos3 -= 1;
        servo3.write(servoPos3);
       
        }
       }
       
  // servo 2 rotatio 
  // Check for button 2 and 4 state
      if (button2State) {
      if (servoPos2 < 160) { // rotate servo towards 180 degrees
      servoPos2 += 1;
      servo2.write(servoPos2);
      
        }
       }   else if (button4State) {
        if (servoPos2 > 95) { // rotate servo towards 0 degrees
        servoPos2 -= 1;
        servo2.write(servoPos2);
       
        }
       }
    }
   }
}

the output looks like this:

<0,0,0,0,1,1,1,1,1,1>
<0,0,0,0,1,1,1,1,1,1>
<0,0,0,0,1,1,1,1,1,1>
<0,0,0,0,1,1,1,1,1,1>( end of working)
0(starts to not control and Radom motors are turned on and don't stop have to unplug)
<0,0,0,0,1,1,1,1,1,1>
0
<0,0,0,0,1,1,1,1,1,1>
0
<0,0,0,0,1,1,1,1,1,1>
0
<0,0,0,0,1,1,1,1,1,1>

Is this output is after 30 second or from the starting

this is around the 30second mark when it changes before that its just content strings with no spaces probably around 400 strings im thinking something with memory not sure tho

  return inputs;

You are returning a pointer to a local variable. Will that cause a problem ?

@westfootball99 , you could have edited your initial post in your earlier discussion:

Maybe one of the moderators will combine your two posts as others may be unaware that you have now asked the same Q in 2 different categories.

On the plus side, thanks for using code tags - it makes your code a lot easier to read through.

Avoid using the String type and stick to simple null terminated c strings.

Your two or more topics on the same or similar subject have been merged.

Please do not duplicate your questions as doing so wastes the time and effort of the volunteers trying to help you as they are then answering the same thing in different places.

Please create one topic only for your question and choose the forum category carefully. If you have multiple questions about the same project then please ask your questions in the one topic as the answers to one question provide useful context for the others, and also you won’t have to keep explaining your project repeatedly.

Repeated duplicate posting could result in a temporary or permanent ban from the forum.

Could you take a few moments to Learn How To Use The Forum

It will help you get the best out of the forum in the future.

Thank you.

fast repeated assigning new values to variables of type String
Do you see the capital "S" ?

Eats up all RAM-memory over time and then other variables will be overwritten.

This will make your code act very strange and it is very hard to debug.

This is the reason why you should change your code to

not

use
variables of type String

If I see right you are transmitting some relay-state-values and some X-pot / Y-Pot values for motorspeed.

There is absolutely no need to transmitt Strings for this.
It would be sufficient to use integers or longs.
If you like to keep sending character-sequence I recommend using the SafeString-library

@the c_string fans:
If you recommend using pure c_strings make sure to explain everything nescessary to avoid out of boundary writing with the char-arrays
Oh !! You are too lazy to write that?
Then it is ok to use the SafeString-library

So the options are:
learning to use pure c_strings (including how to do array-boundary checking)
learning how to use the SafeString-library which offers almost the same comfort as Strings
learning how to send much less bytes by using the code from serial input basics

with start and endmarkers

best regards Stefan

100% agree there is not need for string and I thought the same thing seems like it gets messed up in the same spot or same number of passes and running out of ram the issue is this code talks to a controller that outputs string that my professor coded and I can’t recode the controller so I have to make my code read strings so I don’t know what to do.

as I already mentioned

The name SafeString is program
SafeStrings are really safe. They do not eat up RAM over time.
You define them at compile-time and then they need just the RAM as defined

Sorry about that I’m new to Arduino I didn’t understand if that mean recode the controller or mine I’ll give it a go I spent about 15 hours trying to debug and I couldn’t get it

here is a demo-code using the SafeString-library that might come close to what you need
I guess you have to replace Serial with Softwareserial

// SafeStringReader_Cmds.ino
//
// Example of NON-Blocking read commmands from the Arduino Monitor input and acts on them
// the available commands are start stop
// See the SafeStringReader_CmdsTimed.ino for an example using a struct to hold the commands and their functions
//
// Commands are delimited by space dot comma NL or CR
// If you set the Arduino Monitor to No line ending then the last command will be ignored until it is terminated by a space or ,
//  Use the settings Newline or Carrage Return or Both NL & CR
//
// These commands can be picked out of a line of user input
// start  stop
// The input line can be as long as you like 100's of Kb long, but only two small buffers need to parse the commands
//
// download and install the SafeString library from
// www.forward.com.au/pfod/ArduinoProgramming/SafeString/index.html
#include "SafeStringReader.h"

// create an sfReader instance of SafeStringReader class
// that will handle commands upto 5 chars long
// delimited by space, comma or CarrageReturn or NewLine
// the createSafeStringReader( ) macro creates both the SafeStringReader (sfReader) and the necessary SafeString that holds input chars until a delimiter is found
// args are (ReaderInstanceName, expectedMaxCmdLength, delimiters)
createSafeStringReader(sfReader, 5, " ,\r\n");

bool running = true;
unsigned long loopCounter = 0;

void setup() {
  Serial.begin(115200);
  for (int i = 10; i > 0; i--) { // pause a little to give you time to open the Arduino monitor
    Serial.print(i); 
    Serial.print(' '); 
    delay(500);
  }
  Serial.println();
  Serial.println(F(" Commands are stop start"));
  Serial.println(F(" Set the Arduino IDE monitor to Newline, or Carriage return or Both NL & CR"));
  Serial.println(F(" See the SafeStringReader_CmdsTimed.ino for an example using a struct to hold the commands and their functions."));

  SafeString::setOutput(Serial); // enable error messages and SafeString.debug() output to be sent to Serial
  if (running) {
    Serial.println(F(" Counter Started"));
  }
  sfReader.connect(Serial); // where SafeStringReader will read from
  sfReader.echoOn(); // echo back all input, by default echo is off
}

void handleStartCmd() {
  running = true;  
  Serial.println(); 
  Serial.print(F("> start at Counter:")); 
  Serial.println(loopCounter);
}

void handleStopCmd() {
  running = false; 
  Serial.println(); 
  Serial.print(F("> stop at Counter:")); 
  Serial.println(loopCounter);
}

void loop() {
  if (sfReader.read()) {
    if (sfReader == "start") {
      handleStartCmd();
    } else if (sfReader == "stop") {
      handleStopCmd();
    } // else ignore unrecognized command
  } // else no delimited command yet

  // rest of code here is executed while the user typing in commands
  if (running) {
    loopCounter++;
    if ((loopCounter % 100000) == 0) { // print the current counter every now and again
      Serial.print(F("Counter:")); 
      Serial.println(loopCounter);
    }
  }
}

If it does not work with SoftwareSerial simply replace your Strings with SafeStrings

This may require recoding some more parts as SafeStrings use different functions than Strings
best regards Stefan

Do you know what the maximum length of the string could be? It should be defined somewhere - ask your professor.

here is my professors code

//JOYSITICK MANUAL CONTROLLER/TRANSMITTER: Sends control data in CSV string formatting over serial.
//Written By: Nicholas Pilato 
//Date Written: December 20, 2017
//Last Modified: January 23, 2018

#define Foward_Reverse_Pin A1 // Y axis on joystick 1
#define Yaw_Pin A0 // X axis on joystick 1
#define buttonOne 2//Joystick 1 button
#define buttonTwo 3// Joystick 2 button
#define Pitch_Pin A2 // Y axis joystick 2
#define Roll_Pin A3 // X axis on joystick 2
#define LED 11 //LED indicator


int Foward_Reverse_Unmapped;
int Foward_Reverse;

int Yaw_Unmapped;
int Yaw;

int Pitch_Unmapped;
int Pitch;

int Roll_Unmapped;
int Roll;

int Lateral_Unmapped;
int Lateral;

int Vertical_Unmapped;
int Vertical;

int LeftUD;
int LeftLR;
int RightUD;
int RightLR;
int LeftUD_Unmapped;
int LeftLR_Unmapped;
int RightUD_Unmapped;
int RightLR_Unmapped;

int D2;
int D3;
int D4;
int D5;
int D6;
int D7;

int systemMode;

bool buttonOneMode = 0;
bool buttonTwoMode = 0;
bool ledMode = 0; 



  /////////////////////////////////////////////////////////////////////////////////////
 ///-----------------------------------SETUP--------------------------------------///
///////////////////////////////////////////////////////////////////////////////////

void setup() {
  pinMode(Foward_Reverse_Pin, INPUT); //Left F/R
  pinMode(Yaw_Pin, INPUT);            //Left L/R
  pinMode(Pitch_Pin, INPUT);          //Right F/R
  pinMode(Roll_Pin, INPUT);           //Right L/R

  pinMode(buttonOne, INPUT_PULLUP);
  pinMode(buttonTwo, INPUT_PULLUP);
  pinMode(4, INPUT_PULLUP);
  pinMode(5, INPUT_PULLUP);
  pinMode(6, INPUT_PULLUP);
  pinMode(7, INPUT_PULLUP);
  pinMode(LED, OUTPUT);
  
  Serial.begin(57600);
  Serial.println("hola");
  
  systemMode = 1; // 0 = screw command, 1 = raw outputs
}

  /////////////////////////////////////////////////////////////////////////////////////
 ///---------------------------------MAIN LOOP------------------------------------///
///////////////////////////////////////////////////////////////////////////////////

void loop() {
  readJoystick();
  sendData();
  delay(50);
}

  ///////////////////////////////////////////////////////////////////////////////////
 //---------------------------------FUNCTIONS------------------------------------///
///////////////////////////////////////////////////////////////////////////////////

void readJoystick () {
  
  if(systemMode == 0) //Screw Command (surge/sway/heave/roll/pitch/yaw)
  {
    if (digitalRead(buttonOne) == LOW ) {
      delay(50);
      if (digitalRead(buttonOne) == LOW) {
        while (digitalRead(buttonOne) == LOW) {
          sendData();
          }
        buttonOneMode = !buttonOneMode;
        ledMode = !ledMode;
      }
    }
  
    if (buttonOneMode == LOW) {
  
      //Turn off led
      digitalWrite(LED, ledMode);
  
      //Read values From Joysticks
      
      Foward_Reverse_Unmapped = analogRead(Foward_Reverse_Pin);
      Yaw_Unmapped = analogRead(Yaw_Pin);
      Pitch_Unmapped = analogRead(Pitch_Pin);
      Roll_Unmapped = analogRead(Roll_Pin);
  
      //Map Values
      
      Foward_Reverse = map(Foward_Reverse_Unmapped, 0, 972, -100, 100);
      if (Foward_Reverse > 100) {
        Foward_Reverse = 100;
      }
      Yaw = map(Yaw_Unmapped, 0, 972, -100, 100);
      if (Yaw > 100) {
        Yaw = 100;
      }
      
      Pitch = map(Pitch_Unmapped, 0, 1023, -100, 100);
      
      Roll = map(Roll_Unmapped, 0, 1057, -100, 100);
      if (100-Roll == 7) {
        Roll = 100;
      }
  
      // Set vertical and lateral outputs to zero. This is to differentiate between non-angular
      // lateral and vertical movement form angular movement (pitch, roll, yaw).
  
      Vertical = 0;
      Lateral = 0;
    }
  
  
  
    if (buttonOneMode == HIGH) {
  
      // Turn LED On
      digitalWrite(LED, ledMode);
  
      Vertical_Unmapped = analogRead(Foward_Reverse_Pin);
      Vertical = map(Vertical_Unmapped, 0, 972, -100, 100);
      if (Vertical > 100) {
        Vertical = 100;
      }
      
      Lateral_Unmapped = analogRead(Yaw_Pin);
      Lateral = map(Lateral_Unmapped, 0, 972, -100, 100);
      if (Lateral > 100) {
        Lateral = 100;
      }
  
      Pitch_Unmapped = analogRead(Pitch_Pin);
      Pitch = map(Pitch_Unmapped, 0, 1023, -100, 100);
      
      Yaw_Unmapped = analogRead(Roll_Pin);
      Yaw = map(Yaw_Unmapped, 0, 1057, -100, 100);  
      if (100-Yaw == 7) {
        Yaw = 100;
      }
    }
  }
  else //Raw mode
  {
    LeftUD_Unmapped = analogRead(Foward_Reverse_Pin);
    LeftUD = map(LeftUD_Unmapped, 0, 972, -100, 100);
    LeftLR_Unmapped = analogRead(Yaw_Pin);
    LeftLR = map(LeftLR_Unmapped, 0, 972, -100, 100);
    RightUD_Unmapped = analogRead(Pitch_Pin);
    RightUD = map(RightUD_Unmapped, 0, 1023, -100, 100);
    RightLR_Unmapped = analogRead(Roll_Pin)-20;
    RightLR = map(RightLR_Unmapped, 0, 1023, -100, 100);
    D3 = digitalRead(3);
    D4 = digitalRead(4);
    D5 = digitalRead(5);
    D6 = digitalRead(6);
    D2 = digitalRead(2);
    D7 = digitalRead(7);
    
  }
}

void sendData()  { 
  if(systemMode == 0)
  {
    String commandString = String(Foward_Reverse);
    commandString = "<" + commandString + "," + Vertical + "," + Lateral + "," + Roll + "," + Pitch + "," + Yaw + ">";
    Serial.println(commandString);
  }
  else
  {
    String commandString = String(LeftUD);
    commandString = "<" + commandString + "," + LeftLR + "," + RightUD + "," + RightLR + "," + D2 + "," + D3 + "," + D4 + "," + D5 + "," + D6 + "," + D7 + ">";
    Serial.println(commandString);
  }
//  Serial.print(Foward_Reverse);
//  Serial.print(',');
//  Serial.print(Vertical);
//  Serial.print(',');
//  Serial.print(Lateral);
//  Serial.print(',');
//  Serial.print(Roll);
//  Serial.print(',');
//  Serial.print(Pitch);
//  Serial.print(',');
//  Serial.println(Yaw);

}

The sended character sequence uses a start-marker "<" and an endmarker ">"
so you oculd use the function like desribed in the serial input basics from robin2

this function stores the characters into an char-array
Then you copy the char-array to a SafeString and go from there

// fetch data from receivebuffer
void recvWithStartEndMarkers() {
  static boolean recvInProgress = false;
  static byte ndx = 0;
  char startMarker = '<';
  char endMarker = '>';
  char rc;

  // if bytes are inside the receivebuffer .available() > 0
  // .available() delivers the number of bytes in the buffer
  while (Serial2.available() > 0 && newData == false) {
    rc = Serial2.read();

    if (recvInProgress == true) { // if startmamrker is found set flag
      if (rc != endMarker) {      // if byte in variable "rc" is NOT the Endmarker 
        receivedChars[ndx] = rc;  // append byte in variable "rc to end of array
        ndx++;                    // increment indexcounter
        if (ndx >= numChars) {    // if byteseqwuence is too long
          ndx = numChars - 1;     // reduce indexcounter throw away the byte
        }
      } // if (rc != endMarker) {
      else {
        receivedChars[ndx] = '\0'; // terminate the string with trailing zero
        recvInProgress = false;    // set flag message received finished
        ndx = 0;
        newData = true;            // set flag command received completely 
      }
    } // if (recvInProgress == true) {

    else if (rc == startMarker) {  // if Byte in variable "rc" is the startmarker
      recvInProgress = true;       // set boolean flag 
    }
  } // while (Serial2.available() > 0 && newData == false) {
}

if a full sequence is received variable newData is set to true

if (NewData) {
// process data
}

best regards Stefan