Code behaving oddly

I am building a Johnny 5 inspired robot. I have a track assembly, a humanoid torso,Arduino Mega with a sensor shield, L298 Motor Driver Module,Torobot servo driver board, PS2 Controller, HC 05 Bluetooth module, SRF04 unit and 1.3" OLED display. I have upgraded the Scanning "Radar" project to have duplex communication, and have added modes, speeds and a tilt function for the head. I have an FPV cam, Video TX, IMU and an IR ranging module to add as well. I am using a Finite State Machine that is switched by the PS2 controller by using a combination of buttons to give me a maximum of 16 states that I can call from the remote. I have many pieces of code written for each of the states. State 2 is the scanning code. The backbone (PS2 controller and FSM) works great until I put in the scanning code. When I run this sketch I can enter state 2 but switching out of 2 it makes me wait until both halves of the scan are finished before changing states. Here is the code. What am I missing.

void poll_controller() {
  ps2x.read_gamepad(false, vibrate);          //read controller and set large motor to spin at 'vibrate' speed
  //ps2x.Analog(PSAB_BLUE)ps2x.Button(PSB_START)

  if (ps2x.Analog(PSAB_GREEN)) {                 //will be TRUE as long as button is pressed

    if (ps2x.NewButtonState())              //will be TRUE if any button changes state (on to off, or off to on)
    {
      if (ps2x.Button(PSB_L1))
        //Serial.println("Tri+L1 pressed");
        state = 1;
      if (ps2x.Button(PSB_R1))
        // Serial.println("Tri+R1 pressed");
        state = 2;
      if (ps2x.Button(PSB_L2))
        // Serial.println("Tri+L2 pressed");
        state = 3;
      if (ps2x.Button(PSB_R2))
        // Serial.println("Tri+R2 pressed");
        state = 4;
    }
  }
  
  if (ps2x.Analog(PSAB_RED)) {                 //will be TRUE as long as button is pressed

    if (ps2x.NewButtonState())              //will be TRUE if any button changes state (on to off, or off to on)
    {
      if (ps2x.Button(PSB_L1))
        state = 13;
      //Serial.println("Cir+L1 pressed");
      if (ps2x.Button(PSB_R1))
        state = 14;
      //Serial.println("Cir+R1 pressed");
      if (ps2x.Button(PSB_L2))
        state = 15;
      //Serial.println("Cir+L2 pressed");
      if (ps2x.Button(PSB_R2))
        state = 16;
      //Serial.println("Cir+R2 pressed");
    }
  }
  
}
void scanner() {
  // Serial.println(state);
  // rotates the servo motor from 15 to 165 degrees
  for (int i = min_sweep; i <= max_sweep; i++) {
    Pan_Servo.write(i);
    //IMU_Data();
    Tilt_Servo.write(j);
    ps2x.read_gamepad(false, vibrate);
    poll_controller();
    delay(sweep_rate);
    buttons();
    get_US_range();
    Serial.print(i); // Sends the current degree into the Serial Port
    Serial.print(","); // Sends addition character right next to the previous value needed later in the Processing IDE for indexing
    Serial.print(sonar.ping_result / US_ROUNDTRIP_CM); // Sends the distance value into the Serial Port
    Serial.print("."); // Sends addition character right next to the previous value needed later in the Processing IDE for indexing 
  }
  // Repeats the previous lines from 165 to 15 degrees
  for (int i = max_sweep; i > min_sweep; i--) {
    Pan_Servo.write(i);
    //IMU_Data();
    Tilt_Servo.write(j);
    ps2x.read_gamepad(false, vibrate);
    poll_controller();
    delay(sweep_rate);
    buttons(); 
    get_US_range();
    Serial.print(i);
    Serial.print(",");
    Serial.print(sonar.ping_result / US_ROUNDTRIP_CM);//Ranging data
    Serial.print(".");
  }

  
  buttons();
  ps2x.read_gamepad(false, vibrate);
  poll_controller();

}

I find it easier to send a debug message to the Serial Monitor for each type of button press.
You'll find out soon enough your logic error.

.

Yeah, I did that and see the button presses but the sonar finishes before responding

