10 years, 10 months ago.

General c++ question

I have a question that is very easy for most (but not me).

I need to use two 8 bit i2c registers to count beyond 255.

These register are 8 bit (d0 - d7), that will give me a maximum count of 255, however I want to record values beyond this. So I have the second 8 bit register to use.

My question is what is the best c code to use both register to store values beyond 255.

I can write and read from both no problem its the maths part I'm not sure on. Do I multiple one register by 255 and add the second like below or is there a better way.

This works but messy

#include "mbed.h"

// Write code

    rst[0]=0x10;
    rst[1]=(rtcset_times >>8);
    i2c.write(0xD0,rst,2); 
    rst[0]=0x11;
    rst[1]=(rtcset_times & 0xFF);
    i2c.write(0xD0,rst,2); 

// Read code

    set[0]=0x10;
    i2c.write(0xD0,set,1);
    i2c.read(0xD0,cmd,1);
    rtcset_times=cmd[0]*255;
    set[0]=0x11;
    i2c.write(0xD0,set,1);
    i2c.read(0xD0,cmd,1);    
    rtcset_times=rtcset_times+cmd[0];

How would I write this in a 'propper' way?

Thank you

1 Answer

10 years, 10 months ago.

It looks to be close to the proper way. I assume 0x10 and 0x11 are internal addresses in the device? Normally they auto-increment their address pointer. So if you write another value, it will be stored to the next location (same for reading). So you could also do:

//rst must be 3 long
rst[0]=0x10;
rst[1]=rtcset_times >> 8;
rst[2]=rtcset_times & 0xFF;

i2c.write(0xD0, rst, 3);

And for reading something like:

//cmd must be 2 long
set[0] = 0x10;
i2c.write(0xD0, set, 1);
i2c.read(0xD0, cmd, 2);
rtcset_times = (cmd[0] << 8) + cmd[1];

You can also play around with pointers to do it, but this is the standard way.

Accepted Answer

Thank you Erik (again) this does help me get to grips with 'long hand code' to 'short hand code'.

Further to this, I timed the two methods and found that your code took 403uS to execute where mine takes 616uS. That's 50% faster. A good example of poor and good code practice.

posted by Paul Staron 12 Jun 2013