just do it

[测试]NanoPi Duo 用php调用python3 实现串口操作

python3操作串口很方便,想测试一下php调用python3操作串口效果。

 

python3

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# -*- coding: utf-8 -*
import serial
import time
import sys
 
 
def main(code,port):
    # 创建serial实例
    ser = serial.Serial()
    ser.port = port
    ser.baudrate = 9600
    ser.parity = 'N'
    ser.bytesize = 8
    ser.stopbits = 1
#    ser.timeout = 0.2
    # 打开串口
    ser.open()
    # 发送
    ser.write(bytes.fromhex(code))
    # 必要的软件延时
    time.sleep(0.2)
    # 获得接收缓冲区字符
    count = ser.inWaiting()
    if count != 0:
        # 读取内容并回显
        recv = ser.read(count)
        data= recv.hex()
        print(data);
    # 清空接收缓冲区
    ser.flushInput()
 
if __name__ == '__main__':
    try:   
        if len(sys.argv)<3:
            print("参数过少[code,port]")
        else:
            code_input = sys.argv[1]
            port_input = sys.argv[2]
            main(code_input,port_input)
    except KeyboardInterrupt:
        if ser != None:
            ser.close()

php

1
2
3
4
5
6
7
8
9
10
11
12
13
<!--?php &lt;/p&gt;
&lt;p&gt;/**&lt;br ?-->
 *
 * @author ls
 * @email lmt@lostphp.com
 * @date 2018-04-09 05:27:59
 * @desc php 调用python 操作串口
 */
$code = '01 03 40 00 00 02 D1 CB';// 查询 ec值指令
$port = '/dev/ttyUSB0';// 指定串口
$shell = 'python3 py.py';
$output = shell_exec($shell." '$code'"." '$port'");
echo $output;

调用效果

点赞