2 #include "stm32f1xx_hal.h"
10 #define bmp_debug debug_printf
12 static inline void bmp_debug(char *msg, ...)
16 static byte bmp_i2c_buf[4];
17 volatile byte *bmp_i2c_ptr;
18 volatile byte bmp_i2c_len;
19 volatile byte bmp_i2c_addr;
21 static uint bmp_read(uint reg, uint bytes)
24 bmp_i2c_ptr = bmp_i2c_buf;
28 LL_I2C_GenerateStartCondition(I2C1);
29 LL_I2C_EnableIT_TX(I2C1);
34 bmp_i2c_ptr = bmp_i2c_buf;
38 LL_I2C_GenerateStartCondition(I2C1);
39 LL_I2C_EnableIT_RX(I2C1);
45 for (uint i=0; i<bytes; i++)
46 d = (d << 8) | bmp_i2c_buf[i];
51 static void bmp_start_measure(uint type)
53 LL_I2C_GenerateStartCondition(I2C1);
54 while (!LL_I2C_IsActiveFlag_SB(I2C1))
57 LL_I2C_TransmitData8(I2C1, 0xee);
58 while (!LL_I2C_IsActiveFlag_ADDR(I2C1))
60 LL_I2C_ClearFlag_ADDR(I2C1);
62 while (!LL_I2C_IsActiveFlag_TXE(I2C1))
64 LL_I2C_TransmitData8(I2C1, 0xf4);
66 while (!LL_I2C_IsActiveFlag_TXE(I2C1))
68 LL_I2C_TransmitData8(I2C1, type);
70 while (!LL_I2C_IsActiveFlag_TXE(I2C1))
72 LL_I2C_GenerateStopCondition(I2C1);
75 // Formulae from BMP085 specs
76 static void bmp_recalc(uint UT, uint UP, uint oss, u16 cc[11], int *tt, int *pp)
91 int X1 = (UT-AC6)*AC5 / (1<<15);
92 int X2 = MC*(1<<11) / (X1+MD);
94 int T = (B5+8) / (1<<4);
98 X1 = (B2*(B6*B6/(1<<12))) / (1<<11);
99 X2 = AC2 * B6 / (1<<11);
101 int B3 = (((AC1*4 + X3) << oss) + 2) / 4;
102 X1 = AC3 * B6 / (1<<13);
103 X2 = (B1*(B6*B6/(1<<12))) / (1<<16);
104 X3 = ((X1+X2) + 2) / (1<<2);
105 uint B4 = (uint)(AC4 * (X3 + 32768)) / (1U<<15);
106 uint B7 = (uint)(UP-B3) * (uint)(50000>>oss);
112 X1 = (p/(1<<8)) * (p/(1<<8));
113 X1 = (X1*3038) / (1<<16);
114 X2 = (-7357*p) / (1<<16);
115 p = p + (X1 + X2 + 3791) / (1<<4);
122 static u16 bmp_constants[11] = {
138 bmp_debug("BMP: Test constants\n");
144 static u16 bmp_constants[11];
148 bmp_debug("BMP: Reading constants\n");
149 for (uint i=0; i<11; i++)
151 bmp_constants[i] = bmp_read(0xaa + 2*i, 2);
152 bmp_debug("BMP: const[%d] = %04x\n", i, bmp_constants[i]);
165 static byte bmp_state = BMP_IDLE;
167 static u32 raw_press;
180 bmp_debug("BMP: Start measure\n");
181 bmp_start_measure(0x2e);
185 if (!LL_GPIO_IsInputPinSet(BMP_DONE_GPIO_Port, BMP_DONE_Pin))
187 bmp_debug("BMP: Temperature measured\n");
191 raw_temp = bmp_read(0xf6, 2);
193 bmp_debug("BMP: Raw temperature: %04x\n", raw_temp);
194 bmp_start_measure(0xf4 | (BMP_OSS<<6));
198 if (!LL_GPIO_IsInputPinSet(BMP_DONE_GPIO_Port, BMP_DONE_Pin))
200 bmp_debug("BMP: Pressure measured\n");
202 raw_press = 23843 << 8;
204 raw_press = bmp_read(0xf6, 3);
206 bmp_debug("BMP: Raw pressure: %06x\n", raw_press);
207 bmp_recalc(raw_temp, raw_press, BMP_OSS, bmp_constants, &adjusted_temp, &adjusted_press);
208 bmp_debug("BMP: Adjusted temp %d, press %d\n", adjusted_temp, adjusted_press);
210 bmp_state = BMP_IDLE;