#ifndef __MS5611_H__
#define __MS5611_H__

#ifdef __cplusplus
 extern "C" {
#endif

#include "stm32f4xx.h"

#define MS5611_ADDR (0x77 << 1)

#define MS5611_DELAY_CNT_START_1       (5)
#define MS5611_DELAY_CNT_START_2       (5)
#define MS5611_DELAY_CNT_STOP_1        (5)
#define MS5611_DELAY_CNT_STOP_2        (5)
#define MS5611_DELAY_CNT_DATA_MODIFY_1 (5)
#define MS5611_DELAY_CNT_DATA_MODIFY_2 (5)
#define MS5611_DELAY_CNT_DATA_SAMPLE_1 (5)
#define MS5611_DELAY_CNT_DATA_SAMPLE_2 (5)

#define I2Cx            I2C1
#define MS5611_PORT    (GPIOB)
#define MS5611_PIN_SCL (GPIO_Pin_8)
#define MS5611_PIN_SDA (GPIO_Pin_9)

#define MS5611_CMD_RESET      (0x1E)
#define MS5611_CMD_D1_OSR256  (0x40)
#define MS5611_CMD_D1_OSR512  (0x42)
#define MS5611_CMD_D1_OSR1024 (0x44)
#define MS5611_CMD_D1_OSR2048 (0x46)
#define MS5611_CMD_D1_OSR4096 (0x48)
#define MS5611_CMD_D2_OSR256  (0x50)
#define MS5611_CMD_D2_OSR512  (0x52)
#define MS5611_CMD_D2_OSR1024 (0x54)
#define MS5611_CMD_D2_OSR2048 (0x56)
#define MS5611_CMD_D2_OSR4096 (0x58)
#define MS5611_CMD_ADC_READ   (0x00)

#define MS5611_FLAG_IDLE    (0)
#define MS5611_FLAG_CMD_D1  (1)
#define MS5611_FLAG_READ_D1 (2)
#define MS5611_FLAG_END_D1  (3)
#define MS5611_FLAG_CMD_D2  (4)
#define MS5611_FLAG_READ_D2 (5)
#define MS5611_FLAG_END_D2  (6)

struct data_ms5611_s {
    uint32_t data[2];
    uint16_t prom[8];
    uint8_t prom_error;
    uint8_t flag;
    int32_t pressure;
};

extern uint32_t system_tick_cnt;
extern struct data_ms5611_s data_ms5611;

void ms5611_init(void);
ErrorStatus ms5611_i2c_write_data(uint8_t *data, uint16_t len);
ErrorStatus ms5611_i2c_read_data(uint8_t *data, uint16_t len);
uint8_t ms5611_crc4_check_valid(uint16_t *prom);
void ms5611_read_prom(void);
void ms5611_write_cmd(uint8_t cmd);
ErrorStatus ms5611_read_data(uint32_t *data);
void ms5611_loop(void);

#ifdef __cplusplus
}
#endif

#endif /* __MS5611_H__ */
