Hi. I am trying to develop a function that will display a monthly calendar as part of my project.
The calendar is displaying incorrectly and I can't work out exactly what is wrong.
If anyone can give me any ideas of what to do or alternative approaches I would really appreciate it.
Thanks
#include <Arduino.h>
#include <Adafruit_GFX.h>
#include <Adafruit_ILI9341.h>
#include <RTClib.h>
#include "button.h"
#include <time.h>
const char *days[] = {"Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"};
Adafruit_ILI9341 tft = Adafruit_ILI9341(TFT_CS, TFT_DC, TFT_RST);
RTC_DS1307 rtc;
int getDaysInMonth(int year, int month)
{
if (month == 2)
{
if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0))
{
return 29; // February in a leap year
}
else
{
return 28; // February in a non-leap year
}
}
else if (month == 4 || month == 6 || month == 9 || month == 11)
{
return 30; // April, June, September, and November
}
else
{
return 31; // All other months
}
}
void drawCalendar(int currentDay, int month, int year) {
tft.setTextColor(ILI9341_WHITE);
tft.setTextSize(1);
char text[30];
int text_w, pos_x, pos_y;
int16_t x1, y1;
uint16_t w, h;
// Calculate the day of the week for the first day of the month
struct tm tm = {0};
tm.tm_mday = 1;
tm.tm_mon = month - 1; // Months are 0-based in tm structure
tm.tm_year = year - 1900; // Years are years since 1900 in tm structure
mktime(&tm); // Update the tm structure with the correct values
int firstDayOfWeek = tm.tm_wday; // Get the day of the week
int day = 1;
String str_day = (String) day;
int days_of_month = getDaysInMonth(year, month);
pos_x = 0;
pos_y = 36;
for (int i=0; i<7; i++)
{
pos_x = 104 + i*(tft.width()-108)/7;
tft.getTextBounds(days[i], 0, 0, &x1, &y1, &w, &h);
tft.print(days[i]);
tft.setCursor(pos_x+((tft.width()-100)/7-w)/2, pos_y);
}
tft.drawLine(102, 40, 260, 40, ILI9341_BLUE);
pos_y = 55;
// Skip the days before the first day of the month
for (int i=0; i<firstDayOfWeek; i++)
{
pos_x = 104 + i*(tft.width()-108)/7;
tft.setCursor(pos_x, pos_y);
tft.print(" "); // Print two spaces for empty days
}
while(day <= days_of_month)
{
for (int i=0; i<7; i++)
{
pos_x = 104 + ((i + firstDayOfWeek - 1) % 7) * (tft.width()-108)/7;
if ((day >= 1) && (day <= days_of_month))
{
tft.getTextBounds(str_day, 0, 0, &x1, &y1, &w, &h);
pos_x += (tft.width()-108)/7/2 - w/2;
tft.setCursor(pos_x, pos_y);
// highlight today with filled red circle
if (day == currentDay)
{
int cur_x = tft.getCursorX();
int cur_y = tft.getCursorY();
tft.setTextColor(ILI9341_RED);
tft.fillCircle(cur_x+6, cur_y-5, 7, ILI9341_RED);
tft.print(day);
tft.setTextColor(ILI9341_WHITE);
}
else
{
tft.print(day);
}
}
day++;
}
pos_y += 16;
}
}
void setup() {
Serial.begin(115200);
tft.begin();
rtc.begin();
drawCalendar(1, 11, 2023);
}
void loop() {
}


