RC2026 – Part 6 – Reading atmospheric pressure from a BME280 on an RC2014

In previous posts, I’ve been able to read the temperature and humidity using a BME280 sensor attached to my RC2014 computer. The BME280 has one other reading it can provide, and that is atmospheric pressure.

As with the temperature and humidity, I need to calculate the value using the calibration data stored in the BME280. I also need the value of t_fine I stored when calculating the temperature. My previous post showed how to get these values. The BME280 datasheet gives me the algorithm and example code to calculate the air pressure.

float readPressure(void) {
    int64_t var1, var2, p;

    readTemperature(); // Must be done first to set t_fine

    int32_t adc_P = read24(BME280_REGISTER_PRESSUREDATA);
    adc_P >>= 4;

    var1 = ((int64_t)t_fine) - 128000;
    var2 = var1 * var1 * (int64_t)_bme280_calib.dig_P6;
    var2 = var2 + ((var1 * (int64_t)_bme280_calib.dig_P5) << 17);
    var2 = var2 + (((int64_t)_bme280_calib.dig_P4) << 35);
    var1 = ((var1 * var1 * (int64_t)_bme280_calib.dig_P3) >> 8) +
           ((var1 * (int64_t)_bme280_calib.dig_P2) << 12);
    var1 =
        (((((int64_t)1) << 47) + var1)) * ((int64_t)_bme280_calib.dig_P1) >> 33;

    if (var1 == 0) {
        return 0; // avoid exception caused by division by zero
    }
    p = 1048576 - adc_P;
    p = (((p << 31) - var2) * 3125) / var1;
    var1 = (((int64_t)_bme280_calib.dig_P9) * (p >> 13) * (p >> 13)) >> 25;
    var2 = (((int64_t)_bme280_calib.dig_P8) * p) >> 19;

    p = ((p + var1 + var2) >> 8) + (((int64_t)_bme280_calib.dig_P7) << 4);
    return (float)p / 256.0;
}

I can plug this into existing code and get the temperature, air pressure, and humidity, then show it on the console.

float temperature = readTemperature();
float pressure = readPressure();
float humidity = readHumidity();
printf("Temperature: %.2f°C, ", temperature);
printf("Pressure: %.2f hPa, ", pressure);
printf("Humidity: %.2f %%\n", humidity);

RC2026 – Part 5 – Reading the humidity from a BME280 on an RC2014

In my last post, I showed how to read the temperature from a BME280 sensor using a Z80-based RC2014 computer.

The BME280 can also provide readings for humidity and atmospheric pressure. In this post, I’m going to look at reading humidity.

The BME280 provides the humidity value as a 24bit integer. I can use the read24 function I defined in my last post to read this value from the BME280. However, I can’t use it directly. Like the temperature reading, I have to do some calculations using the calibration data from the BME280. Thankfully, the BME280 datasheet gives me an algorithm to do this on page 25, so I just need to tweak this to drop in the relevant values.

float readHumidity(void) {
    int32_t adc_H = read16(BME280_REGISTER_HUMIDDATA);
    int32_t v_x1_u32r;

    v_x1_u32r = (t_fine - ((int32_t)76800));
    v_x1_u32r = (((((adc_H << 14) - (((int32_t)_bme280_calib.dig_H4) << 20) -
                    (((int32_t)_bme280_calib.dig_H5) * v_x1_u32r)) +
                   ((int32_t)16384)) >>
                  15) *
                 (((((((v_x1_u32r * ((int32_t)_bme280_calib.dig_H6)) >> 10) *
                      (((v_x1_u32r * ((int32_t)_bme280_calib.dig_H3)) >> 11) + ((int32_t)32768))) >>
                     10) +
                    ((int32_t)2097152)) *
                       ((int32_t)_bme280_calib.dig_H2) +
                   8192) >>
                  14));
    v_x1_u32r =
        (v_x1_u32r -
         (((((v_x1_u32r >> 15) * (v_x1_u32r >> 15)) >> 7) *
           ((int32_t)_bme280_calib.dig_H1)) >>
          4));
    v_x1_u32r = (v_x1_u32r < 0 ? 0 : v_x1_u32r);
    v_x1_u32r = (v_x1_u32r > 419430400 ? 419430400 : v_x1_u32r);
    return (float)(v_x1_u32r >> 12) / 1024.0;
}

