gpt4 book ai didi

c - 从目录中读取输入 (4096) 以在 C 中使用

转载 作者:太空宇宙 更新时间:2023-11-03 23:47:13 25 4
gpt4 key购买 nike

我正在尝试从我的 AIN0 channel 读取一个 ADC(12 位,即 0 - 4095)输入,并将其用作“int”,以便我可以在数学函数中使用它。这可能吗?

我指的目录是 Beaglebone Black Debian Wheezy 上的“sys/bus/iio/devices/iio:device0/in_voltage0_raw”。

目前,我有一个 C 文件可以读取用户的输入(通过终端)并执行我需要它执行的数学函数,但我很难理解这个活跃/不断变化的 ADC 值。我也研究过使用“fopen”函数。使用下面的代码,我能够在终端上获得 ADC 值,它会根据输入的电压变化而变化。有没有办法“抓取”来自 ADC 的输入并在数学中使用它功能,即使 ADC 值不断变化?

#define SYSFS_ADC_DIR "/sys/bus/iio/devices/iio:device0/in_voltage0_raw"
#define MAX_BUFF 64
int main(){
int fd;
char buf[MAX_BUFF];
char ch[5]; //Update
ch[4] = 0; //Update

int i;
for(i = 0; i < 30; i++)
{
snprintf(buf, sizeof(buf), SYSFS_ADC_DIR);
fd = open(buf, O_RDONLY);
read(fd,ch,4);
printf("%s\n", ch);
close(fd);

usleep(1000);
}
}

更新代码

我已经对 char ch[5] 进行了更改,我还在代码中进一步放置了我想要的数学函数。

int AIN0_low = 0;    //lowest input of adc
int AIN0_high = 4095; //highest input of adc
int motor_low = 0; //lowest speed value for motor
int motor_high = 3200; //highest speed value for motor
double output = 0;

int main(){
double fd;
char buf[MAX_BUF];
char ch[4] = 0;

int i;
for(i = 0; i < 30; i++)
{
snprintf(buf, sizeof(buf), SYSFS_ADC_DIR);

fd = open(buf, O_RDONLY);
read(fd, ch, 4);

double slope = 1.0 * (motor_high - motor_low) / (AIN0_high - AIN0_low);
output = motor_low + slope * (ch - AIN0_low);

printf("%f\n", output);

close(fd);
usleep(1000);
}
}

最佳答案

在您的第二个函数中,您在计算中使用了文件句柄。我认为你的意思是你读到的值(ch)。只需将值转换为 float ,然后再进行计算即可。

同时向您读取的缓冲区添加另一个字节以容纳结尾的\0

像这样

int  main(){
double fd = 0.0;
char buf[MAX_BUF] = {0};
char ch[5] = {0,0,0,0,0};

// move slope here since it is constant
double slope = 1.0 * (motor_high - motor_low) / (AIN0_high - AIN0_low);

int i;
for(i = 0; i < 30; i++)
{
snprintf(buf, sizeof(buf), SYSFS_ADC_DIR);

fd = open(buf, O_RDONLY);
read(fd, ch, 4);
output = motor_low + slope * (atof(ch) - AIN0_low);

printf("%f\n", output);

close(fd);
usleep(1000);
}
return 0; // add this
}

免责声明:我不知道您使用的硬件,如果设备的行为类似于文件,我只是修复了您的代码。

关于c - 从目录中读取输入 (4096) 以在 C 中使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29972421/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com