Linux下PHP串口通讯

发布于:2023-07-06 08:59:00

设备连接

将支持485通讯的设备,按照下图接线方式连接到485转USB模块

之后将485转USB模块插到服务器USB接口上,正常设备亮红灯,系统自动识别USB设备

PHP按照dio扩展

扩展地址: https://pecl.php.net/package/dio

此扩展支持windows,需要自行测试

源码安装

下载源码后 https://pecl.php.net/get/dio-0.2.1.tgz 解压

进入解压文件夹按下列步骤执行


[root@localhost dio-0.2.1]# phpize
[root@localhost dio-0.2.1]# ./configure
[root@localhost dio-0.2.1]# make && make install

最后在php.ini中增加

extension=dio.so

pear安装

首先为PHP安装pear

[root@localhost ~]# wget http://pear.php.net/go-pear.phar
[root@localhost ~]# php go-pear.phar 
[root@localhost ~]# pear list dio

之后使用pear安装dio扩展

[root@localhost ~]# pecl install dio
#或者
[root@localhost ~]# pecl install dio channel://pecl.php.net/dio-0.2.1 

查看扩展状态

[root@localhost ~]# php -m|grep dio

完成之后即可使用dio扩展

测试PHP串口通讯

使用如下程序测试

<?php

$fd  =  dio_open('/dev/ttyUSB0',  O_RDWR | O_NOCTTY | O_NONBLOCK);
if (!$fd) {
    exit('串口打开失败');
}
if (dio_fcntl($fd,  F_SETLK, array("type" => F_WRLCK)) == -1) {
    echo  "设备已被锁定";
} else {
    echo  "设备锁定成功";
}
$option = array('baud'  =>  2400,    'bits'  =>  8,    'stop'   =>  1,    'parity'  =>  2);
dio_tcsetattr($fd, $option);

$cmd="\x68\x21\x47\x90\x02\x03\x22\x68\x11\x04\x04\x00\x01\x02\x0B\x16";//读取电能表时间,和校验结果(HEX),https://www.23bei.com/tool/8.html
$c = dio_write($fd, $cmd);
sleep(1);
$res  =  dio_read($fd);
var_dump(showHex($res));//输出结果
dio_close($fd);


function showHex($data)
{
    $hexs = [];
    $das = unpack('C*', $data);
    foreach ($das as $d) {
        $hex = dechex($d);
        $hexs[] = $hex;
    }
    return $hexs;
}


function getSumCheckHex($data)
{
    $sum = 0;
    $das = unpack('C*', $data);
    foreach ($das as $d) {
        $sum += $d;
    }
    $ck = $sum % 256;
    return $ck;
}


阅读 247