[Python] ESP32 with Flask server to display data in web

Discussão em 'Python' iniciado por Stack, Julho 7, 2025.

  1. Stack

    Stack Membro Participativo

    I'm attempting to send data from an ESP32 to a Flask application on my PC for real-time visualization.

    I've followed tutorials and reviewed the codes, yet I'm still encountering a 'connection refused' error on the ESP32. I've double-checked IP addresses and ports, and I'm confident they match. Any insights into why this issue might be occurring?

    app.py code

    from flask import Flask, render_template, request, jsonify
    import json

    app = Flask(__name__, template_folder='template')

    # Almacena los datos recibidos del ESP32
    data = {'gasto': [], 'presion': [], 'vibracion': []}


    @app.route('/')
    def index():
    return render_template('index.html')


    @app.route('/data', methods=['POST'])
    def receive_data():
    try:
    content = request.get_json()

    gasto = content['gasto']
    presion = content['presion']
    vibracion = content['vibracion']

    data['gasto'].append(gasto)
    data['presion'].append(presion)
    data['vibracion'].append(vibracion)

    print(f"Received data: gasto={gasto}, presion={presion}, vibracion={vibracion}")
    return jsonify({'success': True})
    except Exception as e:
    print(f"Error receiving data: {str(e)}")
    return jsonify({'success': False, 'error': str(e)})


    @app.route('/get_data')
    def get_data():
    return jsonify(data)


    if __name__ == '__main__':
    app.run(debug=True)



    esp32 code

    #include <WiFi.h>
    #include <HTTPClient.h>
    #include <ArduinoJson.h>

    const char* ssid = "ASUS_F4"; // Nombre de tu red Wi-Fi
    const char* password = "banana_6424"; // Contraseña de tu red Wi-Fi
    const char* serverAddress = "http://192.168.50.177:5000/data"; // Cambia la dirección IP con la de tu PC

    void setup() {
    Serial.begin(115200);
    WiFi.begin(ssid, password);

    while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.println("Connecting to WiFi...");
    }

    Serial.println("Connected to WiFi");
    }

    void loop() {
    float gasto = 123.45; // Valor simulado de gasto
    float presion = 67.89; // Valor simulado de presión
    float vibracion = 0.12; // Valor simulado de vibración

    // Crea un objeto JSON
    DynamicJsonDocument jsonDoc(200);
    jsonDoc["gasto"] = gasto;
    jsonDoc["presion"] = presion;
    jsonDoc["vibracion"] = vibracion;

    // Serializa el JSON en una cadena
    String payload;
    serializeJson(jsonDoc, payload);

    // Crea una instancia de HTTPClient
    HTTPClient http;
    Serial.println("Server Address: " + String(serverAddress));
    // Envía la solicitud POST al servidor
    http.begin(serverAddress);
    http.addHeader("Content-Type", "application/json");
    int httpResponseCode = http.POST(payload);

    if (httpResponseCode > 0) {
    Serial.printf("HTTP Response code: %d\n", httpResponseCode);
    String response = http.getString();
    Serial.println(response);
    } else {
    Serial.printf("HTTP Request failed: %s\n", http.errorToString(httpResponseCode).c_str());
    }

    http.end();

    delay(5000); // Espera 5 segundos antes de enviar el siguiente dato
    }



    Monitoring a system and display data on a website

    Continue reading...

Compartilhe esta Página