读取工控机io system 与 popen
- io操作API
- c++ system()
- popen
- open
os.system()、os.popen()和subprocess的区别(一)
 
函数system
直接读文件最快![Linux] Ubuntu实机下控制GPIO
io操作API
工控机的io口操作的函数
 需要通过命令行执行
 
 具体指令内容:
 
c++ system()
返回数据为字符串
 c++程序中通过sytem(cmd)可以执行该操作,但无法接收到返回值
 system()操作成功的返回值是0
 io信息只打印在终端中
 执行过程平均15ms
 
popen
通过popen可以开启管道接收system返回的字符串到程序中
 
 但是耗时更久了,平均55ms
 
open
通过文件直接读取DIO电平
#include "stdio.h"
#include "fcntl.h"
#include "unistd.h"//引用需要的头文件
 
int main(void)
{
	int fd;
	char value=0;
	
	fd = open("/sys/class/gpio/export",O_RDWR);     //fd作为可读可写的/sys/class/gpio/export
	write(fd,"36",2);                               //启用36号ID引脚,返回的期望值为2个字符
	close(fd);                                      //释放FD
 
	fd = open("/sys/class/gpio/gpio36/direction",O_RDWR);
	write(fd,"in",3);                               //36号ID设为输入
	close(fd);
 
    fd = open("/sys/class/gpio/gpio36/value",O_RDWR); //fd作为IO口的电平状态value
	while(1)
    {
		read(fd,&value,1);                          //读入电平
		printf("Value =%c \r\n",value);             //打印电平状态
        sleep(1);                                   //延时1S
	}
	return 0;
}
类似地
	char tmp[1024];
    memset(tmp, 0 , 1024);
    std::string result;
    int fd ;
    fd = open("/sys/kernel/debug/asus-nb-wmi/call", O_RDWR);
    // cout << " open call res : " << fd  << endl;
   int rest =   read(fd, tmp, 100 );
    result += tmp;
    close(fd);
	// 从返回字符串中截取倒数第二个字符为电平状态
   fd= result.size();
    string res = result.substr(fd-2,1);
    fd = atoi(res.c_str());
    // cout << " res : " << x << endl;
    return fd;
时间测试,1.3ms读取一次
 



















