BQBaterryInfo

mail@pastecode.io avatar
unknown
c_cpp
a month ago
2.7 kB
13
Indexable
Never
#include <Wire.h>
#include <Arduino.h>
#define BQ20Z45_ADDRESS 0x0B  //BQ20Z45

// Definicje rejestrów
#define BATTERY_VOLTAGE_REGISTER 0x09
#define BATTERY_STATUS_REGISTER 0x16
#define REMAINING_CAPACITY_REGISTER 0x0F
#define FULL_CHARGE_CAPACITY_REGISTER 0x10
#define DESIGN_CAPACITY_REGISTER 0x18
#define DESIGN_VOLTAGE_REGISTER 0x19
#define CYCLE_COUNT_REGISTER 0x17
#define RELATIVE_STATE_OF_CHARGE_REGISTER 0x0D
#define ABSOLUTE_STATE_OF_CHARGE_REGISTER 0x0E

#define SDA_PIN 21
#define SCL_PIN 22

void setup() {
  Serial.begin(115200);
  Wire.begin(SDA_PIN, SCL_PIN);
  delay(1000); // Czas na stabilizację

  Serial.println("Init...[END] [ odczyt parametrów...]");
}

uint16_t readRegister(uint8_t reg) {
  Wire.beginTransmission(BQ20Z45_ADDRESS);
  Wire.write(reg); 
  Wire.endTransmission();
  
  Wire.requestFrom(BQ20Z45_ADDRESS, 2);  // Odczyt 2 bajtów

  if (Wire.available() == 2) {
    uint8_t msb = Wire.read();  //MSB
    uint8_t lsb = Wire.read();  // LSB
    return (msb << 8) | lsb;    // MxL
  } else {
    Serial.println("Error: Failed to read data.");
    return 0xFFFF; 
  }
}

void readBatteryData() {
  uint16_t voltage = readRegister(BATTERY_VOLTAGE_REGISTER);
  uint16_t status = readRegister(BATTERY_STATUS_REGISTER);
  uint16_t remainingCapacity = readRegister(REMAINING_CAPACITY_REGISTER);
  uint16_t fullChargeCapacity = readRegister(FULL_CHARGE_CAPACITY_REGISTER);
  uint16_t designCapacity = readRegister(DESIGN_CAPACITY_REGISTER);
  uint16_t designVoltage = readRegister(DESIGN_VOLTAGE_REGISTER);
  uint16_t cycleCount = readRegister(CYCLE_COUNT_REGISTER);
  uint8_t relativeSOC = readRegister(RELATIVE_STATE_OF_CHARGE_REGISTER) & 0xFF;  // 1 b
  uint8_t absoluteSOC = readRegister(ABSOLUTE_STATE_OF_CHARGE_REGISTER) & 0xFF;  // 1 b

  Serial.print("Napięcie baterii: ");
  Serial.print(voltage);
  Serial.println(" mV");

  Serial.print("Status baterii: 0x");
  Serial.println(status, HEX);

  Serial.print("Pozostała pojemność: ");
  Serial.print(remainingCapacity);
  Serial.println(" mAh");

  Serial.print("Pełna pojemność: ");
  Serial.print(fullChargeCapacity);
  Serial.println(" mAh");

  Serial.print("Pojemność projektowa: ");
  Serial.print(designCapacity);
  Serial.println(" mAh");

  Serial.print("Napięcie projektowe: ");
  Serial.print(designVoltage);
  Serial.println(" mV");

  Serial.print("Liczba cykli: ");
  Serial.println(cycleCount);

  Serial.print("Relatywny stan naładowania: ");
  Serial.print(relativeSOC);
  Serial.println(" %");

  Serial.print("Absolutny stan naładowania: ");
  Serial.print(absoluteSOC);
  Serial.println(" %");
}

void loop() {
  readBatteryData();
  delay(10000); 
}
Leave a Comment