I can now simply tweak my main() function to query this and display the results to the console.

float humidity = readHumidity();
printf("Humidity: %.2f %%\n", humidity);

That was really simple because most of the hard work had already been done in my previous post. The readHumidity function looks complex, but it’s just the example code from the datasheet tweaked to use my variables.

RC2026 – Part 4 – Reading the temperature from a BME280 on an RC2014

In my previous posts, I’ve shown how to read the ID value from a BME280 sensor using an RC2014 computer. That’s not very useful in itself, but it is a good building block for getting practical information from the sensor. In this post, I’m going to read the current temperature.

The temperature isn’t returned as a sensible, human-understandable value directly from the sensor. It needs to be calculated using calibration data that the BME280 also supplies. The BME280 datasheet gives us an algorithm to do this.

I also need to tell the BME280 to continually sense; otherwise, it is in sleep mode.

The BME280 is a very well-known sensor, and there are some libraries written for other systems that I can use to verify my work. Adafruit has a BME280 library for the Arduino that is written in C++. I am going to use some of the code from the Adafruit library where possible.

Writing and reading data

My previous post had a transfer routine to handle the bit-banging of SPI data, so I am going to build upon this.

The first routine we need is one to send and receive data of different lengths. I pass in address locations and lengths. The routine will then bit-bang that amount of data.

void write_then_read(const uint8_t *write_data, uint8_t write_length, uint8_t *read_data, uint8_t read_length) {
    // Deselect the BME280 to ensure it's not selected before starting communication.
    io_spi = SELECT | CLK | MOSI;

    // Write data
    for (uint8_t i = 0; i < write_length; i++) {
        transfer(write_data[i]);
    }

    // Read data
    for (uint8_t i = 0; i < read_length; i++) {
        read_data[i] = transfer(0x00); // Send dummy byte to read
    }

    // Deselect the BME280 after communication is done.
    io_spi = SELECT | CLK | MOSI;
}

I need to be able to read in 8 bit, 16 bit, and 24 bit values in little-endian format, both signed and unsigned, as well as to be able to write an 8 bit value. These utility routines can help with that.

void write8(uint8_t reg, uint8_t value) {
    uint8_t write_data[2] = { reg & 0x7F, value }; // Clear MSB
    write_then_read(write_data, 2, NULL, 0);
}   

uint8_t read8(uint8_t reg) {
    uint8_t write_data[1] = { reg };
    uint8_t read_data[1] = { 0 };

    write_then_read(write_data, 1, read_data, 1);
    return read_data[0];
}

uint16_t read16_LE(uint8_t reg) {
    uint8_t write_data[1] = { reg };
    uint8_t read_data[2] = { 0 };

    write_then_read(write_data, 1, read_data, 2);
    return (read_data[1] << 8) | read_data[0];
}

int16_t readS16_LE(uint8_t reg) {
    return (int16_t)read16_LE(reg);
}   

uint32_t read24(uint8_t reg) {
    uint8_t write_data[1] = { reg };
    uint8_t read_data[3] = { 0 };

    write_then_read(write_data, 1, read_data, 3);
    uint32_t value = 0;
    value |= read_data[0];
    value <<= 8;
    value |= read_data[1];
    value <<= 8;
    value |= read_data[2];
    return value;
}

BME280 registers

The BME280 has numerous registers we can read and write to. The ID we retrieve in the previous blog post uses register 0xd0. Adafruit has defined all of these in their library, so I will reuse their code for this.

enum {
  BME280_REGISTER_DIG_T1 = 0x88,
  BME280_REGISTER_DIG_T2 = 0x8A,
  BME280_REGISTER_DIG_T3 = 0x8C,

