Push button to on and off system

hi

I am trying to design a system consist of a DHT sensor controlling a fan and a heater

down the code am using it and it works correctly

#include "DHT.h"


#define DHTPIN 8
#define DHTTYPE DHT11

DHT dht(DHTPIN, DHTTYPE); 

int FAN=7;
int LAMP=6;

void setup()
{
  
    Serial.begin(9600);
    pinMode(FAN, OUTPUT);
    pinMode(LAMP, OUTPUT);
}

void loop()
{
 float h = dht.readHumidity();
 Serial.println(h);
 float t = dht.readTemperature();
 Serial.println(t);
  
  if(h>=75)
  {
    digitalWrite(FAN,HIGH);
  }
  else
  {
    digitalWrite(FAN,LOW);
  }
  
  delay(500);
  if(t>=50)
  {
    digitalWrite(LAMP,LOW);
  }
  else
  {
    digitalWrite(LAMP,HIGH);
  }
  
  delay(500);
}

am in need of help to add a Toggle switch code to start and close the system
I have tried many codes I also tried much Merging most of the normal codes to my code all of them doesn't work
please help me

You could try something like this.

// Hook up a toggle switch between digital pin 8 and ground. 

#define SWITCH  8

void setup()
{
  Serial.begin(115200);
  pinMode(SWITCH, INPUT_PULLUP);
}

void loop()
{
  if (digitalRead(SWITCH))                // 1 if the switch is off, 0 if it is on
  {
    Serial.println(digitalRead(SWITCH));
    // Do what you need when the switch is off
  }
  else
  {
    Serial.println("Switch on");
    // Do what you need when the switch is on
  }
}

thanx a lot of replays

I tried it and its work correctly

but what if I want to use a single push button to start and off the system?

Just set a variable named 'power' to true or false. When the button is pushed, change the state from true to false or vice versa. In this case you have to detect the switch being depressed and wait for it to be released or you will cause multiple state changes.

can you give an explained example as you wrote to me above?

Something like this.

// Hook up a push button switch between digital pin 8 and ground.

#define SWITCH  8
boolean power = false;

void setup()
{
  Serial.begin(115200);
  pinMode(SWITCH, INPUT_PULLUP);
}

void loop()
{
  CheckSwitch();
  if (power)
  {
    // Do what you need when the power is on
  }
  else
  {
    // Do what you need when the power is off
  }
}

void CheckSwitch()
{
  if (digitalRead(SWITCH))            // 1 if the switch is not pressed      
    return;
  else                                // the switch is pressed
  {
    power = !power;                   // change the power state
    while (!digitalRead(SWITCH));     // wait here until the switch is released
  }
}