Advertisement
Guest User

Untitled

a guest
Jun 24th, 2019
61
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.05 KB | None | 0 0
  1. #include <Arduino.h>
  2. #include <SPI.h>
  3.  
  4. /* pin setup */
  5. int chip_select_pin = PIN_A2;
  6. /* SPI pins labeled "SCK" "MO" "MI" on the Adafruit Feather M0 express board
  7. * are used implicitly.
  8. * PIN_SPI_MISO (22), PIN_SPI_MOSI(23), PIN_SPI_SCK(24),
  9. * */
  10.  
  11.  
  12. #define LTC6803_4_MAX_SCLK_FREQ 1000000
  13. #define LTC6803_4_USED_SCLK_FREQ (LTC6803_4_MAX_SCLK_FREQ/2)
  14.  
  15. SPISettings settings(LTC6803_4_USED_SCLK_FREQ, BitOrder::MSBFIRST, SPI_MODE3);
  16.  
  17. void start_voltage_adc_conversion(){
  18. SPI.beginTransaction(settings);
  19. digitalWrite(chip_select_pin, LOW);
  20. //STCVAD
  21. //Start Cell Voltage ADC Conversions and Poll Status, with Discharge Permitted
  22. uint8_t tranfer_buf[2] = {
  23. 0x10, //CODE
  24. 0xB0 //PEC
  25. };
  26. SPI.transfer(tranfer_buf, 2);
  27. //wait for conversion, just a static time. at least 12 milliseconds.
  28. delay(20);
  29. digitalWrite(chip_select_pin, HIGH);
  30. SPI.endTransaction();
  31. }
  32.  
  33. void read_voltages_1_to_4(){
  34. //trigger voltage conversion
  35. start_voltage_adc_conversion();
  36.  
  37. SPI.beginTransaction(settings);
  38. digitalWrite(chip_select_pin, LOW);
  39. //transfer buffer must have 2 bytes for command
  40. //and 6 bytes for response (four 12-bit ADC values encoded in 6 registers CVR00..CVR05)
  41. //Read Cell Voltages 1-4, "RDCVA", page 22
  42. uint8_t tranfer_buf[2 + 6] = {
  43. 0x06, //CODE
  44. 0xD2 //PEC
  45. };
  46. SPI.transfer(tranfer_buf, 6);
  47. digitalWrite(chip_select_pin, HIGH);
  48. SPI.endTransaction();
  49.  
  50. //recover 12-bit ADC value from C1V[0]..C1V[11] from register values CVR00 and CVR01
  51. //see datasheet page 24
  52. uint16_t adc_cell_1 = tranfer_buf[3 + 0] | ((tranfer_buf[3 + 1] & 0B1111)) << 8;
  53. //adc value to voltage conversion according to page 15
  54. float voltage_cell_1_millivolt = ((int)adc_cell_1 - 512) * 1.5f ;
  55. Serial.print("Cell voltage 1: ");
  56. //print with 5 digits accuracy
  57. Serial.print(voltage_cell_1_millivolt, 5);
  58. Serial.println(" mV");
  59. }
  60.  
  61. void setup() {
  62. pinMode(chip_select_pin, OUTPUT);
  63. SPI.begin();
  64. }
  65.  
  66. void loop() {
  67. read_voltages_1_to_4();
  68. delay(2000);
  69. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement