Push button + MQ2 sensor + 16x2 I2C LCD

Here is your code modified. It will display "My Name" at start up and until the button switch is pressed.

I do not use the old LiquidCrystal_I2C libraries. I like the hc44780 library for LCDs. The hd447680 library is available through the library manager.

I do not like to use delay so I use the blink without delay method of timing with millis().

#include <Wire.h>
#include <hd44780.h>                       // main hd44780 header
#include <hd44780ioClass/hd44780_I2Cexp.h> // i2c expander i/o class header

hd44780_I2Cexp lcd; // declare lcd object: auto locate & auto config expander chip

// LCD geometry
const int LCD_COLS = 16;
const int LCD_ROWS = 2;

const byte buttonPin = 4;  // switch wired to ground and a digital input pin
const byte MQ2pin = A0; // const is preferred over #define

int sensorValue; //variable to store sensor value

void setup()
{
   Serial.begin(115200);
   pinMode(buttonPin, INPUT_PULLUP);  // enable internal pullup
   lcd.begin(LCD_COLS, LCD_ROWS);
   lcd.print("  My Name");
   while (digitalRead(buttonPin) == HIGH); // switch input goes low when pressed
}

void loop()
{
   static unsigned long timer = 0;
   unsigned long interval = 2000;
   if (millis() - timer >= interval)
   {
      timer = millis();

      sensorValue = analogRead(MQ2pin); // read analog input pin 0

      lcd.setCursor(0, 0);
      lcd.print("VALUE:          "); // extra spaces to overwrite old data
      lcd.setCursor(7, 0);
      lcd.print(sensorValue);
      lcd.print("ppm");

      if (sensorValue > 300)
      {
         lcd.setCursor(0, 1);
         lcd.print(" SMOKE DETECTED ");
      }
      else
      {
         lcd.setCursor(0, 1);
         lcd.print("    NO SMOKE    ");  // extra spaces to overwrite old data
      }
   }
}
  

Non-blocking timing using millis() tutorials:
Several things at a time.
Beginner's guide to millis().
Blink without delay().

Push button switch wiring

1 Like