• 博客园logo
  • 会员
  • 周边
  • 新闻
  • 博问
  • 闪存
  • 众包
  • 赞助商
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
MKT-porter
博客园    首页    新随笔    联系   管理    订阅  订阅
树莓派mpu6050网页画图echart

 static  echarts.min.js

 

 

import time
import threading
import os
from flask import Flask, jsonify, render_template
import smbus2

# ------------------ MPU6050 Configuration ------------------ #
MPU6050_ADDR = 0x68
ACCEL_XOUT_H = 0x3B
PWR_MGMT_1 = 0x6B
bus = smbus2.SMBus(1)
bus.write_byte_data(MPU6050_ADDR, PWR_MGMT_1, 0)

log_file = "accel_data.txt"

def read_word(reg):
    high = bus.read_byte_data(MPU6050_ADDR, reg)
    low = bus.read_byte_data(MPU6050_ADDR, reg+1)
    value = (high << 8) + low
    if value >= 0x8000:
        value = -((65535 - value) + 1)
    return value

def read_accel():
    ax = read_word(ACCEL_XOUT_H) / 16384.0
    ay = read_word(ACCEL_XOUT_H+2) / 16384.0
    az = read_word(ACCEL_XOUT_H+4) / 16384.0
    return ax, ay, az

def log_data():
    while True:
        ax, ay, az = read_accel()
        line = f"{time.time():.2f},{ax:.3f},{ay:.3f},{az:.3f}\n"
        with open(log_file, "a") as f:
            f.write(line)
        time.sleep(0.1)

# ------------------ Flask Web Server ------------------ #
app = Flask(__name__)

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

@app.route("/data")
def get_data():
    if not os.path.exists(log_file):
        return jsonify({"time": [], "x": [], "y": [], "z": []})

    time_list, x_list, y_list, z_list = [], [], [], []
    with open(log_file, "r") as f:
        lines = f.readlines()[-100:]
        for line in lines:
            t, x, y, z = line.strip().split(",")
            time_list.append(float(t))
            x_list.append(float(x))
            y_list.append(float(y))
            z_list.append(float(z))

    return jsonify({"time": time_list, "x": x_list, "y": y_list, "z": z_list})

# ------------------ Main Entry ------------------ #
if __name__ == "__main__":
    threading.Thread(target=log_data, daemon=True).start()
    app.run(host="0.0.0.0", port=5000)

  templates   index.html

 

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>MPU6050 Acceleration Chart</title>
    <script src="/static/echarts.min.js"></script>
</head>
<body>
    <h2>Real-time 3-Axis Acceleration Chart</h2>
    <button onclick="downloadTXT()">Download TXT</button>
    <div id="chart" style="width:100%;height:500px;"></div>

    <script>
    var chart = echarts.init(document.getElementById('chart'));

    function fetchData() {
        fetch("/data").then(res => res.json()).then(data => {
            chart.setOption({
                tooltip: { trigger: 'axis' },
                legend: { data: ['X', 'Y', 'Z'] },
                toolbox: {
                    feature: {
                        saveAsImage: { title: 'Save as Image' }
                    },
                    right: '10%',
                    top: 'top'
                },
                xAxis: {
                    type: 'category',
                    data: data.time.map(t => new Date(t * 1000).toLocaleTimeString())
                },
                yAxis: { type: 'value' },
                series: [
                    { name: 'X', type: 'line', data: data.x },
                    { name: 'Y', type: 'line', data: data.y },
                    { name: 'Z', type: 'line', data: data.z }
                ]
            });
        });
    }

    function downloadTXT() {
        fetch("/data").then(res => res.json()).then(data => {
            let content = "Timestamp,X,Y,Z\n";
            for (let i = 0; i < data.time.length; i++) {
                content += `${data.time[i]},${data.x[i]},${data.y[i]},${data.z[i]}\n`;
            }
            let blob = new Blob([content], { type: "text/plain" });
            let link = document.createElement("a");
            link.href = URL.createObjectURL(blob);
            link.download = "accel_data.txt";
            link.click();
        });
    }

    fetchData();
    setInterval(fetchData, 1000);
    </script>
</body>
</html>

  

 

posted on 2025-05-11 01:35  MKT-porter  阅读(25)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2026
浙公网安备 33010602011771号 浙ICP备2021040463号-3