I need help with i2C code

I want to communicate with a vacuum cleaner battery using i2C.
I think i wrote the right code, but it keeps returning only -1. Can you help me?

#include <Wire.h>

const byte batteryAddress = 0x49;   
const byte voltageRegister = 0x09; 

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  Wire.begin();
}

void loop() {
  // put your main code here, to run repeatedly:
  float batteryVoltage = readBatteryVoltage(batteryAddress, voltageRegister);

  Serial.print("Battery Voltage: ");
  Serial.print(batteryVoltage);
  Serial.println(" V");

  delay(1000);
}

float readBatteryVoltage(int deviceAddress, byte registerAddress) 
{
  float voltage = 0.0;

  Wire.beginTransmission(deviceAddress);
  Wire.write(registerAddress);
  Wire.endTransmission();

  Wire.requestFrom(deviceAddress, 2);

  byte highByte = Wire.read();
  byte lowByte = Wire.read();

  int voltage = (highByte << 8) | (lowByte >> 8);

  return voltage;
}

Welcome to the forum.

If you haven't read it yet, read the thread:

"How to get the best out of this forum

Which "arduino" are you using?

Run I2Cscanner.ino and see if it finds the addresses of the module(s).
"Arduino Playground - I2cScanner

Check the return code.

lowByte does not deserve shifting.

2 Likes

Are you sure it's I2C; not SMBus - or even PMBus?

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.