CentOS Linux下使用PHP实现串口通信(serial)

方法一:在Linux上安装minicom串口调试助手,将串口内容打印到文件,再到文件里面去取

yum install minicom -y

minicom -b 9600 -D /dev/ttyS0 -H -w -C /tmp/serial0 > /dev/null

另外一个窗口执行显示即可

tail -f /tmp/serial0

方法二:使用php_dio函数直接读写串口内容(支持windows)

安装PHP运行环境,到官网下载dio安装包并进行编译

下载地址  ​​​​​​http://pecl.php.net/package/dio

使用root用户登录Linux ,执行如下指令

​
tar -zxvf dio-0.2.0.tgz

cd dio-0.2.0

phpize

./configure

make

make install


​

​​​​​​在php.ini中加入extension=dio

便可以使用PHP脚本进行串口通信啦

脚本下载地址:

<?php
$fd  =  dio_open ( '/dev/ttyS0' ,  O_RDWR  |  O_NOCTTY  |  O_NONBLOCK );

//dio_fcntl ( $fd ,  F_SETFL ,  O_SYNC );
if ( dio_fcntl ( $fd ,  F_SETLK , Array( "type" => F_WRLCK )) == - 1 ) {
    // the file descriptor appears locked
    echo  "The lock can not be cleared. It is held by someone else.\n" ;
} else {
   echo  "Lock successfully set/cleared\n" ;
}

dio_tcsetattr ( $fd , array(
   'baud'  =>  9600 ,
   'bits'  =>  8 ,
   'stop'   =>  1 ,
   'parity'  =>  0
)); 

while ( 1 ) {
   $data  =  dio_read ( $fd ,  9999 );
   if ( $data  ) {
      echo  bin2hex($data)."\n";
   }  
   usleep(300000);
}

Windows下脚本如下:

<?php

exec('mode com1: baud=9600 data=8 stop=1 parity=n xon=on');
// execute 'help mode' in command line of Windows for help

$fd = dio_open('com1:', O_RDWR);

while ( true ) {
  $data  =  dio_read ( $fd ,  256 );
  if ($data) {
      echo bin2hex($data)."\n";
  }
  //usleep(10000);
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值