【发布时间】:2016-03-09 00:50:33
【问题描述】:
所以我被招募到学校的 Baja 赛车队,在那里我们设计建造并与越野沙丘越野车竞争。我是一名 CS 专业的,对 python 有相当多的经验,因此被要求帮助电气团队与我们想要在汽车上安装的所有传感器进行接口。到目前为止一切都很好,但现在我正在使用一个红外温度传感器来读取环境和物体温度。 (我们将把它放在引擎的某个地方以读取它的温度并输出到我们的 GUI)
问题在于,似乎使用过这个传感器的唯一库都是用 C 语言编写的,并且通常与 arduinos 一起使用……尽管如此,我编译并编辑了一些我在网上找到的 C 代码,效果很好!在 C. :( 因为我们的项目完全基于 python;我真的很想通过 i2c 和 Python 来阅读这个传感器,虽然我真的没有很多编写库的经验,尤其是对于电子产品。任何提示会很好地引导我朝着正确的方向前进。这是我们目前使用的 C 代码,我基本上想要在 Python 中做同样的事情:
//fordit: gcc MLXi2c.c -o i2c -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
#define LOGTIME 10 //loging period
int main(int argc, char **argv)
{
unsigned char buf[6];
unsigned char i,reg;
double temp=0,calc=0, skytemp,atemp;
FILE *flog;
flog=fopen("mlxlog.csv", "a");..
bcm2835_init();
bcm2835_i2c_begin();
bcm2835_i2c_set_baudrate(25000);.
// set address...........................................................................................
bcm2835_i2c_setSlaveAddress(0x5a);
....
printf("\nOk, your device is working!!\n");
....
....
while(1) {
time_t t = time(NULL);
<------>struct tm tm = *localtime(&t);
<------>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("%02d-%02d %02d:%02d:%02d\n Tambi=%04.2f C, Tobj=%04.2f C\n", tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec,atemp,skytemp);
<------>fprintf(flog,"%04d-%02d-%02d %02d:%02d:%02d,%04.2f,%04.02f\n",tm.tm_year+1900, tm.tm_mon +1, tm.tm_mday,tm.tm_hour, tm.tm_min, tm.tm_sec,atemp,skytemp);
<------>fflush(flog);
<------>sleep(LOGTIME-(2*AVG));
}
...
printf("[done]\n");
}
提前致谢!
- 艾迪
【问题讨论】:
-
为什么不直接从python调用C程序而不是重写整个东西?
-
我不知道你能做到这一点?你介意详细说明吗?我其实想过这个,如果我能以某种方式将 C 程序的返回值导入 python,我会很高兴。
-
如果你有一个不能无限运行的程序,它就像
import subprocess; sens_val = subprocess.check_output(["path_to_your_c_program"])一样简单如果你的 C 程序确实可以无限运行(例如,在while(1)循环中,就像在 arduino 上一样),您可以简单地删除该循环,使其每次执行仅获取一个传感器读数,将其打印到标准输出并退出。
标签: python raspberry-pi