TTGO T-Display esp32

Hi guys,
I'm using a TTGO esp-32 to see the stress level with a pulse sensor and gsr sensor. What I want to do is to create a web server which has 2 buttons, one to start the program on the device, one to turn it off. Also I would like on that webserver to also see the stress level and the values that were read. But the most important are the buttons. I tried to write a code for it.

#include <TFT_eSPI.h> // includem biblioteca TFT_eSPI pentru afișajul TFT
#include <WiFi.h>

// Inlocuiti cu SSID-ul si password-ul rețelei Wifi la care va conectati
const char* ssid = "ssis";
const char* password = "password";

// Setare numar port pentru web server
WiFiServer server(80);

// Variabila pentru memorarea cererii HTTP (HTTP request)
String header;
// Variabila pentru memorarea starii curente a LED-ului (on / off)
String stressLevelStare = "off";

// Current time
unsigned long currentTime = millis();
// Previous time
unsigned long previousTime = 0; 
// Define timeout time in milliseconds (example: 2000ms = 2s)
const long timeoutTime = 2000;
char c;

TFT_eSPI tft = TFT_eSPI(); // Initialize TFT object

int sensorPin = 36; // Pinul senzorului de puls
unsigned long lastBeatTime = 0; // Timpul în milisecunde de la ultimul puls
unsigned long thisBeatTime = 0; // Timpul în milisecunde de la pulsul curent
bool beatInProgress = false; // Indicator pentru a verifica dacă pulsul este în progres sau nu
int beatsPerMinute = 0; // Numărul de bătăi pe minut

#define GSR_PIN 32 // Pinul senzorului GSR
#define GSR_SAMPLE_COUNT 100 // Numărul de eșantioane pentru senzorul GSR

float stressLevel = 0; // Variabilă pentru a stoca nivelul de stres

void setup() {
  Serial.begin(9600); // Inițializăm serialul la 9600 de biți pe secundă
    // Conectare la reteaua Wi-Fi cu SSID si password de mai sus
  Serial.print("Connecting to ");
  Serial.println(ssid);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  // Afisare adresa IP locala a placii ESP32 si pornire web server
  // Accesarea web server-ului se va face dintr-un browser tastand
  //    in bara de adrese aceasta adresa IP
  Serial.println("");
  Serial.println("WiFi connected.");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
  server.begin();
  tft.init(); // Inițializăm ecranul TFT
  tft.setRotation(1); // Rotim ecranul TFT cu 90 de grade
  tft.fillScreen(TFT_BLACK); // Umplem ecranul TFT cu culoarea neagră
  tft.setTextSize(2); // Setăm dimensiunea textului pe 2
}

