#include #include "spi.h" #include "ml5238.h" static int ml5238_read(uint8_t regaddr, uint8_t *data); void ml5238_init(void){ spi0_init(); ml5238_softreset(); } /* disable the vmon output the cell voltage */ int ml5238_disable_vmon(void){ return ml5238_write(ML5238_VMON, 0x00); } /* select one cell (0-14) connect to vmon, so we can measure * the cell voltage from vmon pin */ int ml5238_select_cell_to_vmon(int cell){ return ml5238_write(ML5238_VMON, cell | VMON_OUT); } int ml5238_enable_discharger_mosfet(int enable){ uint8_t data; if (ml5238_read(ML5238_FET, &data) == 0){ if (data & FET_DF == enable){ return 0; //alread enable/disabled } data &= ~(FET_DF); if (enable){ data |= (FET_DF | FET_DRV); } return ml5238_write(ML5238_FET, data); } return -1; } /* when enable charger the discharger mosfet also must be enabled for charging */ int ml5238_enable_charger_mosfet(int enable){ uint8_t data; if (ml5238_read(ML5238_FET, &data) == 0){ if (((data & FET_CF) >> 1) == enable){ return 0; //alread enable/disabled } data &= ~(FET_CF); if (enable){ data |= (FET_CF | FET_DRV); } return ml5238_write(ML5238_FET, data); } return -1; } int ml5238_short_current_detect(int mode){ uint8_t rsense = 0; if (mode >= SHORT_CURRENT_MODE_33_3A){ if (ml5238_read(ML5238_RSENSE, &rsense) == 0){ if (ml5238_write(ML5238_SETSC, mode) == 0){ if (rsense & (RSENSE_ESC | RSENSE_ISC)){ return 0; //already enabled short current detect } rsense |= (RSENSE_ESC | RSENSE_ISC);//enable short current detect && irq return ml5238_write(ML5238_SETSC, rsense); } } }else { if (ml5238_read(ML5238_RSENSE, &rsense) == 0){ if (rsense & RSENSE_ESC == 0){ return 0; //already disabled } rsense &= ~(RSENSE_ESC|RSENSE_ISC); return ml5238_write(ML5238_SETSC, rsense); } } return -1; } void ml5238_softreset(void) { unsigned char i; for(i=0u;i<0x0Au;i++) { ml5238_write((uint8_t)(ML5238_VMON + i), 0x00u); } } void ml5238_irq_handler(void){ } int ml5238_write(uint8_t regaddr, uint8_t data){ uint16_t send_data=(((uint16_t)regaddr)<<(0x08+1u))|((uint16_t)data); ml5238_cs(0); int ret = spi0_send_uint16(send_data, NULL); ml5238_cs(1); return ret; } static int ml5238_read(uint8_t regaddr, uint8_t *data){ uint16_t send_data=((((uint16_t)regaddr)<<(0x08+1u))|0x0100u)|((uint16_t)0x00u); ml5238_cs(0); int ret = spi0_send_uint16(send_data, data); ml5238_cs(1); return ret; }