{"id":21392313,"url":"https://github.com/andy-y-li/pi-temp","last_synced_at":"2026-04-16T11:31:14.947Z","repository":{"id":86473938,"uuid":"257813109","full_name":"andy-y-li/pi-temp","owner":"andy-y-li","description":"Get the temperature of Raspberry Pi and control the fan, write the process data to sqlite database.","archived":false,"fork":false,"pushed_at":"2020-04-22T06:42:56.000Z","size":220,"stargazers_count":2,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"master","last_synced_at":"2025-03-16T13:42:14.427Z","etag":null,"topics":["auto-start","db","fan","pi3","raspiberry","sqlite","temperature"],"latest_commit_sha":null,"homepage":null,"language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"gpl-3.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/andy-y-li.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2020-04-22T06:34:12.000Z","updated_at":"2020-04-28T06:53:51.000Z","dependencies_parsed_at":null,"dependency_job_id":"bb88429c-e74f-413a-a477-9aa66f71b794","html_url":"https://github.com/andy-y-li/pi-temp","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/andy-y-li/pi-temp","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/andy-y-li%2Fpi-temp","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/andy-y-li%2Fpi-temp/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/andy-y-li%2Fpi-temp/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/andy-y-li%2Fpi-temp/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/andy-y-li","download_url":"https://codeload.github.com/andy-y-li/pi-temp/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/andy-y-li%2Fpi-temp/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":31883695,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-04-16T09:23:21.276Z","status":"ssl_error","status_checked_at":"2026-04-16T09:23:15.028Z","response_time":69,"last_error":"SSL_connect returned=1 errno=0 peeraddr=140.82.121.6:443 state=error: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["auto-start","db","fan","pi3","raspiberry","sqlite","temperature"],"created_at":"2024-11-22T13:39:56.041Z","updated_at":"2026-04-16T11:31:14.931Z","avatar_url":"https://github.com/andy-y-li.png","language":"Python","funding_links":[],"categories":[],"sub_categories":[],"readme":"## RPi temperature \u0026 fan control\n\n   本文使用python实现对树莓派的温度实时检测和风扇的控制，并把相关的温度，风扇控制信息保存到sqlite数据库中。\n\n1. ***创建数据库和空表***\n\n​    a.  在文件 ***create-table-only.sql***定义一个表temps, 共4个字段: 其中 ***name***,  ***tdatetime***有默认值, \n\n​         ***temperature*** 记录当前温度, ***fan*** 记录风扇的使用率；\n\n```\nPRAGMA foreign_keys=OFF;\nBEGIN TRANSACTION;\nCREATE TABLE temps(\n    name DEFAULT 'RPi.CPU',\n    tdatetime DATETIME DEFAULT (datetime('now', 'localtime')),\n    temperature NUMERIC NOT NULL,\n    fan NUMERIC NOT NULL\n);\nCOMMIT;\n```\n\n\n\n   b.  写一个shell脚本 ***create-table-only.sh***, 用于创建一个空表：\n\n```\n#!/bin/sh\nDBNAME=\"cpu.db\"\nrm -f $DBNAME\necho 开始插入数据\nsqlite3 $DBNAME \u003c create-table-only.sql\necho 插入完成\n```\n\n​     给shell文件新增可执行权限, 运行后生成数据库文件  ***cpu.db***：\n\n```\nchmod +x create-table-only.sh\n./create-table-only.sh\n```\n\n\n\n2. ***用python读取温度,控制风扇，并保存到数据库***\n\n​      创建文件 ***db-insert-temp.py***\n\n```\n#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport time\nimport sqlite3\nimport RPi.GPIO as GPIO\n\nT_HIGH = 50\nT_LOW = 45\nfan_pin = 36\n\ndef get_cpu_temp():\n    # 打开文件\n    file = open(\"/sys/class/thermal/thermal_zone0/temp\")\n    # 读取结果，并转换为浮点数\n    temp = float(file.read()) / 1000\n    # 关闭文件\n    file.close()\n    return temp\ndef insert_cpu_temp(temp, open_fan_num, close_fan_num):\n    # 连接数据库\n    conn=sqlite3.connect('cpu.db')\n    curs=conn.cursor()\n\n    f = float(open_fan_num)/float((open_fan_num + close_fan_num)) * 100\n    fans = \"%.1f%%\" % (f)\n    # 插入数据库\n    strtemp = \"%.1f\" % (temp);\n    curs.execute(\"INSERT INTO temps(temperature, fan) VALUES((?),(?))\", (strtemp, fans))\n    conn.commit()\n\n    # 关闭数据库\n    conn.close()\n\ndef init_gpio():\n    GPIO.setwarnings(False)\n    GPIO.setmode(GPIO.BOARD)\n    GPIO.setup(fan_pin, GPIO.OUT)\n    # Close Fan\n    GPIO.output(fan_pin, GPIO.LOW)\n\ndef process_fan(temp):\n    if  temp \u003e T_HIGH:\n        GPIO.output(fan_pin, GPIO.HIGH)\n        return 1\n    elif temp \u003c T_LOW:\n        GPIO.output(fan_pin, GPIO.LOW)\n        return 2\n    return 0\n\ndef main():\n    init_gpio()\n    n_loop = 0\n    case_open_fan_num = 0\n    case_close_fan_num = 0\n\n    fan_is_on = False\n\n    temp = get_cpu_temp()\n    insert_cpu_temp(temp, 0, 1)\n\n    temp_sum = 0.0\n    while True:\n        temp = get_cpu_temp()\n        temp_sum += temp;\n        time.sleep(5)\n\n        ret = process_fan(temp)\n        if ret == 1:\n            case_open_fan_num += 1;\n            fan_is_on = True\n        elif ret == 2:\n            case_close_fan_num += 1;\n            fan_is_on = False\n\n        else:\n            if fan_is_on == True:\n                case_open_fan_num += 1\n            else:\n                case_close_fan_num += 1\n\n        n_loop += 1\n        if n_loop \u003e= 60:\n            temp = temp_sum / n_loop;\n            insert_cpu_temp(temp, case_open_fan_num, case_close_fan_num)\n            n_loop = 0\n            temp_sum = 0.0\n            case_open_fan_num = 0\n            case_close_fan_num = 0\n\n\nif __name__ == '__main__':\n    main()\n```\n\n***简要说明***\n\na. 从文件 ***/sys/class/thermal/thermal_zone0/temp*** 读取树莓派的当前温度，\n\n​    也可以用命令 ***/opt/vc/bin/vcgencmd measure_temp***得到树莓派的温度；\n\nb. 风扇控制, 树莓派的GPIO分布如下:\n\n![rpi](raspi.png)\n\n 风扇的控制电路如下：\n\n![fan](fan_sch.png)\n\n   ***说明:*** 按BOARD引脚编码, +5V为4脚，GND接到6脚，用36脚控制NPN开关：\n\n```\nfan_pin = 36\ndef init_gpio():\n    GPIO.setwarnings(False)\n    GPIO.setmode(GPIO.BOARD)\n    GPIO.setup(fan_pin, GPIO.OUT)\n    # Close Fan\n    GPIO.output(fan_pin, GPIO.LOW)\n```\n\n在这里，温度超过50度时打开风扇，小于45度时关闭风扇：\n\n```\nT_HIGH = 50\nT_LOW = 45\ndef process_fan(temp):\n    if  temp \u003e T_HIGH:\n        GPIO.output(fan_pin, GPIO.HIGH)\n        return 1\n    elif temp \u003c T_LOW:\n        GPIO.output(fan_pin, GPIO.LOW)\n        return 2\n    return 0\n```\n\n\n\n​    C. 在程序中，加入了温度和风扇使用率的统计，并写数据库：\n\n```\n.\n.\n.\n    temp_sum = 0.0\n    while True:\n        temp = get_cpu_temp()\n        temp_sum += temp;\n        time.sleep(5)\n\n        ret = process_fan(temp)\n        if ret == 1:\n            case_open_fan_num += 1;\n            fan_is_on = True\n        elif ret == 2:\n            case_close_fan_num += 1;\n            fan_is_on = False\n\n        else:\n            if fan_is_on == True:\n                case_open_fan_num += 1\n            else:\n                case_close_fan_num += 1\n\n        n_loop += 1\n        if n_loop \u003e= 60:\n            temp = temp_sum / n_loop;\n            insert_cpu_temp(temp, case_open_fan_num, case_close_fan_num)\n            n_loop = 0\n            temp_sum = 0.0\n            case_open_fan_num = 0\n            case_close_fan_num = 0\n            \n```\n\n\n\n运行时查看数据结果：\n\n```\nsqlite3 cpu.db\n再输入 SELECT * FROM temps;\n2020-04-22T10:03:14Z,47.4,63.3%\n2020-04-22T10:08:15Z,48.1,35.0%\n2020-04-22T10:13:15Z,46.2,43.3%\n2020-04-22T10:18:15Z,47  ,71.7%\n2020-04-22T10:23:16Z,47.9,36.7%\n```\n\n3. ***设置开机启动***\n\na. 启动脚本 ***auto-start.sh***\n\n```\n#!/bin/bash\ncd /home/pi/work/py/temp\npython db-insert-temp.py \u0026\n```\n\n用shell脚本来启动python文件, 注意要为auto-start.sh 增加可执行权限：\n\n```\nchmod +x auto-start.sh \n```\n\nb. 设置启动项, 在/etc/init.d 下编辑文件temp-app\n\n```\nsudo vim /etc/init.d/temp-app \n```\n\n内容如下：\n\n```\n#!/bin/sh\n#/etc/init.d/init-app\n \n### BEGIN INIT INFO\n# Provides:          get-ip-address\n# Required-Start:    $remote_fs $syslog\n# Required-Stop:     $remote_fs $syslog\n# Default-Start:     2 3 4 5\n# Default-Stop:      0 1 6\n# Short-Description: init-app\n# Description: This service is used to start init shell\n### END INIT INFO\n \ncase \"$1\" in\n    start)\n        echo \"Starting temp service\"\n        su pi -c \"exec /home/pi/work/py/temp/auto-start.sh\"\n         ;;\n    stop)\n        echo \"Stop\"\n        ;;\n \n    *)\n        echo \"Usage: service temp-app start|stop\"\n        exit 1\n        ;;\nesac\nexit 0\n```\n\n保存后，设置开机启动：\n\n```\nsudo update-rc.d temp-app defaults\n```\n\n重启树莓派就可以自动启动程序了, 也可以先手动启动:\n\n```\nsudo service temp-app start\n```\n\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fandy-y-li%2Fpi-temp","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fandy-y-li%2Fpi-temp","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fandy-y-li%2Fpi-temp/lists"}