c - 传感器的 C 代码仅打印输出一次并退出
问题描述
我是一个 C 菜鸟,我有这个代码,它应该使用树莓派上的 IR 传感器测量体温。该代码工作正常,但它不能在循环模式下工作,只打印一次温度并退出。虽然我希望它连续运行,直到用户按下某个中断键/被用户杀死。
//gcc mlx90614.c -o mlx90614 -l bcm2835
#include <stdio.h>
#include <bcm2835.h>
#include <stdlib.h>
#include <fcntl.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <time.h>
#define AVG 1 //averaging samples
int main(int argc, char **argv)
{
unsigned char buf[6];
unsigned char i,reg;
double temp=0,calc=0, skytemp,atemp;
bcm2835_init();
bcm2835_i2c_begin();
bcm2835_i2c_set_baudrate(25000);
// set address
bcm2835_i2c_setSlaveAddress(0x5a);
printf("\ndevice is working!!\n");
calc=0;
reg=7;
for(i=0;i<AVG;i++)
{
bcm2835_i2c_begin();
bcm2835_i2c_write (®, 1);
bcm2835_i2c_read_register_rs(®,&buf[0],3);
temp = (double) (((buf[1]) << 8) + buf[0]);
temp = (temp * 0.02)-0.01;
temp = temp - 273.15;
calc+=temp;
sleep(1);
}
skytemp=calc/AVG;
calc=0;
reg=6;
for(i=0;i<AVG;i++){
bcm2835_i2c_begin();
bcm2835_i2c_write (®, 1);
bcm2835_i2c_read_register_rs(®,&buf[0],3);
temp = (double) (((buf[1]) << 8) + buf[0]);
temp = (temp * 0.02)-0.01;
temp = temp - 273.15;
calc+=temp;
sleep(1);
}
atemp=calc/AVG;
printf("ambient temperature = %04.2f\n", atemp);
printf("object temperature = %04.2f\n", skytemp);
printf("done\n");
return 0;
}
编译
gcc mlx90614.c -o mlx90614 -l bcm2835
sudo ./mlx90614
输出
device is working!!
ambient temperature = 30.06
object temperature=31.04
done
解决方案
你需要一个无限循环。例如:
printf("\ndevice is working!!\n");
while(1)
{
calc=0;
reg=7;
...
printf("ambient temperature = %04.2f\n", atemp);
printf("object temperature = %04.2f\n", skytemp);
}
printf("done\n");
推荐阅读
- android - AssetLinks 文件预期流量和故障场景
- html - 更改 Kendo UI Timepicker 突出显示的文本颜色
- homebrew - 如何将自制软件包标记为候选发布?
- api - 使用证书测试 API
- wordpress - Wordpress - 重写 url 中的分类值以进行翻译
- github - 如何解决 GitHub 保护分支上的合并冲突。?
- vba - 如何用vba代码打开外部访问数据库并最大化
- r - R chisq.test - 通过df自动化,每个变量都有,df有数据,不是计数,宽格式
- excel - Excel 索引匹配 - 最大、第二大、第三大且没有重复匹配
- python - 如何使用 django 从用户输入中计算未保存到数据库的值和数据库中的值