void loop() {
   WiFiClient client = server.available();   // Verificare solicitari de acces (Listen for incoming clients)
  if (client) {                             // Daca s-a conectat un client nou (If a new client connects,)
    currentTime = millis();
    previousTime = currentTime;
    Serial.println("New Client.");          // Afisare mesaj pe Serial Monitor
    String currentLine = "";                // Creare sir pentru receptionarea datelor de la client (cerere HTTP)
    // bucla ce ruleaza atata timp clientul este conectat
    while (client.connected() && currentTime - previousTime <= timeoutTime) {   
      currentTime = millis();

      
      //RECEPTIE CERERE HTTP client
      if (client.available()) {             // Daca exista bytes de citit de la client,
        char c = client.read();             // se citeste un byte, apoi
        Serial.write(c);                    // se trimite la Serial Monitor
        header += c;                        // concatenare byte in sirul cerere HTTP
        if (c == '\n') {                    // Daca byte-ul este un carater newline 
          // if the current line is blank, you got two newline characters in a row.
          // that's the end of the client HTTP request, so send a response:
          if (currentLine.length() == 0) {
            // HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK)
            // and a content-type so the client knows what's coming, then a blank line:
            client.println("HTTP/1.1 200 OK");
            client.println("Content-type:text/html");
            client.println("Connection: close");
            client.println();
                        // functia indexOf cauta in sirul header textul "GET /2/on" care 
            // va fi interpretat ca o comanda de aprindere a LED-ului
            if (header.indexOf("GET /2/on") >= 0) {
               tft.fillScreen(TFT_BLACK);
                measureHeartRate();
                uint32_t gsrValue = 0;
                for (int i = 0; i < GSR_SAMPLE_COUNT; i++) {
                  gsrValue += analogRead(GSR_PIN);
                }
                gsrValue /= GSR_SAMPLE_COUNT;

                float voltage = map(gsrValue, 0, 4095, 0, 3300) / 1000.0;

                if (beatsPerMinute > 0 && voltage > 0) {
                  stressLevel = (((beatsPerMinute - 60) / 90.0) * 90.0 + (3.3-voltage) * 10.0);
                }
                // Afișează BPM, GSR și nivelul de stres pe ecranul TFT
                  tft.setCursor(0, 0);
                  tft.setTextColor(TFT_RED);
                  tft.printf("Stress Level: %.2f", stressLevel);
                  tft.setCursor(0, 30);
                  tft.setTextColor(TFT_WHITE);
                  tft.printf("BPM: %d  ", beatsPerMinute);
                  tft.setCursor(0, 60);
                  tft.setTextColor(TFT_WHITE);
                  tft.printf("GSR: %.3f V", voltage);
                  Serial.println(voltage);
                  
                  delay(100); // Așteptăm 100 de milisecunde
}}}
            else if (header.indexOf("GET /2/off") >= 0) {
                tft.fillScreen(TFT_BLACK);
            } 
                        
            // Display the HTML web page
            client.println("<!DOCTYPE html><html>");
            client.println("<head><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">");
            client.println("<link rel=\"icon\" href=\"data:,\">");
            // CSS to style the on/off buttons 
            // Feel free to change the background-color and font-size attributes to fit your preferences
            client.println("<style>html { font-family: Helvetica; display: inline-block; margin: 0px auto; text-align: center;}");
            client.println(".button { background-color: #4CAF50; border: none; color: white; padding: 16px 40px;");
            client.println("text-decoration: none; font-size: 30px; margin: 2px; cursor: pointer;}");
            client.println(".button2 {background-color: #555555;}</style></head>");
            
            // Web Page Heading
            client.println("<body><h1>ESP32 ----- Web Server</h1>");
            
            // afisare stare curenta a LED-ului, and ON/OFF buttons for GPIO 2  
            client.println("<p>Stare stressLevel - " + stressLevelStare  + "</p>");
            // If the stressLevel is off, it displays the ON button       
            if (stressLevelStare =="off") {
              client.println("<p><a href=\"/2/on\"><button class=\"button\">- ON -</button></a></p>");
            } else {
              client.println("<p><a href=\"/2/off\"><button class=\"button button2\">- OFF -</button></a></p>");
            } 
            client.println("</body></html>");
            
            // The HTTP response ends with another blank line
            client.println();
            // Break out of the while loop
            break;
          } else { // if you got a newline, then clear currentLine
            currentLine = "";
          }
        } else if (c != '\r') {  // if you got anything else but a carriage return character,
          currentLine += c;      // add it to the end of the currentLine
        }
      }
    }
    // Clear the header variable
    header = "";
    // Close the connection
    client.stop();
    Serial.println("Client disconnected.");
    Serial.println("");
  }