What are the values for min_sweep and max_sweep in below (probably 15 and 165 but not sure)

for (int i = min_sweep; i <= max_sweep; i++)

What is the value of sweep_rate in below

    delay(sweep_rate);

So that's a delay of 150 times how much?

Getting rid of the delay in favour of a millis() based approach will probably solve the problem.

PS
If you would have posted the complete code, I would not have had to ask the questions.

/*Johnny 5 code 4/12/2020
/*Author Lane Barry
/*-----( Import needed libraries )-----*/
// system states //
#define SLEEP        0
#define WAKE         1
#define SEARCH       2
#define DRIVE        3
#define MANIPULATE   4
#define CROUCH       5
#define STOW         6
#define SEQUENCE     7
#define MANUAL       8
#define ERROR        9
#define NAG          10

#include "U8glib.h"
U8GLIB_SH1106_128X64 u8g(U8G_I2C_OPT_NONE);  // I2C / TWI 


#include <Servo.h>
#include <NewPing.h>
#define TRIGGER_PIN 3 // Arduino pin tied to trigger pin on ping sensor.
#define ECHO_PIN 4 // Arduino pin tied to echo pin on ping sensor.
#define MAX_DISTANCE 200 // Maximum distance we want to ping for (in centimeters). Maximum sensor distance is rated at 400-500cm.
#define beeper    53
int min_sweep = 20;
int max_sweep = 130;
int min_tilt = 0;
int max_tilt = 180;
int sweep_rate = 40;
float correct;
int k = 0;
int j = 90;
// Defines Trig and Ecko pins of the Ultrasonic Sensor
const int trigPin = 3;
const int echoPin = 4;
// Variables for the duration and the distance
long duration;
int distance;
Servo Pan_Servo; // Creates a servo object for controlling the servo motor
Servo Tilt_Servo; // Creates a servo object for controlling the servo motor

NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE); // NewPing setup of pins and maximum distance.
unsigned int pingSpeed = 50; // How frequently are we going to send out a ping (in milliseconds). 50ms would be 20 times a second.
unsigned long pingTimer; // Holds the next ping time.
// ---------------------------------------------------------------------------
char val; // Data received from the serial port
int command = 2;       // This is the command char, in ascii form, sent from the serial port
byte zero;
int state = 2;       // master variable for the state machine
int second; // declare time variables
int counter = 0;
/////////////////////////////////////////
#include <PS2X_lib.h>  //for v1.6
PS2X ps2x; // create PS2 Controller Class
int error = 0;
byte type = 0;
byte vibrate = 0;

