RS485+PHP+串口服务器,用TCP方式实现温度实时监测代码

写这个程序是有原因的,近期天气越来越凉,估计邻居的循环泵又开始作妖了,为了摸清邻居夜间开循环泵的规律,做了这套PHP+RS485温度模块的监测程序,直接把温度传感器放到暖气上判断温度降低的时间段。

所需设备的连接方式:

一个USR-W610的串口服务器和一个温度传感器,连线方式就如下图,两个设备都需要供电。之前的博文中有介绍过这两个设备的情况包括花费的RMB

上图设备中串口服务器是需要设置参数的,通电后可以通过无线WIFI连接,进入管理界面,配置信息如下图:

注意的地方是:波特率、数据位要与温度传器一致,工作模式透明传输,网络模式、协议、端口、IP可不是服务器地址而是W610获取到的IP,这个IP就是PHP代码中发送TCP指令的目标IP。


监测页面截图:

监测页面核心代码:

<script src="../jquery.min.js"></script>
<script>
function tcp_control(zhiling,type){
$("#status").html('正在读取数据,请稍后...');
var ajaxform=$.post("jilu-ajax.php",{zhiling:zhiling,type:type},function(result){
var give_strs= new Array(); //定义一数组
give_strs=result.split("|"); //字符分割
if (give_strs[0]=="ok"){
if (zhiling=='wendu'){
$("#shidu").html(give_strs[1]);
$("#wendu").html(give_strs[2]);
$("#status").html('读取温、湿度,成功,返回值:'+give_strs[3]+'');
}if (zhiling=='light'){
$("#status").html('执行成功,返回值:'+give_strs[1]+'');
}
}else{
$("#status").html('Error-'+result+'')
}
});
}
</script>
实时温度
温度:- 湿度:-
---
<script> $(document).ready(function(){ tcp_control('wendu',''); setInterval(function(){tcp_control('wendu','')},10000); }); </script>

RS485协议用PHP+AJAX发送指令和接收数据的核心代码:

3, "usec"=>0 ) );//接收超时
socket_set_option($socket,SOL_SOCKET,SO_SNDTIMEO,array("sec"=>1, "usec"=>0 ) );//发送超时
if (socket_connect($socket, $host, $port)) { //连接
socket_write($socket, $sendStr); // 逐组数据发送
$receiveStr = '';
$receiveStr = socket_read($socket, 1024, PHP_BINARY_READ); // 采用2进制方式接收数据
$receiveStrHex = bin2hex($receiveStr); // 将2进制数据转换成16进制
return $receiveStrHex;//返回的值
}
socket_close($socket);// 关闭Socket
}
if ($zhiling=='wendu'){
//要发送的指令(温度传感器发出的查询指令:01 03 00 00 00 02 C4 0B)
$sendStr = "\x01\x03\x00\x00\x00\x02\xC4\x0B"; // 16进制数据
$get_value=tcp($sendStr);
$indate=date("Y-m-d H:i:s");
$shidu=substr($get_value,6,4);//获取湿度信息
$shidu_str=number_format((hexdec($shidu)/10),2);
//echo "当前湿度:".$shidu.",转为十进制:".hexdec($shidu).",显示为:".number_format((hexdec($shidu)/10),2)."%";
$wendu=substr($get_value,10,4);//获取温度信息
$wendu_str=number_format((hexdec($wendu)/10),2);
//echo "当前温度:".$shidu.",转为十进制:".hexdec($shidu).",显示为:".number_format((hexdec($shidu)/10),2)."℃";
echo "ok|".$shidu_str."|".$wendu_str."|".$get_value.",最后返回时间:".$indate;
$sql2 = "insert into wendu (indate,wendu,shidu) values ('" . $indate . "','" . $wendu_str . "','" . $shidu_str . "') ";
$mysqli->query($sql2);
}
?>

以上放的都是主要的核心PHP代码,里面还有一个利用highchart做的统计图,这个代码就不放了,自由发挥吧。