Settings | Sign in | Sign up

There are currently 10 posts.

[案例]Linux下PHP讀寫串口

Floor 1 巨大八爪鱼 6/29/15 23:21
<?php
$fp = fopen("/dev/ttyUSB0", "r+");
fwrite($fp, "\x80");
$data = fread($fp, 81);
$data = preg_replace("/^./", "", $data); // $data{0} is useless
$data = str_replace("\n", "<br>", $data);
$data = str_replace(" ", "&nbsp;", $data);
echo $data;
fclose($fp);
?>
Floor 2 巨大八爪鱼 6/29/15 23:21
輸出:
****************
It works. -- PCE
         -- By Octopus
**********************
Floor 3 巨大八爪鱼 6/29/15 23:21
注:/dev/ttyUSB0的權限是666
Floor 4 巨大八爪鱼 6/29/15 23:32
向串口发送0x80这个十六进制数:
fwrite($fp, "\x80");
Floor 5 巨大八爪鱼 6/29/15 23:34
$data = fread($fp, 81);
从串口中读取81字节字符串。读出来的字符串的第一个字符没有用,要删除。如果串口发送的数据不到81字节,程序就会停在这里,直到81个字节都接收完毕。所以这里无需sleep函数
Floor 6 巨大八爪鱼 6/29/15 23:35
看了一下资料,读取出来的第一个字节应该是用于判断有无后续数据。
Floor 7 巨大八爪鱼 6/29/15 23:38
这个用于删除接收到的字符串的首字符:
$data = preg_replace("/^./", "", $data); // $data{0} is useless
Floor 8 巨大八爪鱼 6/29/15 23:40
回復:5樓
所以,第一次执行这个语句后,程序只从串口中读取了80字节数据。
Floor 9 巨大八爪鱼 6/30/15 9:40
<?php
$filename = "/dev/ttyUSB0";
if (file_exists($filename)) {
    echo "File \"$filename\" exists.<br>\n";
}
$perms = substr(sprintf("%o", fileperms($filename)), -4);
echo "Permissions: $perms";
?>
輸出:
File "/dev/ttyUSB0" exists.
Permissions: 0666
Floor 10 巨大八爪鱼 6/30/15 9:40
<?php
$filename = "/dev/ttyUSB0";
$fp = fopen($filename, "a+");
fwrite($fp, "\x80");
$flag = fread($fp, 1);
$data = fread($fp, 80);

$data = str_replace("\n", "<br>", $data);
$data = str_replace(" ", "&nbsp;", $data);

printf("Flag: 0x%x<br>\nData:<br>\n %s", ord($flag), $data);
fclose($fp);
?>
輸出:
Flag: 0x80
Data:
****************
It works. -- PCE
         -- By Octopus
**********************

Content converter:

Reply the post
Content:
User: You are currently anonymous.
Captcha:
Unclear? Try another one.
©2010-2025 Purasbar Ver3.0 [Mobile] [Desktop]
Except where otherwise noted, content on this site is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported license.