AdSense

Sunday, 2 March 2014

Register pointer - accessing specific registers via I2C with Arduino

(Deutsche Version) Sometimes when using I2C you want to access a specific register of your I2C-save for reading and writing, e.g. when usingthe real time clock DS1307. This can be done using the so called register pointers. As you cann guess by the name, these pointers point to the register you want to read or write.

This is pretty easy to use: when writing via I2C, the first byte written with the write()-command sets the register pointer to the desired register. An example using the DS1307:
  Wire.beginTransmission(DS1307_ADDRESS);
  Wire.write(0x02); //set pointer to register 2
  Wire.write(decToBcd(hour)); //write value for hours in register 2
  Wire.write(decToBcd(weekDay)); //write value for weekday in register 3    
  Wire.endTransmission();

The first byte written after beginTransmission() sets the pointer to register 2 (where the hours are stored). With the second write()-command the value itself is written to the register. Then the pointer is automatically set to the next register, so the following write()-command writes to register 3.

Reading data from a specific register works similar:

  Wire.beginTransmission(DS1307_ADDRESS);
  Wire.write(0x02); //set pointer to register 2
  Wire.endTransmission();

  Wire.requestFrom(DS1307_ADDRESS, 7);//begin data request from register 2
  int hour = bcdToDec(Wire.read()); //read hours from register 2
  int weekDay = bcdToDec(Wire.read()); //read weekday from register 3
  
Like in the first example, the pointer is set to register 2. Then we can request data using the reguestFrom()-command. After that, read() reads data from register 2. After reading, the pointer is automatically set to the next register, so the following read()-command reads from register 3.

No comments:

Post a Comment