How do I parse the time values received from ds1302 to be in integer format?

44 Views Asked by At

I use mbed Keil studio to write a program to read time from the ds1302 module and output it to an OLED display.

The library function signature is this

void get_time(BYTE &hour, BYTE &minute, BYTE &second)

I query the time and display it but I get a value like +0000000013 for minutes.

I can confirm that the circuit is OK because the time is continuous and the seconds are ticking but it is a matter of converting the values.

I have tried direct conversion using

int hour = hour;

Bit masking using

int hour = hour & 0xFF;

Casting using

int hour = static_cast<int>(hour);

But the output has remained the same.

The output function to display has the below signatures:

void print(int Col, int Row, const char *Text)

void print(int Col, int Row, int32_t Value)

I also tried manually eliminating the leading zeros and + sign by using the function below but it cannot compile because it says at ss.str() "Member reference base type 'std::stringstream' (aka int) is not a structure or union"

    string stripped_time(BYTE time)
    {
        std::stringstream ss;
        std::string str;

         ss << time;
         str = ss.str();

         size_t pos = str.find_first_not_of('0');
         if(pos != std::string::npos){
             str.erase(0, pos);
         }

         if(str[0] == '+'){
             str.erase(0, 1);
         }

         return str;
    }

The library I use is https://os.mbed.com/users/gcibeira/code/ds1302/

1

There are 1 best solutions below

0
On

To strip the zeros and + sign I used unsigned char minute to pass to get_time function.

From here, I created char minuteI[2]; that can hold the variable, the resulting value is then transferred using sprintf(minuteI, "%02d", minute);

I used "%02d" because I needed the value to be two digits e.g 01 even when the value is less than 10. The format to remain will only the digit is "%u".

So the result looks like this: ```c++ unsigned char hour, minute, second;

  rtcEquipment.get_time(hour, minute, second);

  char hourI[2];
  char minuteI[2];
  char secondI[2];
  char separator[3] = ":";

  sprintf(hourI, "%02d", hour);
  sprintf(minuteI, "%02d", minute);
  sprintf(secondI, "%02d", second);

Then the hourI, minuteI, and secondI contain the values in the desired format.