  BME280_REGISTER_DIG_P1 = 0x8E,
  BME280_REGISTER_DIG_P2 = 0x90,
  BME280_REGISTER_DIG_P3 = 0x92,
  BME280_REGISTER_DIG_P4 = 0x94,
  BME280_REGISTER_DIG_P5 = 0x96,
  BME280_REGISTER_DIG_P6 = 0x98,
  BME280_REGISTER_DIG_P7 = 0x9A,
  BME280_REGISTER_DIG_P8 = 0x9C,
  BME280_REGISTER_DIG_P9 = 0x9E,

  BME280_REGISTER_DIG_H1 = 0xA1,
  BME280_REGISTER_DIG_H2 = 0xE1,
  BME280_REGISTER_DIG_H3 = 0xE3,
  BME280_REGISTER_DIG_H4 = 0xE4,
  BME280_REGISTER_DIG_H5 = 0xE5,
  BME280_REGISTER_DIG_H6 = 0xE7,

  BME280_REGISTER_CHIPID = 0xD0,
  BME280_REGISTER_VERSION = 0xD1,
  BME280_REGISTER_SOFTRESET = 0xE0,

  BME280_REGISTER_CAL26 = 0xE1, // R calibration stored in 0xE1-0xF0

  BME280_REGISTER_CONTROLHUMID = 0xF2,
  BME280_REGISTER_STATUS = 0XF3,
  BME280_REGISTER_CONTROL = 0xF4,
  BME280_REGISTER_CONFIG = 0xF5,
  BME280_REGISTER_PRESSUREDATA = 0xF7,
  BME280_REGISTER_TEMPDATA = 0xFA,
  BME280_REGISTER_HUMIDDATA = 0xFD
};

Setting the sampling rate

The BME280 doesn’t do much unless it’s told to. So we need a routine to turn it on and get it sampling data. There are various configurations defined in the BME280 documentation, but I’m going to lift these values from the Adafruit library, as they have done the hard work of turning them into enum values already.

enum sensor_mode {
    MODE_SLEEP = 0b00,
    MODE_FORCED = 0b01,
    MODE_NORMAL = 0b11
};

enum sensor_filter {
    FILTER_OFF = 0b000,
    FILTER_X2 = 0b001,
    FILTER_X4 = 0b010,
    FILTER_X8 = 0b011,
    FILTER_X16 = 0b100
};

enum sensor_sampling {
    SAMPLING_NONE = 0b000,
    SAMPLING_X1 = 0b001,
    SAMPLING_X2 = 0b010,
    SAMPLING_X4 = 0b011,
    SAMPLING_X8 = 0b100,
    SAMPLING_X16 = 0b101
};

To set the sampling rate, I need to perform several operations. I first put the BME280 to sleep. This allows me to safely update the configuration and control registers.

void setSampling(enum sensor_mode mode, enum sensor_filter filter, enum standby_duration duration) {
    // Set the sensor to sleep mode before changing settings
    write8(BME280_REGISTER_CONTROL, MODE_SLEEP); 

    // Set the humidity oversampling to x1 (0b001)
    write8(BME280_REGISTER_CONTROLHUMID, 0b001);

    // Set the filter and standby duration in the config register
    uint8_t config = (duration << 5) | (filter << 2);
    write8(BME280_REGISTER_CONFIG, config);

    // Set the temperature and pressure oversampling to x1 (0b001)
    // and the mode
    uint8_t control = (0b001 << 5) | (0b001 << 2) | mode;
    write8(BME280_REGISTER_CONTROL, control);
}

Reading the calibration coefficients

I mentioned earlier the need to use calibration data to calculate the temperature. We need to get these values and store them.

