twartzek / bme680-raspberry

C Code which reads measurements of a BME680 connected to a raspberry pi.
MIT License
21 stars 9 forks source link

exposing functions to make it callable from python #5

Open And1DS opened 6 years ago

And1DS commented 6 years ago

Hi, not really an issue but wanted to share...

I have adapted the code from twartzek to be compiled as a shared library and the functions callable from python. This is how I did it (code might be incomplete but you get the idea):

I changed the main function and added some subroutines, also made the two following variables global:

//global Variables
struct bme680_dev gas_sensor;
struct bme680_field_data data;

int8_t update_sensor_data(){
    int8_t rslt = BME680_OK;
    // Trigger a meausurement
    rslt = bme680_set_sensor_mode(&gas_sensor); /* Trigger a measurement */

    uint16_t meas_period;
    bme680_get_profile_dur(&meas_period, &gas_sensor);
    // Wait for a measurement to complete
    user_delay_ms(meas_period + 1000); /* Wait for the measurement to complete */
    rslt = bme680_get_sensor_data(&data, &gas_sensor);
    // Avoid using measurements from an unstable heating setup 
        if(data.status & BME680_HEAT_STAB_MSK)
        {
            return 0;
        }
        else {
            return -1;
        }
}

int16_t get_temperature(){
    if (data.temperature != NULL) {
        return data.temperature;
    }
    else {
        return -999;
    }
}

uint32_t get_pressure(){
    if (data.pressure != NULL) {
        return data.pressure;
    }
    else {
        return 0;
    }
}

uint32_t get_humidity(){
    if (data.humidity != NULL) {
        return data.humidity;
    }
    else {
        return 0;
    }
}

uint32_t get_gas_resistance(){
    if (data.gas_resistance != NULL) {
        return data.gas_resistance;
    }
    else {
        return 0;
    }
}

uint8_t get_status(){
    return data.status;
}

uint8_t get_gas_index(){
    return data.gas_index;
}

Compile code using gcc

gcc -c -fpic bme680_main.c bme680.c -std=c11

Create shared library

gcc -shared -o libbme680.so bme680.o bme680_main.o

Call from Python

from ctypes import *
bme680 = cdll.LoadLibrary('./libbme680.so')
rslt = bme680.init_device(1)
rslt = bme680.update_sensor_data()
temp = bme680.get_Temperature()

...

bme680.disconnect_device()
twartzek commented 6 years ago

Hi @AjejeBraso,

thanks for this submission, which shows how to use it seamlessly in python.

Best, Tobias