Starting code with Push Button

Does anyone know how to start my code up with the push of a push button? I tried coding in an if statement however regardless of where I put my if statement the code automatically starts running

Heres my code:

/*Heart pulse sensor with Arduino
 * https://srituhobby.com
 */
 
#include <SPI.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>

Adafruit_SSD1306 srituhobby = Adafruit_SSD1306(128, 64, &Wire);

#define sensor A0
#define Highpulse 540

const int startButton = 3;
const int endButton = 4; 
int sX = 0;
int sY = 60;
int x = 0;
int Svalue;
int value;
long Stime = 0;
long Ltime = 0;
int count = 0;
int Bpm = 0;

void setup(){
  Serial.begin(9600);
  srituhobby.begin(SSD1306_SWITCHCAPVCC, 0x3C);// Address 0x3C for 128x32
  delay(1000);
  srituhobby.clearDisplay();
  
}

void loop() {
  Svalue = analogRead(sensor);
  Serial.println(Svalue);
  value = map(Svalue, 0, 1024, 0, 45);

  int y = 60 - value;

  if (x > 128) {
    x = 0;
    sX = 0;
    srituhobby.clearDisplay();
  }

  srituhobby.drawLine(sX, sY, x, y, WHITE);
  sX = x;
  sY = y;
  x ++;

  BPM();

  srituhobby.setCursor(0, 0);
  srituhobby.setTextSize(2);
  srituhobby.setTextColor(SSD1306_WHITE);
  srituhobby.print("BPM :");
  srituhobby.display();
  }


void BPM() {
  if (Svalue > Highpulse) {
    Stime = millis() - Ltime;
    count++;
    if (Stime / 1000 >= 60) {
      Ltime = millis();
      Serial.println(count);
      srituhobby.setCursor(60, 0);
      srituhobby.setTextSize(2);
      srituhobby.setTextColor(SSD1306_WHITE);
      srituhobby.print(count);
      srituhobby.print("   ");
      srituhobby.display();
      count = 0;
    }
  }
}

void setup() {
  Serial.begin(9600);

  // configure startButton pin
  pinMode(startButton, INPUT_PULLUP); // wired: pin 3 >> startButton >> ground

  // while startButton is NOT pressed (HIGH), stay here...
  while (digitalRead(startButton));
  // startButton was pressed (LOW), so continue...

  srituhobby.begin(SSD1306_SWITCHCAPVCC, 0x3C);// Address 0x3C for 128x32
  delay(1000);
  srituhobby.clearDisplay();
}

void loop() {
    // et c.
}
1 Like

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.