ml5238.c 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. #include <string.h>
  2. #include "spi.h"
  3. #include "ml5238.h"
  4. static int ml5238_read(uint8_t regaddr, uint8_t *data);
  5. void ml5238_init(void){
  6. spi0_init();
  7. ml5238_softreset();
  8. }
  9. int ml5238_enable_discharger_mosfet(int enable){
  10. uint8_t data;
  11. if (ml5238_read(ML5238_FET, &data) == 0){
  12. if (data & FET_DF == enable){
  13. return 0; //alread enable/disabled
  14. }
  15. data &= ~(FET_DF);
  16. if (enable){
  17. data |= (FET_DF | FET_DRV);
  18. }else {
  19. if (data & FET_CF == 0){
  20. data &= ~(FET_DRV);
  21. }
  22. }
  23. return ml5238_write(ML5238_FET, data);
  24. }
  25. return -1;
  26. }
  27. /* when enable charger the discharger mosfet also must be enabled for charging */
  28. int ml5238_enable_charger_mosfet(int enable){
  29. uint8_t data;
  30. if (ml5238_read(ML5238_FET, &data) == 0){
  31. if (((data & FET_CF) >> 1) == enable){
  32. return 0; //alread enable/disabled
  33. }
  34. data &= ~(FET_CF);
  35. if (enable){
  36. data |= (FET_CF | FET_DRV);
  37. }else {
  38. if (data & FET_DF == 0){
  39. data &= ~(FET_DRV);
  40. }
  41. }
  42. return ml5238_write(ML5238_FET, data);
  43. }
  44. return -1;
  45. }
  46. int ml5238_short_current_detect(int mode){
  47. uint8_t rsense = 0;
  48. if (mode >= SHORT_CURRENT_MODE_33_3A){
  49. if (ml5238_read(ML5238_RSENSE, &rsense) == 0){
  50. if (ml5238_write(ML5238_SETSC, mode) == 0){
  51. if (rsense & (RSENSE_ESC | RSENSE_ISC)){
  52. return 0; //already enabled short current detect
  53. }
  54. rsense |= (RSENSE_ESC | RSENSE_ISC);//enable short current detect && irq
  55. return ml5238_write(ML5238_SETSC, rsense);
  56. }
  57. }
  58. }else {
  59. if (ml5238_read(ML5238_RSENSE, &rsense) == 0){
  60. if (rsense & RSENSE_ESC == 0){
  61. return 0; //already disabled
  62. }
  63. rsense &= ~(RSENSE_ESC|RSENSE_ISC);
  64. return ml5238_write(ML5238_SETSC, rsense);
  65. }
  66. }
  67. return -1;
  68. }
  69. void ml5238_softreset(void)
  70. {
  71. unsigned char i;
  72. for(i=0u;i<0x0Au;i++)
  73. {
  74. ml5238_write((uint8_t)(ML5238_VMON + i), 0x00u);
  75. }
  76. }
  77. void ml5238_irq_handler(void){
  78. }
  79. int ml5238_write(uint8_t regaddr, uint8_t data){
  80. uint16_t send_data=(((uint16_t)regaddr)<<(0x09))|((uint16_t)data);
  81. ml5238_cs(0);
  82. int ret = spi0_send_uint16(send_data, NULL);
  83. ml5238_cs(1);
  84. return ret;
  85. }
  86. static int ml5238_read(uint8_t regaddr, uint8_t *data){
  87. uint16_t send_data=((((uint16_t)regaddr)<<(0x09))|0x0100u)|((uint16_t)0x00u);
  88. ml5238_cs(0);
  89. int ret = spi0_send_uint16(send_data, data);
  90. ml5238_cs(1);
  91. return ret;
  92. }