typedef struct {
  uint16_t dig_T1; ///< temperature compensation value
  int16_t dig_T2;  ///< temperature compensation value
  int16_t dig_T3;  ///< temperature compensation value

  uint16_t dig_P1; ///< pressure compensation value
  int16_t dig_P2;  ///< pressure compensation value
  int16_t dig_P3;  ///< pressure compensation value
  int16_t dig_P4;  ///< pressure compensation value
  int16_t dig_P5;  ///< pressure compensation value
  int16_t dig_P6;  ///< pressure compensation value
  int16_t dig_P7;  ///< pressure compensation value
  int16_t dig_P8;  ///< pressure compensation value
  int16_t dig_P9;  ///< pressure compensation value

  uint8_t dig_H1; ///< humidity compensation value
  int16_t dig_H2; ///< humidity compensation value
  uint8_t dig_H3; ///< humidity compensation value
  int16_t dig_H4; ///< humidity compensation value
  int16_t dig_H5; ///< humidity compensation value
  int8_t dig_H6;  ///< humidity compensation value
} bme280_calib_data;

bme280_calib_data _bme280_calib;

The calibration data is a mix of signed and unsigned integers of various lengths. I can use the various read functions I defined earlier to read and save these.

void readCoefficients(void) {
  _bme280_calib.dig_T1 = read16_LE(BME280_REGISTER_DIG_T1);
  _bme280_calib.dig_T2 = readS16_LE(BME280_REGISTER_DIG_T2);
  _bme280_calib.dig_T3 = readS16_LE(BME280_REGISTER_DIG_T3);

  _bme280_calib.dig_P1 = read16_LE(BME280_REGISTER_DIG_P1);
  _bme280_calib.dig_P2 = readS16_LE(BME280_REGISTER_DIG_P2);
  _bme280_calib.dig_P3 = readS16_LE(BME280_REGISTER_DIG_P3);
  _bme280_calib.dig_P4 = readS16_LE(BME280_REGISTER_DIG_P4);
  _bme280_calib.dig_P5 = readS16_LE(BME280_REGISTER_DIG_P5);
  _bme280_calib.dig_P6 = readS16_LE(BME280_REGISTER_DIG_P6);
  _bme280_calib.dig_P7 = readS16_LE(BME280_REGISTER_DIG_P7);
  _bme280_calib.dig_P8 = readS16_LE(BME280_REGISTER_DIG_P8);
  _bme280_calib.dig_P9 = readS16_LE(BME280_REGISTER_DIG_P9);

  _bme280_calib.dig_H1 = read8(BME280_REGISTER_DIG_H1);
  _bme280_calib.dig_H2 = readS16_LE(BME280_REGISTER_DIG_H2);
  _bme280_calib.dig_H3 = read8(BME280_REGISTER_DIG_H3);
  _bme280_calib.dig_H4 = ((int8_t)read8(BME280_REGISTER_DIG_H4) << 4) |
                         (read8(BME280_REGISTER_DIG_H4 + 1) & 0xF);
  _bme280_calib.dig_H5 = ((int8_t)read8(BME280_REGISTER_DIG_H5 + 1) << 4) |
                         (read8(BME280_REGISTER_DIG_H5) >> 4);
  _bme280_calib.dig_H6 = (int8_t)read8(BME280_REGISTER_DIG_H6);    
}

Reading the temperature

The example code given in the BME280 datasheet returned the temperature as an integer, but for ease of use, I will want to use a floating-point value. This is simply the value from the datasheet divided by 100 to give us a value in Celsius. This routine makes extensive use of the calibration data from the BME280.

int32_t t_fine;
int32_t t_fine_adjust = 0;

float readTemperature(void) {
    int32_t var1, var2;
    int32_t adc_T = read24(BME280_REGISTER_TEMPDATA);
    adc_T >>= 4;

    var1 = (int32_t)((adc_T / 8) - ((int32_t)_bme280_calib.dig_T1 * 2));
    var1 = (var1 * ((int32_t)_bme280_calib.dig_T2)) / 2048;
    var2 = (int32_t)((adc_T / 16) - ((int32_t)_bme280_calib.dig_T1));
    var2 = (((var2 * var2) / 4096) * ((int32_t)_bme280_calib.dig_T3)) / 16384;

    t_fine = var1 + var2 + t_fine_adjust;

    int32_t T = (t_fine * 5 + 128) / 256;

    return (float)T / 100;
}

