如何利用树莓派 乐联网实现温度网络监控
如何利用树莓派 乐联网实现温度网络监控
树莓派脚本编写
1、准备树莓派,还有相对应的IDE程序,一并下载安装。然后安装乐联网模块
2、准备温度传感器,温度传感器建议负温度系数。然后把电阻焊好了,接线稍好看些。
3、制作并连接电路,如图所示,只要把温度传感器的正负两极练到面包板上,然后就可以连上树莓派的输入端,加上VCC电源正极线即可完成
4、这个过程中需要杜邦线三根(双头母),然后按照如图所示的焊接电路,注意三极管的三更管线不要弄错,后文会讲解如何便捷辨别三更管教和他们的作用的。
5、在IDE中穿件文件,写入下面的优化代码:#!/usr/bin/env pythonimport osimport time#show raspberry temperature,CPU,memorydef getCPUtemp(): temp = os.popen('vcgencmd measure_temp').readline() tempfloat = float(temp.replace('temp=','').replace('\'C\n','')) print 'CPU Temperature is now %.1f Centigrade' %tempfloat if tempfloat > 60: print 'CPU Temperature is too high, pls cool it down' def getCPUusage():
6、#calculate CPU with two short time, time2 - time1time1 = os.popen('cat /proc/stat').readline().split()[1:5]time.sleep(0.2)time2 = os.popen('cat /proc/stat').readline().split()[1:5]deltaUsed = int(time2[0])-int(time1[0])+int(time2[2])-int(time1[2])deltaTotal = deltaUsed + int(time2[3])-int(time1[3])cpuUsage = float(deltaUsed)/float(deltaTotal)*100print 'CPU Usage is now %.1f' %cpuUsage +'%'def getRAM():RAM = os.popen('free').read().split()[7:10]RAM0 = float(RAM[0])/1024
7、print 'RAM Total is %.1f MB' %RAM0RAM1 = float(RAM[1])/1024percent = RAM1/RAM0*100print 'RAM Used is %.1f MB, %.2f' %(RAM1,percent) +'%'RAM2 = float(RAM[2])/1024print 'RAM Free is %.1f MB' %RAM2def getDisk():#get Disk information,DISK[8],[9],[10],[11]:Size, Used. free, Used %DISK = os.popen('df -h /').read().split()[8:12]print 'Disk total space is %s ' %DISK[0]print 'Disk Used space is %s ' %DISK[1] +'and is %s' %DISK[3]print 'Disk Free space is %s ' %DISK[2]while True:print '\n-------------SysInfo-----------------\n'getCPUtemp()getCPUusage()getRAM()getDisk()print '\n-------------------------------------\n'time.sleep(5)
8、烧录代码,在IDE中首先编译,然后下载即可,过一会就可以看到板上有指示灯亮起,说明烧录成功。我们然后可以进入联网模块的编写操作了!
控制脚本
1、树莓派的15号引脚连接到了三极管的基极(引脚编号可参看这里),当温度过高时,GPIO引脚输出低电平,可以开启风扇。
2、新建一个新的Python代码修改内容如下:import commands,timeFAN_GPIO = 15commands.getoutput('sudo gpio mode '+str(FAN_GPIO)+' OUTPUT')while True: tmpFile = open( '/sys/class/thermal/thermal_zone0/temp' )cpu_temp_raw = tmpFile.read()tmpFile.close()cpu_temp = round(float(cpu_temp_raw)/1000, 1)print cpu_tempif cpu_temp >= 50.0 :commands.getoutput('sudo gpio write '+str(FAN_GPIO)+' 0')if cpu_temp <= 45.0 :commands.getoutput('sudo gpio write '+str(FAN_GPIO)+' 1') time.sleep(10)
3、保存为 cooperate.py 后,然后就可以运行程序了。
4、(提示一下)执行sudo python命令来运行程序。这个程序的作用是用过乐联网模块来进行网络信息的发送。
5、如果你还需要编写安卓APP来进入关联的操作的话,可以使用okhttp的封装框架来知行。方式也是很简单的,只要获取resquert然后传入OKHTTPclient实例就可以了,newcall后进行execute操作就可以获取温度信息了。
6、当然,也可以使用MockWebServer封装好的模块。
三极管封装
1、焊接电路的时候需要用到三极管,而这个元件的三个管脚分别为发射极、基极和集电极
2、管线图见下面
上传代码,最后测试。
1、上传代码到云端就完成了,最终完成后,可以配置外接电源即可。
2、我们只需要在手机客户端查看温度就可以了。连接你的乐联网的ip本地地址,端口见文档信息,温度就会回传回来了。