void setup()
{

// flip screen, if required
  u8g.setRot180();
  
  u8g.setFont(u8g_font_unifont);
  u8g.setColorIndex(1); // Instructs the display to draw with a pixel on.



u8g.firstPage();
  do {  
    draw();    
  } while( u8g.nextPage() );
  delay(500); 
  u8g.firstPage();
  do {  
    draw2();    
  } while( u8g.nextPage() ); 
 delay(500); 
  u8g.firstPage();
do {  
    draw3();    
  } while( u8g.nextPage() ); 
 delay(500);
u8g.firstPage();
do {  
    draw4();    
  } while( u8g.nextPage() ); 
 delay(500);





  
  //CHANGES for v1.6 HERE!!! **************PAY ATTENTION*************

  error = ps2x.config_gamepad(13, 11, 10, 12, true, true); //setup pins and settings:  GamePad(clock, command, attention, data, Pressures?, Rumble?) check for error

  if (error == 0) {
    Serial.print("");

    //Serial.println("Found Controller, configured successful");
    // Serial.println("Try out all the buttons, X will vibrate the controller, faster as you press harder;");
    //Serial.println("holding L1 or R1 will print out the analog stick values.");
    //Serial.println("Go to www.billporter.info for updates and to report bugs.");
  }

  else if (error == 1)
    Serial.println("No controller found, check wiring, see readme.txt to enable debug. visit www.billporter.info for troubleshooting tips");

  else if (error == 2)
    Serial.println("Controller found but not accepting commands. see readme.txt to enable debug. Visit www.billporter.info for troubleshooting tips");

  else if (error == 3)
    //Serial.println("Controller refusing to enter Pressures mode, may not support it. ");
    Serial.print(".");

  //Serial.print(ps2x.Analog(1), HEX);

  type = ps2x.readType();
  switch (type) {
    case 0:
      Serial.println("Unknown Controller type");
      break;
    case 1:
      Serial.println("DualShock Controller Found");
      Serial.print("");

u8g.firstPage();
  do {  
    draw5();    
  } while( u8g.nextPage() );
  delay(500); 

  u8g.firstPage();
  do {  
    draw6();    
  } while( u8g.nextPage() ); 
 delay(500); 
  u8g.firstPage();


do {  
    draw7();    
  } while( u8g.nextPage() ); 
 delay(500);

      break;
    case 2:
      Serial.println("GuitarHero Controller Found");
      break;
  }
  /*-----( scanning sonar )-----*/
  // ----------------------------------U/S Ranging-----------------------------------------
  pingTimer = millis(); // Start now.
  // ---------------------------------------------------------------------------
  pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
  pinMode(echoPin, INPUT); // Sets the echoPin as an Input
  //Serial.begin(115200);
  Pan_Servo.attach(5); // Defines on which pin is the servo motor attached
  Tilt_Servo.attach(6); // Defines on which pin is the servo motor attached
  //Tilt_Servo.write(45);
  // pinMode(ledPin, OUTPUT); // Set pin as OUTPUT
  // pinMode(ledPin, OUTPUT); // Set pin as OUTPUT
  //initialize serial communications at a 9600 baud rate
  // Serial.begin(115200);
  //establishContact(); // send a byte to establish contact until receiver responds

  /*----------------------------*/

  //initialize serial communications at a 115200 baud rate
  Serial.begin(115200);
  // Serial.print("Setup Finished");
}

void loop()
{
  //Serial.println(state);
  poll_controller();

  switch (state)
  {
    case SLEEP:
      HandleSLEEPState();
      break;
    case WAKE:
      HandleWAKEState();
      break;
    case SEARCH:
      HandleSEARCHState();
      break;
    case DRIVE:
      HandleDRIVEState();
      break;
    case MANIPULATE:
      HandleMANIPULATEState();
      break;
    case CROUCH:
      HandleCROUCHState();
      break;
    case STOW:
      HandleSTOWState();
      break;
      HandleSLEEPState();
      break;
    case ERROR:
      HandleERRORState();
      break;
    case MANUAL:
      HandleMANUALState();
      break;
    case NAG:
      HandleNAGState();
      break;

    default:
      Serial.print("Unknown State: ");
      Serial.println(state);
      allRelaysOff; // Should never get here
      break;
  }
}
/////////////////////////////////////////////////////////////////
void HandleNAGState()
{
//Serial.println(state);

}
/////////////////////////////////////////////////////////////////
void HandleERRORState()
{
// Serial.println(state);
}
/////////////////////////////////////////////////////////////////
void HandleSEQUENCEState()
{
//Serial.println(state);
//check_buttons();
}
/////////////////////////////////////////////////////////////////
void HandleWAKEState()
{
  Pan_Servo.write(90);
  Tilt_Servo.write(90);
  ps2x.read_gamepad(false, vibrate);
  poll_controller();

}
/////////////////////////////////////////////////////////////////
void HandleSEARCHState()
{
scanner();
}

/////////////////////////////////////////////////////////////////
void HandleDRIVEState()

{
Pan_Servo.write(130);
  Tilt_Servo.write(100);
  ps2x.read_gamepad(false, vibrate);
  poll_controller();

}
////////////////////////////////////////////////////////////////
void HandleMANIPULATEState()
{

Pan_Servo.write(40);
  Tilt_Servo.write(120);
  ps2x.read_gamepad(false, vibrate);
  poll_controller();
}
/////////////////////////////////////////////////////////////////
void HandleCROUCHState()

{
//Serial.println(state);
//check_buttons();
}
/////////////////////////////////////////////////////////////////
void HandleSTOWState()
{
// Serial.println(state);
//check_buttons();

}
/////////////////////////////////////////////////////////////////

void HandleDRAINING2State()

