Raspberry Pi - 与支持i2c的红外温度传感器接口(MLX90614)

时间:2016-03-09 00:50:34

标签: python raspberry-pi

所以我被招募到我学校的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 (&reg, 1);
<------>    bcm2835_i2c_read_register_rs(&reg,&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 (&reg, 1);
<------>    bcm2835_i2c_read_register_rs(&reg,&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");
}

提前感谢!

  • 埃迪

1 个答案:

答案 0 :(得分:1)

<强>的变化:

  • 删除while(1) - 每次执行只读取一次。如果传感器需要重复启动,则可能需要for / while循环;除非你打算从python中删除进程,否则不要让它成为无限循环。
  • 最后printf现在输出一个由起始和结束管道分隔的JSON字符串/ |
  • return 0;添加到main(),以便python的子进程模块知道 怎么了
  • 删除了导致编译器错误的注释和句号(低级别的C专家,这些句号是完整的吗?)

将其另存为 mlx90614_query.c 并编译:

//fordit:  gcc mlx90614_query.c -o mlx90614_query -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");

    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 (&reg, 1);
        bcm2835_i2c_read_register_rs(&reg,&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 (&reg, 1);
        bcm2835_i2c_read_register_rs(&reg,&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("|{\"time\":{\"month\":\"%02d\",\"day\":\"%02d\",\"hour\":\"%02d\",\"min\":\"%02d\",\"sec\":\"%02d\"},\"data\":{\"t_ambi\":\"%04.2f\",\"t_obj\":\"%04.2f\"}}|\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");

    return 0;
}

您的C程序现在输出您现有的调试消息以及此json(“|”用作分隔符):

{
    "time": {
        "month": "03",
        "day": "09",
        "hour": "20",
        "min": "24",
        "sec": "28"
    },
    "data": {
        "t_ambi": "77.77",
        "t_obj": "34.44"
    }
}

将此保存为与mlx90614_query相同的文件夹中的python脚本(如果复制/粘贴到交互式解释器,额外的空格将导致麻烦):

from __future__ import print_function
import json
import subprocess
import sys

sensor_dict = {}

py3 = False

# python version check determines string handling

try:
    if (sys.version_info > (3, 0)):
        py3 = True    
except:
    pass

try:

    subp_ret = subprocess.check_output(["./mlx90614_query"])

    # at this point, subprocess succeeded and subp_ret holds your output 

    if py3:
        subp_ret = subp_ret.decode('utf8')

    sensor_dict = json.loads(subp_ret.split("|")[1].strip())

    # cast temperatures to float and print

    for k in sensor_dict["data"]:
        val = float(sensor_dict["data"][k]) 
        sensor_dict["data"][k] = val  
        print (k, "\t", val) 

    # cast date/time segments to int and print

    for k in sensor_dict["time"]:
        val = int(sensor_dict["time"][k])
        sensor_dict["time"][k] = val  
        print (k, "\t", val)         

    # Now go win that race! :P

except Exception as e:
    print(str(e))

输出:

$ gcc mlx90614_query.c -o mlx90614_query -l bcm2835
$

$ ./mlx90614_query
Ok, your device is working!!
|{"time":{"month":"03","day":"09","hour":"21","min":"45","sec":"53"},"data":{"t_ambi":"0.00","t_obj":"0.00"}}|
[done]


$ python3.4 mlx_print.py 
t_obj    34.44
t_ambi   77.77
hour     21
sec      33
min      58
month    3
day      9

$ python2 mlx_print.py 
t_ambi   77.77
t_obj    34.44
min      58
sec      37
day      9
hour     21
month    3

很抱歉您偷了作业 - 只需<3代码:D