Search code examples
cgccavr-gccatmega

Day of Week function not working as intended in Atmega8


I have a C function that finds the Day of the week if given the complete date. This function works perfectly when I compile it on my laptop using gcc.

But when I compile the function for the Atmega8 using avr-gcc it gives the wrong answer. Could anyone help me figure out why?

Here's the C function

unsigned char *getDay(int year, int month, int day) {
static unsigned char *weekdayname[] = {"MON", "TUE",
    "WED", "THU", "FRI", "SAT", "SUN"};
size_t JND =                                                     \
      day                                                      \
    + ((153 * (month + 12 * ((14 - month) / 12) - 3) + 2) / 5) \
    + (365 * (year + 4800 - ((14 - month) / 12)))              \
    + ((year + 4800 - ((14 - month) / 12)) / 4)                \
    - ((year + 4800 - ((14 - month) / 12)) / 100)              \
    + ((year + 4800 - ((14 - month) / 12)) / 400)              \
    - 32045;
return weekdayname[JND % 7];
}

For example, when I enter the date 01/01/2015 into the function on a laptop the function gives me the correct day of the week (Thursday) but on the atmega8 it gives me Monday.

Update: The function sujithvm gave works! :D

But I still have no clue why the original function doesn't work on the avr. I tried uint32_t and int32_t. However, it looks like the day is always off by 3. Adding three to JND gives the correct day. That's a bit strange.


Solution

  • Try using this code

    unsigned char *getDay(int y, int m, int d) {
        static unsigned char *weekdayname[] = {"SUN", "MON", "TUE", "WED", "THU", "FRI", "SAT"};
    
        int weekday  = (d += m < 3 ? y-- : y - 2 , 23 * m / 9 + d + 4 + y / 4 - y / 100 + y / 400) % 7;
        return weekdayname[weekday];
    }