{
// Serial.println(state);
}
/////////////////////////////////////////////////////////////////
void HandlePAUSE2State()
{
//Serial.println(state);
}
/////////////////////////////////////////////////////////////////
void HandleFILLING3State()

{

//Serial.println(state);
}
/////////////////////////////////////////////////////////////////
void HandleSTIRRING3State()
{
// Serial.println(state);
}
/////////////////////////////////////////////////////////////////
void HandleDRAINING3State()

{
// Serial.println(state);
}
/////////////////////////////////////////////////////////////////
void allRelaysOff() {
// Serial.println(state);

}
/////////////////////////////////////////////////////////////////
void HandleSTOPPEDState()
{
// Serial.println(state);
}
//////////////////////////////////////////////////////////////////
void HandleSLEEPState()
{
//Serial.println(state);
}
/////////////////////////////////////////////////////////////////
void HandleMANUALState()
{
//Serial.println(state);
}
/////////////////////////////////////////////////////////////////
void ABORT() {
//Serial.println(state);

}
/////////////////////////////////////////////////////////////////
void establishContact() {
while (Serial.available() <= 0) {
  Serial.print("A"); // send a capital A
  //aSerial.println("."); // send a capital A
 
}
}
///////////////////////////////////////////////////////////////////
void get_US_range() {
if (millis() >= pingTimer) { // pingSpeed milliseconds since last ping, do another ping.
  pingTimer += pingSpeed; // Set the next ping time.
  sonar.ping_timer(echoCheck); // Send out the ping, calls "echoCheck" function every 24uS where you can check the ping status.
}
// Do other stuff here, really. Think of it as multi-tasking.
poll_controller();
}
void echoCheck() { // Timer2 interrupt calls this function every 24uS where you can check the ping status.
// Don't do anything here!
if (sonar.check_timer()) { // This is how you check to see if the ping was received.
}
}

(Use code tags please, </> on the menu, Thanks, Moderator)