Putting it all together

I have enough code to be able to read the temperature from the BME280, so it’s time to put it all together.

The first thing I need to do is reset the BME280. I can do this by writing to the soft reset register. Secondly, I turn on the BME280 and get it sampling. Next, I read the calibration data. Finally, in a loop, I can continually read the temperature and display it to my serial terminal.

int main(void) {
    write8(BME280_REGISTER_SOFTRESET, 0xB6);

    setSampling(MODE_NORMAL, FILTER_OFF, SAMPLING_X16);

    readCoefficients();

    while(1) {
      float temperature = readTemperature();
      printf("Temperature: %.2f°C\n", temperature);
    }
}

Compiling the code

Because I am using floating-point numbers, I need to include the maths library when compiling. I do this using the -lm flag.

The printf command doesn’t handle floating-point numbers by default, so I also need to enable this. This is done using a C pragma.

#pragma printf %f

When I compile the application using z88dk zcc, my command line looks like this.

zcc +rc2014 -subtype=basic -clib=sdcc_iy -lm -v -m -SO3 --max-allocs-per-node200000 bme280.c -o bme280 -create-app

Running the code

It was very satisfying to see real temperatures on screen when I ran the code. The thermostat in my room was set to 18C, so this seems to be working really well.

Temperature readings of 18.39C being shown in a terminal window.

RC2026 – Part 3 – Using a BME280 environmental sensor on an RC2014 with C

In my previous post, I showed how to read the ID register on the BME280 by bit-banging the SPI protocol using Z80 assembly language. I want to be able to read the temperature using the BME280, but this requires the use of floating-point maths to convert the values returned from the device to a value in degrees Celsius. I think this would be a bit too complex to do using Z80 assembly language, so I plan to switch to using C instead.

I have previously written about using the z88dk C compiler with an RC2014, so I won’t fully go over this again. I will rewrite the previous assembly language code to get the ID of the BME280 device and display it on the LEDs.

Pragmas

I need to set a couple of pragma’s in the C code to tell the compiler where to assemble the code and where to set the stack pointer. The assembly language program ran from address 0x9000, so I will do the same here. I will also set the stack pointer to 0xFC00.

#pragma output CRT_ORG_CODE = 0x9000
#pragma output REGISTER_SP = 0xFC00

Z80 IO Ports

To use the Z80’s IO ports from C, I need to use a special function register. The C compiler z88dk uses has a special instruction called __sfr __at that declares a variable at a specific IO port. This variable can then be read from or assigned, and this maps to Z80 in and out instructions. I’m going to be using IO port 0x01 again.

#define __IO_SPI_PORT 0x01
__sfr __at __IO_SPI_PORT io_spi;

Sending and receiving a byte of data using SPI

Sending and receiving a byte of data takes place in parallel, so I’m going to create a C function that takes a byte as a parameter and also returns a byte.

First, I need to include stdint.h to get the required data type of uint8_t. I also need to define the bit masks for MOSI, MISO, CLK, and SELECT.

#include <stdint.h>

#define MOSI 0b00000001
#define MISO 0b00000001
#define CLK  0b00000010
#define SELECT 0b00001000

Now for the actual transfer function.

// Send a byte and receive a byte from the BME280 over SPI. 
uint8_t transfer(uint8_t value) {
    uint8_t received_value = 0;
    for (int i = 0; i < 8; i++) {
        // Set the MOSI line based on the current bit of the value to send,
        // then det the CLK line low.
        if (value & 0x80) {
            io_spi = 0 &~SELECT &~CLK | MOSI; // Set MOSI high and CLK low.
        } else {
            io_spi = 0 &~SELECT &~CLK; // Set MOSI low and CLK low.
        }
        
        // Read the MISO line to get the received bit.
        uint8_t miso = io_spi & MISO; // Read MISO

        // Shift the received value left and add the new bit.
        received_value = (received_value << 1) | (miso ? 1 : 0);
        
        // Pulse the clock line high.
        if (value & 0x80) {
            io_spi = 0 &~SELECT | CLK | MOSI; // Set MOSI high and CLK high.
        } else {
            io_spi = 0 &~SELECT | CLK; // Set MOSI low and CLK high.
        }
        
        // Prepare for the next bit by shifting the value to send left
        value <<= 1;
    }
    return received_value;
}

