Need Help with overriding a switch state with an ultrasonic sensor

So I want to make it so that whenever the sensor reads 50 or bellow the lcd changes into Ground effect and autonomous mode engaged.
moreover i also have to switch states where i can change from manual mode and autonomous mode this is so far working but if anyone could help refining it that would be great thank you.
this is my code

#include <LiquidCrystal.h>

//ultrasonic sensor
int trig = 2;
int echo = 3;

long duration;
int distance; 

//lcd screen
LiquidCrystal lcd(7, 8, 9, 10, 11, 12);
int xp=0;

//button  
const int switchPin = 4;   
static int hits = 0;
int switchState = 0;
int prevSwitchState = 0;


void setup() {

 //ultrasonic sensor
 pinMode(trig, OUTPUT);
 pinMode(echo, INPUT);

 
 //lcd screen
 lcd.begin(16, 2);
 
 pinMode(switchPin, INPUT);
 Serial.begin(9600);
 lcd.clear();
 lcd.setCursor(3, 0);
 lcd.print("AUTONOMOUS");
 lcd.setCursor(6, 1);
 lcd.print("MODE");
}

void loop() {

 //ultrasonic sensor
digitalWrite(trig, LOW);
delayMicroseconds(2);

digitalWrite(trig, HIGH);
delayMicroseconds(10);
digitalWrite(trig, LOW);

duration = pulseIn(echo, HIGH);
distance = duration*0.034/2;

Serial.print("Distance:");
Serial.println(distance);


 //button 
switchState = digitalRead(switchPin);
  Serial.print("switchState:");Serial.println(switchState);
 if (switchState != prevSwitchState) {
   if (switchState == HIGH) {
         hits = hits + 1;
         delay(10);
   }
 }
 
 
 Serial.print("hits:");Serial.println(hits);
 if(hits==1)
 {
   Serial.println("MANUAL MODE");
   lcd.clear();
     lcd.setCursor(5, 0);
     lcd.print("MANUAL");
     lcd.setCursor(6, 1);
     lcd.print("MODE");
 }else
 if(hits==2)
 {
  Serial.println("AUTONOMOUS MODE");
   lcd.clear();
     lcd.setCursor(3, 0);
     lcd.print("AUTONOMOUS");
     lcd.setCursor(6, 1);
     lcd.print("MODE");
 }else
  if (hits>=2)
 {
    hits = 0;
    Serial.println("couter is reset:");
 }else
  if (distance<50)
  {
   Serial.println("OVERIDE");
   lcd.clear();
   lcd.setCursor(1, 0);
   lcd.print("GROUND  EFFECT");
   lcd.setCursor(xp, 1);
   lcd.print("AUTONOMOUS MODE ENGAGED");
   xp=(xp-1)%16;
   
  }
 Serial.println(".................");  
  
delay(1100);
}
[code][code][code]

TASK_2.ino (1.86 KB)

Welcome to the forums. Please read the post at the beginning of the forum about how to properly post your code using code tags. It will help people help you.

Your code never assigns a value to 'prevSwitchState' so your switch detection algorithm is flawed.
Put that line right before you print out the number of hits.

PedroSantos99:
im sorry for the improper post im quite new to all of this. but how could i assign a "prevSwitchState"?

Just like you would assign a value to any other variable