void measureHeartRate() {
  int sensorValue = analogRead(sensorPin); // Read the analog value from the pulse sensor

  if (sensorValue > 400 && !beatInProgress) { // Check if the sensor value is above 400 and heartbeat is not in progress
    thisBeatTime = millis(); // Set the current time in milliseconds since the last heartbeat
    beatInProgress = true; // Set the heartbeat in progress indicator to true
  } else if (sensorValue < 400 && beatInProgress) { // Check if the sensor value is below 400 and heartbeat is in progress
    lastBeatTime = thisBeatTime; // Set the time from the last heartbeat
    thisBeatTime = millis(); // Set the current time in milliseconds since the last heartbeat
    beatsPerMinute = 60000 / (thisBeatTime - lastBeatTime); // Calculate the heart rate in beats per minute
    beatInProgress = false; // Set the heartbeat in progress indicator to false
  }
  void measureHeartRate() {
  int sensorValue = analogRead(sensorPin); // Read the analog value from the pulse sensor

  if (sensorValue > 400 && !beatInProgress) { // Check if the sensor value is above 400 and heartbeat is not in progress
    thisBeatTime = millis(); // Set the current time in milliseconds since the last heartbeat
    beatInProgress = true; // Set the heartbeat in progress indicator to true
  } else if (sensorValue < 400 && beatInProgress) { // Check if the sensor value is below 400 and heartbeat is in progress
    lastBeatTime = thisBeatTime; // Set the time from the last heartbeat
    thisBeatTime = millis(); // Set the current time in milliseconds since the last heartbeat
    beatsPerMinute = 60000 / (thisBeatTime - lastBeatTime); // Calculate the heart rate in beats per minute
    beatInProgress = false; // Set the heartbeat in progress indicator to false
  }
}

First of all I have an eroor which says 'measureHeartRate' was not declared in this scope. Also, if I fix that still on the serial monitor, after I put the ssid and password I have no ip adress, so no web server and I have the wifi connection alright. Could anyone help me fix this of maybe another code which shows what I need?
Thank you

I can see that the void measureHeartRate () function has been declared twice. That may create problems.

I've deteled and it's the same error

my initWiFi code for ESP32s, to be cut and pasted into other code:

#include <WiFi.h> // obviously

String hostname = "yourProjectName]";
const char* ssid = "yourNetworkName";             // "yourNetworkName";
const char* password  = "yourNetworkPassword"";  // "yourNetworkPassword";

void initWiFi()
{
  WiFi.mode(WIFI_STA);
  WiFi.setHostname(hostname.c_str());// define hostname

  Serial.print("WiFi Scan start ");
  int n = WiFi.scanNetworks();
  Serial.print("WiFi Scan done ");
  if (n == 0)
  {
    Serial.println("no networks found");
  }
  else
  {
    Serial.print(n);
    Serial.println(" networks found");
    Serial.println("Nr | SSID                             | RSSI | CH | Encryption");
    for (int i = 0; i < n; ++i)
    {
      // Print SSID and RSSI for each network found
      Serial.printf("%2d", i + 1);
      Serial.print(" | ");
      Serial.printf("%-32.32s", WiFi.SSID(i).c_str());
      Serial.print(" | ");
      Serial.printf("%4d", WiFi.RSSI(i));
      Serial.print(" | ");
      Serial.printf("%2d", WiFi.channel(i));
      Serial.print(" | ");
      switch (WiFi.encryptionType(i))
      {
        case WIFI_AUTH_OPEN:
          Serial.print("open");
          break;
        case WIFI_AUTH_WEP:
          Serial.print("WEP");
          break;
        case WIFI_AUTH_WPA_PSK:
          Serial.print("WPA");
          break;
        case WIFI_AUTH_WPA2_PSK:
          Serial.print("WPA2");
          break;
        case WIFI_AUTH_WPA_WPA2_PSK:
          Serial.print("WPA+WPA2");
          break;
        case WIFI_AUTH_WPA2_ENTERPRISE:
          Serial.print("WPA2-EAP");
          break;

        default:
          Serial.print("unknown");
      }
      Serial.println();
      delay(10);
    }
    WiFi.scanDelete();
    Serial.println();
  }

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

  //  WiFi.begin(ssid, password);
  Serial.print("Connecting to "); Serial.print(ssid); Serial.println(":");
  while (!WiFi.begin(ssid, password));
  {
    counter++;
    Serial.print("WiFiv "); Serial.print(counter); Serial.print(" ");
    delay(1000);

    if (counter == 10)
    {
      counter = 0;
      Serial.println();
      Serial.print("WiFi AP "); Serial.print(ssid); Serial.println(" not available ");
      return;
    }
    Serial.println();
  }
}

void WiFiStationGotIP(WiFiEvent_t event, WiFiEventInfo_t info)
{
  Serial.print("WiFiStationGotIP: ");
  Serial.println(IPAddress(info.got_ip.ip_info.ip.addr));
  return;
}

// in void setup()

  initWiFi();
  WiFi.onEvent(WiFiStationGotIP, SYSTEM_EVENT_STA_GOT_IP);
  Serial.println("Delay(30000);"); delay(30000);

this includes diagnostics.

  • a troubleshooting aid that tells you about the performance of the radio side of your wifi connection.
  • it tells you if you got an IP address, so it verifies connection

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