Reading the ID byte and displaying the result

Now I have a function that can send and receive a byte; I can request the ID byte.

Firstly, I need to make sure the device isn’t selected. Next, I need to request the ID by sending the command 0xD0, then read the returned byte. I need to send a dummy value when reading the returned byte, so I will use 0x00 in this case. Finally, I deselect the BME280 and show the values on the LEDs, as with the assembly language version.

int main(void) {
    io_spi = SELECT | CLK | MOSI; // Deselect the BME280
    transfer(0xD0);               // send the address for the ID register.
    uint8_t id = transfer(0x00);  // Read the ID register.
    io_spi = SELECT | CLK | MOSI; // Deselect the BME280.

    io_spi = id;                  // display the ID value on the output port
    return 0;
}

RC2026 – Part 2 – Using a BME280 environmental sensor on a RC2014

I previously controlled a MAX7219 LED matrix over SPI from my RC2014 computer. Now I want to try another SPI device, the BM280 environmental sensor from Bosch. The code in this article builds on the previous work, so take a moment to read it if you haven’t already.

The BME280 can read temperature, pressure, and humidity. It is a 3.3V device, so I will need a voltage level converter to use it with a 5V RC2014.

The SPI communication will also need to be two-way, as I will need to tell the sensor what values to send me.

I used the following parts (note: Amazon affiliate links)

The regulator allowed me to generate a 3.3v power supply from the RC2014’s 5v supply. I was then able to use this on the low-voltage side of the level shifter to allow the signals to convert between 5v and 3.3v.

As before, I am using the SC129 Digital IO module on my RC2014 to bit-bang the SPI protocol. This is wired up via the level shifters and 3.3V regulator as follows…

SC129BME280
GNDGND
5V3.3V (via 3.3 regulator)
OUT D0SDA / SDI (via level shifter)
OUT D1SCL / SCK (via level shifter)
OUT D3CSB (via level shifter)
IN D0SDO (via level shifter)

The BME280 gives us the following timing diagram for SPI communication.

BME280 SPI timing diagram

Looking at the timing diagram, we can see that before we start any communication, the SCL / SCK and CSB lines both need to be high. We can use a subroutine to do this.

deselect_bme280:
    ld a, 0 | SELECT | CLK | MOSI
    out (OUTPUT_PORT),a
    ret

Sending and receiving take place on the transition of the SCK line from high to low.

This code is similar to the code for the LED matrix in my earlier post. I have added some additional code to handle the input. This reads the bit, rotates it right into the carry flag, then rotates that value into the E register. By the end of the routine, the byte in register D will have been sent, and the byte returned will be in register E.

send_receive_byte:
    push bc
    ld b, 8
    ld a, 0 &~SELECT &~CLK | MOSI
    rra
    ld c, a
.transmit_bme280_bit:
    ld a, c
    rl d
    rla 
    out (OUTPUT_PORT), a.  ; CLK low
    in a, (INPUT_PORT)
    rra
    rl e
    ld a, c
    or a, CLK
    out (OUTPUT_PORT), a   ; CLK high
    djnz .transmit_bme280_bit
    pop bc
    ret

To test that this is working, we can send the value 0xD0 to the BME280. It should send back the value 0x60. To read the returned byte, we send 0x00. While this is being sent, the result byte will be returned simultaneously. We will then output this byte to the SC129 so the display LEDs will show the returned value in binary.

bme280_getId:
    call deselect_bme280
    ld d, 0xD0
    call send_receive_byte
    ld d, 0x00
    call send_receive_byte 
    call deselect_bme280

    ld a, e
    out (OUTPUT_PORT), a
    ret

After running, the LEDs correctly show 01100000 – 0x60.

The next step will be to get actual temperature readings. That will be the subject of the next post.