///////////////////////////////////////////////////////////////////
void poll_controller() {
ps2x.read_gamepad(false, vibrate);          //read controller and set large motor to spin at 'vibrate' speed
//ps2x.Analog(PSAB_BLUE)ps2x.Button(PSB_START)

if (ps2x.Analog(PSAB_GREEN)) {                 //will be TRUE as long as button is pressed

  if (ps2x.NewButtonState())              //will be TRUE if any button changes state (on to off, or off to on)
  {
    if (ps2x.Button(PSB_L1))
      //Serial.println("Tri+L1 pressed");
      state = 1;
    if (ps2x.Button(PSB_R1))
      // Serial.println("Tri+R1 pressed");
      state = 2;
    if (ps2x.Button(PSB_L2))
      // Serial.println("Tri+L2 pressed");
      state = 3;
    if (ps2x.Button(PSB_R2))
      // Serial.println("Tri+R2 pressed");
      state = 4;
  }
}
if (ps2x.Analog(PSAB_BLUE)) {                 //will be TRUE as long as button is pressed

  if (ps2x.NewButtonState())              //will be TRUE if any button changes state (on to off, or off to on)
  {
    if (ps2x.Button(PSB_L1))
      Serial.println("X+L1 pressed");
    state = 5;
    if (ps2x.Button(PSB_R1))
      Serial.println("X+R1 pressed");
    state = 6;
    if (ps2x.Button(PSB_L2))
      Serial.println("X+L2 pressed");
    state = 7;
    if (ps2x.Button(PSB_R2))
      Serial.println("X+R2 pressed");
    state = 8;
  }
}
if (ps2x.Analog(PSAB_PINK)) {                 //will be TRUE as long as button is pressed

  if (ps2x.NewButtonState())              //will be TRUE if any button changes state (on to off, or off to on)
  {
    if (ps2x.Button(PSB_L1))
      // Serial.println("Sq+L1 pressed");
      state = 9;
    if (ps2x.Button(PSB_R1))
      //Serial.println("Sq+R1 pressed");
      state = 10;
    if (ps2x.Button(PSB_L2))
      // Serial.println("Sq+L2 pressed");
      state = 11;
    if (ps2x.Button(PSB_R2))
      //Serial.println("Sq+R2 pressed");
      state = 12;
  }
}
if (ps2x.Analog(PSAB_RED)) {                 //will be TRUE as long as button is pressed

  if (ps2x.NewButtonState())              //will be TRUE if any button changes state (on to off, or off to on)
  {
    if (ps2x.Button(PSB_L1))
      state = 13;
    //Serial.println("Cir+L1 pressed");
    if (ps2x.Button(PSB_R1))
      state = 14;
    //Serial.println("Cir+R1 pressed");
    if (ps2x.Button(PSB_L2))
      state = 15;
    //Serial.println("Cir+L2 pressed");
    if (ps2x.Button(PSB_R2))
      state = 16;
    //Serial.println("Cir+R2 pressed");
  }
}

}
///////////////////////////////////////////////////////////////
void scanner() {
// Serial.println(state);
// rotates the servo motor from 15 to 165 degrees
for (int i = min_sweep; i <= max_sweep; i++) {
  Pan_Servo.write(i);
  //IMU_Data();
  Tilt_Servo.write(j);
  ps2x.read_gamepad(false, vibrate);
  poll_controller();
  delay(sweep_rate);
  buttons();
  get_US_range();
  Serial.print(i); // Sends the current degree into the Serial Port
  Serial.print(","); // Sends addition character right next to the previous value needed later in the Processing IDE for indexing
  Serial.print(sonar.ping_result / US_ROUNDTRIP_CM); // Sends the distance value into the Serial Port
  Serial.print("."); // Sends addition character right next to the previous value needed later in the Processing IDE for indexing 
}
// Repeats the previous lines from 165 to 15 degrees
for (int i = max_sweep; i > min_sweep; i--) {
  Pan_Servo.write(i);
  //IMU_Data();
  Tilt_Servo.write(j);
  ps2x.read_gamepad(false, vibrate);
  poll_controller();
  delay(sweep_rate);
  buttons(); 
  get_US_range();
  Serial.print(i);
  Serial.print(",");
  Serial.print(sonar.ping_result / US_ROUNDTRIP_CM);//Ranging data
  Serial.print(".");
}
buttons();
ps2x.read_gamepad(false, vibrate);
poll_controller();

}
///////////////////////////////////////////////////////////////////
void buttons() {
//establishContact(); // send a byte to establish contact until receiver responds
if (Serial.available() > 0) { // If data is available to read,
  val = Serial.read(); // read it and store it in val
  /////////----------------------
  if (val == 'r') //if we get a r Fast Sweep
  { sweep_rate = 2;
    // R_State = !R_State; //flip the ledState
    // digitalWrite(13, R_State);
  }
  /////////----------------------
  if (val == 't') //if we get a t
  { sweep_rate = 7;
    //T_State = !T_State; //flip the ledState Quick Sweep
    //digitalWrite(13, T_State);
  }
  /////////----------------------
  if (val == 'b') //if we get at b Medium Sweep
  { sweep_rate = 14;
    // B_State = !B_State; //flip the ledState
    // digitalWrite(13, B_State);
  }
  /////////----------------------
  if (val == 'e') //if we get a e Slow Sweep
  { sweep_rate = 30;
    //F_State = !F_State; //flip the ledState
    //digitalWrite(13, F_State);
  }
  /////////----------------------
  if (val == 'y') //if we get a y Full Sweep
  {
    min_sweep = 40;
    max_sweep = 165;
    // R_State = !R_State; //flip the ledState
    // digitalWrite(13, R_State);
  }
  /////////----------------------
  if (val == 'u') //if we get a u Wide Sweep
  {
    min_sweep = 45;
    max_sweep = 140;
    //T_State = !T_State; //flip the ledState
    //digitalWrite(13, T_State);
  }
  /////////----------------------
  if (val == 'i') //if we get at i Narrow Sweep
  {
    min_sweep = 60;
    max_sweep = 120;
  }
  /////////----------------------
  if (val == 'o') //if we get a o Steer Sweep
  {
    min_sweep = 75;
    max_sweep = 105;
  }
  /////////----------------------
  if (val == 'p') //if we get a p Beam Sweep
  {
    min_sweep = 84;
    max_sweep = 96;
  }
  /////////----------------------
  if (val == 's') //if we get a s Stop Sweep
  {
    min_sweep = 90;
    max_sweep = 90;
    sweep_rate = 10;
  }
  /////////----------------------
  if (val == 'd') //if we get a p Beam Sweep
  {
    j = j - 1;
  }
  /////////----------------------
  if (val == 'f') //if we get a s Stop Sweep
  {
    j = j + 1;
  }
  /////////----------------------
  
}
else {
}
}






