繁体   English   中英

带有PHP怪异现象的串口读取

[英]Serial Port Reading with PHP weirdness

我已经有一个用PHP编写的项目。 我需要从串行端口读取数据。 我想保持以与项目其余部分相同的语言从串行端口读取的功能。

我发现很多人似乎都遇到问题的课堂。 php_serial.class.php基于示例,这是我为测试编写的。 使用RFID读卡器作为串行输入。

#!/usr/bin/php
<?php

// Include the class to read the serial line.
include ("php_serial.class.php");

// Let's start the class
$serial = new phpSerial;

$serial->deviceSet("/dev/ttyAMA0");
$serial->confBaudRate(9600);
$serial->confParity("none");
$serial->confCharacterLength(8);
$serial->confStopBits(1);
// We can change the baud rate, parity, length, stop bits, flow control
#$serial->confFlowControl("none");

// Check if we can open the serial line.  Otherwise die.
if(!$serial->deviceOpen()) die("unable to open device");

stream_set_timeout($serial->_dHandle, 10);

$rfid_key = FALSE;

// Start the loop to keep checking the
while(!$rfid_key)
{
    $read = $serial->readPort();

    // Array to store eachvalue of the RFID tag
    $ascii_read  = array();

    for($i = 0; $i < strlen($read); $i++)
    {
        $ascii_read[] = ord($read[$i]);
        if(count($ascii_read) == 14 && $ascii_read[0] == 2 && $ascii_read[13] == 3)
        {
            $rfid_key = implode("", $ascii_read);
            break;
        }
    }

    // If the key is empty then sleep for 1 second.
    if(!$rfid_key)
    {
        sleep(1);
    }
}

print_r($rfid_key);
print "\n\n";

如果我运行脚本,它将等待输入,如果我在天线上闪烁RFID标签,则会失败。

然后,我决定看看是否是php,因此我编写了一个python脚本。

import serial
serialport = serial.Serial("/dev/ttyAMA0", 9600, timeout=0.5)
response = serialport.readlines(None)
print response

如果我将标签放在天线上并运行脚本,然后将标签拉开,那么我会得到在该时间段内读取的任意数量的标签实例。 告诉我RFID读取器可与RaspberryPi一起使用。

现在这是真正奇怪的部分。 如果我在执行python代码后返回并执行php代码,那么它将起作用。 这使我相信,这与在Python中完成的串行端口实例化有关,该实例化在以后执行时会保留在php代码中。 然后,我剥离python代码以仅实例化串行端口并退出,并按预期运行php代码。

所以,我的问题是。 WTF是python在做的PHP代码不是吗? 我不是串行总线方面的专家,并且对atm感到非常困惑。

好的,我找到了解决方案。 问题不是PHP脚本,而是为/ dev / ttyAMA010设置的选项

经过大量研究,我发现运行命令/bin/stty -F /dev/ttyAMA010向我显示了串行线的当前状态。 重新启动后运行该命令,将其作为输出。

speed 9600 baud; line = 0;
-brkint -imaxbel

然后运行python脚本,看看有什么区别。

speed 9600 baud; line = 0;
min = 0; time = 0;
-brkint -icrnl -imaxbel
-opost
-isig -icanon -iexten -echo -echoe -echok -echoctl -echoke

然后,我系统地包含了每个配置选项,并刷新了页面,直到工作为止。 最后,我发现我需要2个选项才能使php串行脚本正常工作。

stty -F /dev/ttyAMA0 -isig
stty -F /dev/ttyAMA0 -icanon

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM