Linux Shell笔记(番外)

写此系列的第一篇博客之前,本人已经把之前项目里面的一个模块用shell脚本语言进行了实现,现在把这其中的源码分享出来。

这个模块就是温度监控程序里面用于在温度文件里面读取温度的一段,之前的那个项目本人是用C语言实现的,可开源的代码只有客户端的代码。现在来分享读取温度模块的另一种实现方式,但是之前的用C语言实现的代码仍然闭源,此代码只算是之前项目的一个小小拓展。

实现的基本思想:从DS18B20上获取温度的基本原理

源码

#!/bin/bash
##File name: ds18b20.sh

TRUE=0
CHECK=`ls /sys/devices/ | grep "w1_bus*"`
NULL=

if [[ $CHECK = $NULL ]] ; then 
	echo "Device ds18b20 does not exit!"
	echo "Fail to get the temperature"
	exit
fi

echo "Please wait..."

#"w1_slave" is a file which records the temperature data 
ds18b20="w1_slave"

#Variable ds18b20_path is the path of "w1_slave"
ds18b20_path="/sys/devices/w1_bus_master1/"


#Different chip has different device_id, but there is a general number on the id_head -- "28"
chip_id=`ls $ds18b20_path | grep "28-"` 

ds18b20_path=${ds18b20_path}${chip_id}"/"${ds18b20}



#Cut the temperature string and convert it to real centigrade temperature
#The structure of w1_slave:
#################################################
#c0 01 4b 46 7f ff 0c 10 2e : crc=2e YES        #
#c0 01 4b 46 7f ff 0c 10 2e t=28000             #
#################################################

#Cut the temperature string
temper_str="t="
temper_str=`grep "t=" $ds18b20_path`
temper_str=${temper_str#*=}

#Convert the temperature string to real centigrade temperature
temper_high=${temper_str:0:2}
temper_low=${temper_str##$temper_high}
temper=${temper_high}"."${temper_low}




#Print the temperature into screen
if [[ $temper = "." ]] ; then
	echo "Fail to get temperature!"
else
	echo "The current temperature is "${temper}" Centigrade."
fi

#end

运行结果

请注意:上述源码一定要在装有DS18B20温度传感器的树莓派上运行,才能得到正常的结果

shallwing@Public_RPi:~ $ bash ds18b20.sh 
Please wait...
The current temperature is 30.250 Centigrade.

在其他Linux主机上运行,结果为

[shallwing@centos ~]$ bash ds18b20.sh 
Device ds18b20 does not exit!
Fail to get the temperature

你可能感兴趣的:(Linux,Shell)