Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
435 views
in Technique[技术] by (71.8m points)

hardware interface - How to Read RS232 Serial Port in PHP like this QBasic Program

I'm trying to port the following small QBASIC program (which works 100%) to PHP:

OPEN "com1:2400,n,8,1,DS," FOR RANDOM AS #3
OPEN "data.dat" FOR OUTPUT AS #2
REM read 17 chars from the port
scale$ = INPUT$(17, #3)
PRINT scale$
WRITE #2, scale$
CLOSE #2
CLOSE #3
SYSTEM

Currently I'm calling it in its compiled (exe) form from PHP (on WAMP5) but I'd like to get rid of the QBASIC and call it directly from PHP.

I wrote this PHP function but it just hangs at the fgets() line:

function read_port($port='COM1:', $length=17, $setmode=TRUE, $simulate='') {
    if ($simulate){
        $buffer = '"'.strval(rand(1000, 2000));
        return $buffer;
    }
    if ($setmode){
        shell_exec('mode com1: baud=2400 parity=n data=8 stop=1 to=on xon=off odsr=on octs=on dtr=on rts=on idsr=on');
    }
    $fp = fopen($port, "rb+");
    if (!$fp) {
        file_put_contents('debug1.log','COM1: could not open'."
",FILE_APPEND);
    } else {
        $buffer = fgets($fp, $length); // <-- IT JUST HANGS HERE DOING NOTHING !
        fclose ($fp);
    }
    return $buffer;

}

I'm using this PHP line to call the above function:

$res = read_port('COM1:', 17, TRUE, SIMULATE_SCALE);

Any help will be creatly appreciated! I've basically given up trying. If QBASIC can do it perfectly then we must be able to make this work with PHP!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You might want to look into PHP Serial by Rémy Sanchez. There's an article about it here:

Controlling the Serial Port with PHP

Also have a look at this example provided by jared at dctkc dot com on the PHP site:

http://php.net/manual/en/function.fopen.php#20935


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...