///////////////////////////////////////////////

void draw(){
u8g.drawStr( 0, 15, " INITILIZING");    
}

void draw2(){
u8g.drawStr( 0, 15, "   INITILIZING"); 
u8g.drawStr( 0, 35, " ROBOT");    
}

void draw3(){
u8g.drawStr( 0, 15, "   INITILIZING"); 
u8g.drawStr( 0, 35, "      ROBOT"); 
u8g.drawStr( 0, 55, " STAND BY");    
 
}
void draw4(){
u8g.drawStr( 0, 15, "   INITILIZING"); 
u8g.drawStr( 0, 35, "      ROBOT"); 
u8g.drawStr( 0, 55, "     STAND BY");    
 
}
void draw5(){
u8g.drawStr( 0, 15, "CONTROLLER"); 
// u8g.drawStr( 0, 35, "  FOUND"); 
// u8g.drawStr( 0, 55, "ROBOT READY");    
 
}

void draw6(){
u8g.drawStr( 0, 15, "CONTROLLER"); 
u8g.drawStr( 0, 35, "  FOUND"); 
// u8g.drawStr( 0, 55, "ROBOT READY");    
 
}

void draw7(){
u8g.drawStr( 0, 15, "CONTROLLER"); 
u8g.drawStr( 0, 35, "  FOUND"); 
 u8g.drawRFrame(15, 20, 100, 30, 10);
 
u8g.drawStr( 0, 55, "ROBOT READY");    
 
}

///////////////////////////////////////////////////////////////////
void poll_controller() {
ps2x.read_gamepad(false, vibrate); //read controller and set large motor to spin at 'vibrate' speed
//ps2x.Analog(PSAB_BLUE)ps2x.Button(PSB_START)

if (ps2x.Analog(PSAB_GREEN)) { //will be TRUE as long as button is pressed

if (ps2x.NewButtonState()) //will be TRUE if any button changes state (on to off, or off to on)
{
if (ps2x.Button(PSB_L1))
//Serial.println("Tri+L1 pressed");
state = 1;
if (ps2x.Button(PSB_R1))
// Serial.println("Tri+R1 pressed");
state = 2;
if (ps2x.Button(PSB_L2))
// Serial.println("Tri+L2 pressed");
state = 3;
if (ps2x.Button(PSB_R2))
// Serial.println("Tri+R2 pressed");
state = 4;
}
}
if (ps2x.Analog(PSAB_BLUE)) { //will be TRUE as long as button is pressed

if (ps2x.NewButtonState()) //will be TRUE if any button changes state (on to off, or off to on)
{
if (ps2x.Button(PSB_L1))
Serial.println("X+L1 pressed");
state = 5;
if (ps2x.Button(PSB_R1))
Serial.println("X+R1 pressed");
state = 6;
if (ps2x.Button(PSB_L2))
Serial.println("X+L2 pressed");
state = 7;
if (ps2x.Button(PSB_R2))
Serial.println("X+R2 pressed");
state = 8;
}
}
if (ps2x.Analog(PSAB_PINK)) { //will be TRUE as long as button is pressed

if (ps2x.NewButtonState()) //will be TRUE if any button changes state (on to off, or off to on)
{
if (ps2x.Button(PSB_L1))
// Serial.println("Sq+L1 pressed");
state = 9;
if (ps2x.Button(PSB_R1))
//Serial.println("Sq+R1 pressed");
state = 10;
if (ps2x.Button(PSB_L2))
// Serial.println("Sq+L2 pressed");
state = 11;
if (ps2x.Button(PSB_R2))
//Serial.println("Sq+R2 pressed");
state = 12;
}
}
if (ps2x.Analog(PSAB_RED)) { //will be TRUE as long as button is pressed

if (ps2x.NewButtonState()) //will be TRUE if any button changes state (on to off, or off to on)
{
if (ps2x.Button(PSB_L1))
state = 13;
//Serial.println("Cir+L1 pressed");
if (ps2x.Button(PSB_R1))
state = 14;
//Serial.println("Cir+R1 pressed");
if (ps2x.Button(PSB_L2))
state = 15;
//Serial.println("Cir+L2 pressed");
if (ps2x.Button(PSB_R2))
state = 16;
//Serial.println("Cir+R2 pressed");
}
}

}
///////////////////////////////////////////////////////////////
void scanner() {
// Serial.println(state);
// rotates the servo motor from 15 to 165 degrees
for (int i = min_sweep; i <= max_sweep; i++) {
Pan_Servo.write(i);
//IMU_Data();
Tilt_Servo.write(j);
ps2x.read_gamepad(false, vibrate);
poll_controller();
delay(sweep_rate);
buttons();
get_US_range();
Serial.print(i); // Sends the current degree into the Serial Port
Serial.print(","); // Sends addition character right next to the previous value needed later in the Processing IDE for indexing
Serial.print(sonar.ping_result / US_ROUNDTRIP_CM); // Sends the distance value into the Serial Port
Serial.print("."); // Sends addition character right next to the previous value needed later in the Processing IDE for indexing
}
// Repeats the previous lines from 165 to 15 degrees
for (int i = max_sweep; i > min_sweep; i--) {
Pan_Servo.write(i);
//IMU_Data();
Tilt_Servo.write(j);
ps2x.read_gamepad(false, vibrate);
poll_controller();
delay(sweep_rate);
buttons();
get_US_range();
Serial.print(i);
Serial.print(",");
Serial.print(sonar.ping_result / US_ROUNDTRIP_CM);//Ranging data
Serial.print(".");
}
buttons();
ps2x.read_gamepad(false, vibrate);
poll_controller();

}
///////////////////////////////////////////////////////////////////
void buttons() {
//establishContact(); // send a byte to establish contact until receiver responds
if (Serial.available() > 0) { // If data is available to read,
val = Serial.read(); // read it and store it in val
/////////----------------------
if (val == 'r') //if we get a r Fast Sweep
{ sweep_rate = 2;
// R_State = !R_State; //flip the ledState
// digitalWrite(13, R_State);
}
/////////----------------------
if (val == 't') //if we get a t
{ sweep_rate = 7;
//T_State = !T_State; //flip the ledState Quick Sweep
//digitalWrite(13, T_State);
}
/////////----------------------
if (val == 'b') //if we get at b Medium Sweep
{ sweep_rate = 14;
// B_State = !B_State; //flip the ledState
// digitalWrite(13, B_State);
}
/////////----------------------
if (val == 'e') //if we get a e Slow Sweep
{ sweep_rate = 30;
//F_State = !F_State; //flip the ledState
//digitalWrite(13, F_State);
}
/////////----------------------
if (val == 'y') //if we get a y Full Sweep
{
min_sweep = 40;
max_sweep = 165;
// R_State = !R_State; //flip the ledState
// digitalWrite(13, R_State);
}
/////////----------------------
if (val == 'u') //if we get a u Wide Sweep
{
min_sweep = 45;
max_sweep = 140;
//T_State = !T_State; //flip the ledState
//digitalWrite(13, T_State);
}
/////////----------------------
if (val == 'i') //if we get at i Narrow Sweep
{
min_sweep = 60;
max_sweep = 120;
}
/////////----------------------
if (val == 'o') //if we get a o Steer Sweep
{
min_sweep = 75;
max_sweep = 105;
}
/////////----------------------
if (val == 'p') //if we get a p Beam Sweep
{
min_sweep = 84;
max_sweep = 96;
}
/////////----------------------
if (val == 's') //if we get a s Stop Sweep
{
min_sweep = 90;
max_sweep = 90;
sweep_rate = 10;
}
/////////----------------------
if (val == 'd') //if we get a p Beam Sweep
{
j = j - 1;
}
/////////----------------------
if (val == 'f') //if we get a s Stop Sweep
{
j = j + 1;
}
/////////----------------------

}
else {
}
}

