简体   繁体   English

在不关闭文件描述符的情况下读取ADC(Beaglebone Black)

[英]Read ADC (Beaglebone Black) without closing File Descriptor

Is it possible to read the ADC of a Beaglebone Black or another embedded-linux system without closing the File descriptor? 是否可以在不关闭文件描述符的情况下读取Beaglebone Black或其他嵌入式Linux系统的ADC?

I tried it with a select before read() . 我在read()之前尝试了一次select。 select() returns 1, but read() returns 0 after the first iteration and therefore I can't get any data. select()返回1,但是read()在第一次迭代后返回0,因此我无法获取任何数据。 Any ideas? 有任何想法吗? Does closing and opening of the file descriptor requires a lot of CPU power? 关闭和打开文件描述符是否需要大量的CPU能力?

My code: 我的代码:

 #include<iostream>
 #include<fstream>
 #include<string.h>
 #include<sstream>
 #include<fcntl.h>
 #include<unistd.h>
 #include<sys/select.h>
 #include <sys/time.h>

 using namespace std;

 #define LDR_PATH "/sys/bus/iio/devices/iio:device0/in_voltage"

 int main(int argc, char* argv[]){
 int number = 1;
 int AdcConnection = 0;

stringstream AdcPath;
AdcPath << LDR_PATH << number << "_raw";


AdcConnection = open(AdcPath.str().c_str(),O_RDONLY |O_NONBLOCK);

 if (AdcConnection <0)
 {
perror("UART: Failed to open the file.\n");
close(AdcConnection);
return -1;
 }

 fd_set fdsAdcRead;
 struct timeval timeout = {5, 0};

 unsigned char receive[5];
 int FlagRead = -1;
 int FlagSelect = -1;

while (1)
{
 FD_ZERO(&fdsAdcRead); //clear the file descriptor
 FD_SET(AdcConnection,&fdsAdcRead); //Set the descriptor

 FlagSelect = select(AdcConnection+1,&fdsAdcRead,NULL,NULL,&timeout);//check if data are available

if (FlagSelect <0)
{
     perror("Failed to check if data are available.\n");
     close(AdcConnection);
     return -1;
}
else if (FlagSelect ==0)
{
    cout << "There were no Data" << endl;
    timeout.tv_sec = 5;
}
else
{
 memset(&receive,0,sizeof(receive));
 FlagRead = read(AdcConnection, (void*)receive, 5);
 cout << receive << endl << FlagRead << FlagSelect << endl;
 timeout.tv_sec = 5;
}


 usleep(1000000);
}

The problem is probably that read() changes the file offset. 问题可能是read()更改了文件偏移量。 Try seeking back to the beginning of the file with lseek(2) after reading, or use pread(2) to explicitly read from offset 0. – Ulfalizer 尝试在读取后使用lseek(2)返回文件的开头,或使用pread(2)从偏移量0显式读取。– Ulfalizer

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

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