///////////////////////////////////////////////

void draw(){
u8g.drawStr( 0, 15, " INITILIZING");
}

void draw2(){
u8g.drawStr( 0, 15, " INITILIZING");
u8g.drawStr( 0, 35, " ROBOT");
}

void draw3(){
u8g.drawStr( 0, 15, " INITILIZING");
u8g.drawStr( 0, 35, " ROBOT");
u8g.drawStr( 0, 55, " STAND BY");

}
void draw4(){
u8g.drawStr( 0, 15, " INITILIZING");
u8g.drawStr( 0, 35, " ROBOT");
u8g.drawStr( 0, 55, " STAND BY");

}
void draw5(){
u8g.drawStr( 0, 15, "CONTROLLER");
// u8g.drawStr( 0, 35, " FOUND");
// u8g.drawStr( 0, 55, "ROBOT READY");

}

void draw6(){
u8g.drawStr( 0, 15, "CONTROLLER");
u8g.drawStr( 0, 35, " FOUND");
// u8g.drawStr( 0, 55, "ROBOT READY");

}

void draw7(){
u8g.drawStr( 0, 15, "CONTROLLER");
u8g.drawStr( 0, 35, " FOUND");
u8g.drawRFrame(15, 20, 100, 30, 10);

u8g.drawStr( 0, 55, "ROBOT READY");

}

You will have to split your for-loops in small pieces.

In a first step, take the for loops out of the scanner function and put it in a function. E.g. call those new functions scanner15_165 and scanner165_15.

In each function, delete for(...) so you only have the body of the for-loop left.

Keep track of a counter (it will replace i of the for loop) using a static variable. E.g. call this counter e.g. sweepCount.

Your scanner15_165 function will now look like

/*
  scan from min_sweep to max_sweep
  Returns:
    true when is sweep is completed, else false
*/
bool scanner15_165()
{
  static int sweepCount = min_sweep;
  
  Pan_Servo.write(sweepCount);
  //IMU_Data();
  Tilt_Servo.write(j);
  ps2x.read_gamepad(false, vibrate);
  poll_controller();
  delay(sweep_rate);
  buttons();
  get_US_range();
  Serial.print(sweepCount); // Sends the current degree into the Serial Port
  Serial.print(","); // Sends addition character right next to the previous value needed later in the Processing IDE for indexing
  Serial.print(sonar.ping_result / US_ROUNDTRIP_CM); // Sends the distance value into the Serial Port
  Serial.print("."); // Sends addition character right next to the previous value needed later in the Processing IDE for indexing
  
  sweepCnt++;
  if (sweepCnt == max_sweep)
  {
    sweepCount = min_sweep;
    return true;
  }
  else
  {
    return false;
  }
}

Now you need to call this numerous times and each time you will do a little step from min_sweep to max_sweep. Once it has reached max_sweep, it will indicate that the operation completed.

Do the same thing for the scanning in the other direction; adjust the count logic.

Next you can implement a simple state machine in the scanner() function; one state to sweep from min to max and one state to sweep from max to min

void scanner() {
  // sweep direction; 0 indicates min to max, 1 indicates max to min
  static byte direction = 0;

  // if min to max
  if (direction == 0)
  {
    // one little step; check to see if all steps have completed
    if (scanner15_165() == true)
    {
      // if complete, change direction
      direction = 1;
    }
  }
  // else max to min
  else
  {
    // one little step, check to see if all steps have completed
    if (scanner165_15() == true)
    {
      // if complete, change direction
      direction = 0;
    }
  }
  
  buttons();
  ps2x.read_gamepad(false, vibrate);
  poll_controller();
}

You can probably get rid of the calls to buttons(), ps2x.read_gamepad() and poll_controller() lines in scanner15_165() and scanner165_15().

I have left the delay in both new functions; if you need a better responsiveness or are a perfectionist, use a millis() based implementation (probably) in scanner and remove the delays from the new functions.

Posted as a guideline.