AtMega 2560 + 2.8 TFT touch Shield + SD card == Problem

Adafruit Ethernet, Motor, Proto, Wave, Datalogger, GPS Shields - etc!

Moderators: adafruit_support_bill, adafruit

Please be positive and constructive with your questions and comments.
Locked
ddutch2001
 
Posts: 11
Joined: Tue Oct 04, 2011 3:41 am

AtMega 2560 + 2.8 TFT touch Shield + SD card == Problem

Post by ddutch2001 »

While using an Atmega2560 plus the 2.8 TFT Touch shield, I have problems when writing to the 2 Gb SD card. I ran the TFT_BMP_Shield example and had no problem to display the tiger.bmp (after I made the required changes in the header files).

In fact I can write to the SD card BUT .... only one time. After writing once to a certain file, I cannot add/write more to that same file. Thus only the first message ("System started") is written to the log-file. Subsequent calls to write2RunLog() will cause error messages ("Can't open run.log").

Actually I can write once per session because each time that I reboot the Arduino, the "System started" message is correctly written (but no more than that, although more calls to write2RunLog() are made).


Below a part of the code that I use:

Code: Select all

void setup(void)
{
    ............
    ............
    ............

    Wire.begin();
    delay(10);

    pinMode(pinSSR, OUTPUT);
    digitalWrite(pinSSR, LOW);

    pinMode(pinVccDS1307, OUTPUT); // always on
    digitalWrite(pinVccDS1307, HIGH);

    pinMode(pinBackLite, OUTPUT);
    digitalWrite(pinBackLite, HIGH);
    backLiteIsOn = true;
    touchedPrev = touchedCur = millis();

    tft.reset();
    uint16_t identifier = tft.readRegister(0x0);

    tft.setRotation(1);
    tft.initDisplay();

    getCurrentDateTime(&theDateTime);

    pinMode(SD_CS, OUTPUT);
    disableSPI();
    
    if (!SD.begin(SD_CS))
    {
        showErrorMsg(MAIN_MENU, "Cannot find SD card !", "");
        delay(2500);
        sdCardPresent = false;
    }
    else
    {
        sdCardPresent = true;
        write2RunLog("System started");
    }

    readSettingsFromEeprom();

    current_menu = MAIN_MENU;
    prev_menu = -1;

    showMainMenu(-1);
}




boolean write2RunLog(char *theMsg)
{
    File runFile;
    boolean ret = false;
    char outMsg[80];
    boolean spiEnabled = false;

    if (sdCardPresent)
    {
        enableSPI();
        spiEnabled = true;

        runFile = SD.open("/run.log", FILE_WRITE);
        if(runFile)
        {
            sprintf(outMsg,"%s ==> %s !\n", theDateTime.timeString, theMsg);
            runFile.write(outMsg);
            runFile.close();
        }
        else
        {
            disableSPI();
            spiEnabled = false;
            showErrorMsg(MAIN_MENU, "Can't open run.log","");
            delay(2500);
        }
        ret = true;
    }
    else
    {
        disableSPI();
        spiEnabled = false;
        showErrorMsg(MAIN_MENU, "No SD card !","");
        delay(2500);
    }

    if(spiEnabled)
        disableSPI();

    return(ret);
}

Any suggestions ?

Thanks !

User avatar
adafruit_support_bill
 
Posts: 88088
Joined: Sat Feb 07, 2009 10:11 am

Re: AtMega 2560 + 2.8 TFT touch Shield + SD card == Problem

Post by adafruit_support_bill »

Once you disable the SPI, you need to call SD.begin() again.

ddutch2001
 
Posts: 11
Joined: Tue Oct 04, 2011 3:41 am

Re: AtMega 2560 + 2.8 TFT touch Shield + SD card == Problem

Post by ddutch2001 »

I did what you suggested but the same problem is still there.
I changed my code, see below:

Code: Select all

void setup(void)
{
    .........
    .........
    .........
    pinMode(SD_CS, OUTPUT);
    write2RunLog("System started");
    .........
    .........
}



boolean write2RunLog(char *theMsg)
{
    File runFile;
    boolean ret = false;
    char outMsg[80];
    boolean spiEnabled = false;

    disableSPI();

    if (!SD.begin(SD_CS))
    {
        showErrorMsg(MAIN_MENU, "Cannot find SD card !", "");
        delay(2500);
    }
    else
    {
        enableSPI();
        spiEnabled = true;

        runFile = SD.open("/run.log", FILE_WRITE);
        if(runFile)
        {
            sprintf(outMsg,"%s ==> %s !\n", theDateTime.timeString, theMsg);
            runFile.write(outMsg);
            runFile.close();
            ret = true;
        }
        else
        {
            disableSPI();
            spiEnabled = false;
            showErrorMsg(MAIN_MENU, "Can't open run.log","");
            delay(2500);
        }
    }

    if(spiEnabled)
        disableSPI();

    return(ret);
}
Also if I place the spiEnabled() call before the call to SD.begin(), the problem remains. Still the very first call to write2RunLog() is always succesfull but subsequent calls generate the error message; SD.begin() is unsuccesfull, thus the message is: "Cannot find SD card !"
:?:

User avatar
adafruit_support_bill
 
Posts: 88088
Joined: Sat Feb 07, 2009 10:11 am

Re: AtMega 2560 + 2.8 TFT touch Shield + SD card == Problem

Post by adafruit_support_bill »

I have a 2650 with a touch shield here. If you post your complete code I will load it up and see what I can find.

ddutch2001
 
Posts: 11
Joined: Tue Oct 04, 2011 3:41 am

Re: AtMega 2560 + 2.8 TFT touch Shield + SD card == Problem

Post by ddutch2001 »

Hi AdaFruit,
below, you'll find the code (which is not finished yet). You mightwant to cut out some parts.
I use Arduino v.0022
Regards,

Code: Select all

#include <string.h>
#include <TFTLCD.h>

#include <TouchScreen.h>
#include <EEPROM.h>
#include "Wire.h"
#include <SD.h>
#include <SPI.h>

typedef struct CURRENT_DTime
{
    int second;     //0-59
    int minute;     //0-59
    int hour;       //0-23
    int weekDay;    //Maandag = 1 -- Zondag = 7
    int monthDay;   //1-31
    int month;      //1-12
    int year;       //2012; //0-99
    char timeString[40];
} CURRENT_DTime;


typedef struct PERIOD2RUN
{
    int startHour;
    int startMinute;
    int stopHour;
    int stopMinute;
} PERIOD2RUN;





/* ************************* Defines LCD/Touchscreen ******************** */
#define LCD_CS A3    // Chip Select goes to Analog 3
#define LCD_CD A2    // Command/Data goes to Analog 2
#define LCD_WR A1    // LCD Write goes to Analog 1
#define LCD_RD A0    // LCD Read goes to Analog 0


//SD card
#define SD_CS 10     // Set the chip select line to whatever you use (10 doesnt conflict with the library)


// you can also just connect RESET to the arduino RESET pin
#define LCD_RESET A4

// Color definitions
#define	BLACK           0x0000
#define	BLUE            0x001F
#define	RED             0xF800
#define	GREEN           0x07E0
#define CYAN            0x07FF
#define MAGENTA         0xF81F
#define YELLOW          0xFFE0
#define WHITE           0xFFFF

#define TS_MINX 152
#define TS_MINY 85
#define TS_MAXX 966
#define TS_MAXY 922

#define MINPRESSURE  100
#define MAXPRESSURE 2000

// These are the pins for the shield!
#define YP A1  // must be an analog pin, use "An" notation!
#define XM A2  // must be an analog pin, use "An" notation!
#define YM 7   // can be a digital pin
#define XP 6   // can be a digital pin
/*  --------------------------------------------------------------------------------- */





/* ********************************* Defines for DS1307 (clock) ******************** */
#define DS1307_ADDRESS 0x68
/*  --------------------------------------------------------------------------------- */





/* ********************************* Defines for User-interface/Menues ******************** */
#define MAX_IDLE_TIME 420000UL  /* 7 minutes == 1000 x (7 x 60) == 420000 msecs */

#define MAIN_MENU       100
#define SETTIME_MENU    0
#define SETPERIOD_MENU  1
#define CALIBRATE_MENU  2
#define BANNED_MENU    3
#define VIEWLOG_MENU    4
#define OFF_MENU        5


// Actions at setDate-Time menu
#define INC_DayOfW  1
#define INC_DayOfM  2
#define INC_Month   3
#define INC_Year    4
#define DEC_DayOfW  5
#define DEC_DayOfM  6
#define DEC_Month   7
#define DEC_Year    8

#define INC_Hour    9
#define INC_Minute	10
#define DEC_Hour   	11
#define DEC_Minute	12

#define SETTIME_Done    13
#define SETTIME_Cancel  14


// Actions at set Start/Stop Time menu
#define INC_Start_Hour		15
#define INC_Start_Minute	16
#define DEC_Start_Hour		17
#define DEC_Start_Minute	18

#define INC_Stop_Hour   19
#define INC_Stop_Minute 20
#define DEC_Stop_Hour   21
#define DEC_Stop_Minute 22

#define SETSTST_Done    23
#define SETSTST_Cancel  24
// End Actions at set Start/Stop Time menu



// Actions at Calibrate menu
#define CAL_Done    25
#define CAL_Cancel  26
// End Actions at Calibrate menu



/*  --------------------------------------------------------------------------------- */






/* ************************* Globals for LCD/Touchscreen ******************** */
Point p;

TFTLCD tft(LCD_CS, LCD_CD, LCD_WR, LCD_RD, LCD_RESET);
TouchScreen ts = TouchScreen(XP, YP, XM, YM, 300);

unsigned int colorAr[8];

int pinBackLite = 3;
boolean backLiteIsOn = true;
/*  --------------------------------------------------------------------------------- */






/* ********************************* Globals for DS1307 (clock & timer) ******************** */
int pinVccDS1307 = 22;
char *days[] = { "", "Mon","Tue", "Wed", "Thu", "Fri", "Sat", "Sun"};
char *months[] = {"","Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};

CURRENT_DTime theDateTime, tmpDateTime;
PERIOD2RUN theRuntime, tmpRuntime;

boolean runManual = false, switchedOff = false;

/*  --------------------------------------------------------------------------------- */






/* ********************************* Globals for User-interface/Menues ******************** */
char *mMenuMsg[] = {" SET CURRENT DATE/TIME",
                    " SET START/STOP TIME",
                    " CALIBRATE",
                    " RUN AUTO or MANUAL",
                    " VIEW LOG",
                    " OFF"};


int mMenuChoice[] = {SETTIME_MENU,
                     SETPERIOD_MENU,
                     CALIBRATE_MENU,
                     BANNED_MENU,
                     VIEWLOG_MENU,
                     OFF_MENU
                     };

int xOrgMmenu[6], yOrgMmenu[6];




char *setTimeMsg[]      = {"  +     +    +     +",
						   " Sun   11   Dec   2011",
                           "  -     -    -     -",
                           "  +    +",
                           " 17 : 41",
						   "  -    -",
                           "    DONE ",
						   "    CANCEL"};

int setTimeXorg[7];
int setTimeYorg[7];
boolean errorSetDateTime    = false;
boolean errorStartStopTime = false;


int setStStXorg[7];
int setStStYorg[7];


char *setStartStopMsg[] = {" SET START TIME",
                           "  +    +",
                           " 17 : 41",
						   "  -    -",
						   " SET STOP TIME",
                           "  +    +",
                           " 17 : 41",
						   "  -    -",
                           "    DONE ",
						   "    CANCEL"};




char *calibrateMsg[]    = {" During calibration, power",
                           " will be switched on a few",
                           " seconds while the current",
                           " per phase will be sampled",
                           " ",
                           " During normal runtime the",
                           " samples can indicate if",
                           " problems exist with power",
                           " supply, pipes or borehole",
                           " ",
                           "     START     CANCEL"};


char *BANNED[]   = {" Manual - Start Now (settings for start- and stoptime are ignored)",
                           " Auto   - according to the start- and stoptimes set by you"};
char *viewLogMsg[]      = {" View error and/or warning messages"};
char *viewOffMsg[]      = {" Are you sure ? "};

char timeString[32];

int current_menu, prev_menu;

boolean doShowMessage = false;
/*  --------------------------------------------------------------------------------- */






/* ********************************* Globals for Solid State Relais (SSR) ******************** */
int pinSSR    = 23;  // runs the solid state relais (which turns on/of the main power contactor)
boolean SSRisOn = false;
/*  --------------------------------------------------------------------------------- */




/* ******************************** Misc.  Globals ************************************** */
unsigned long startMillis = 0UL, endMillis = 0UL, touchedPrev = 0UL, touchedCur = 0L;
boolean sdCardPresent = false;

/*  --------------------------------------------------------------------------------- */


int8_t saved_spimode;

void disableSPI(void) {
  saved_spimode = SPCR;
  SPCR = 0;
}

void enableSPI(void) {
  SPCR = saved_spimode;
}



/* *********** Global Variables for ACS756 current sensors, 1 per phase (RED, Blue and Yellow) ******* */
int pinInRedAcs756 = 13, pinInBlueAcs756 = 14, pinInYellowAcs756 = 15;
int pinFeedAcs756 = 50;
/*  --------------------------------------------------------------------------------- */


byte decToBcd(byte val)
{
// Convert normal decimal numbers to binary coded decimal
  return ( (val/10*16) + (val%10) );
}

byte bcdToDec(byte val)
{
// Convert binary coded decimal to normal decimal numbers
  return ( (val/16*10) + (val%16) );
}



void mkTimeString(struct CURRENT_DTime *dattim)
{
    sprintf(dattim->timeString,"%s %d %s 20%02d - %02d:%02d:%02d", days[dattim->weekDay], dattim->monthDay,
            months[dattim->month], dattim->year, dattim->hour, dattim->minute, dattim->second);
}



void setDateTime(struct CURRENT_DTime *dattim)
{
    Wire.beginTransmission(DS1307_ADDRESS);
    Wire.send(0); //stop Oscillator
    if((dattim->second > 59) || (dattim->second < 0))
		dattim->second = 0;

    Wire.send(decToBcd((byte) dattim->second));
    Wire.send(decToBcd((byte) dattim->minute));
    Wire.send(decToBcd((byte) dattim->hour));
    Wire.send(decToBcd((byte) dattim->weekDay));
    Wire.send(decToBcd((byte) dattim->monthDay));
    Wire.send(decToBcd((byte) dattim->month));
    Wire.send(decToBcd((byte) dattim->year));

    Wire.send(0); //start

    Wire.endTransmission();
}




void getCurrentDateTime(struct CURRENT_DTime *dattim)
{
    // Reset the register pointer
    Wire.beginTransmission(DS1307_ADDRESS);
    Wire.send(0);
    Wire.endTransmission();
    Wire.requestFrom(DS1307_ADDRESS, 7);

    dattim->second   = bcdToDec(Wire.receive());
    dattim->minute   = bcdToDec(Wire.receive());
    dattim->hour     = bcdToDec(Wire.receive() & 0b111111); //24 hour time
    dattim->weekDay  = bcdToDec(Wire.receive()); //0-6 -> sunday - Saturday
    dattim->monthDay = bcdToDec(Wire.receive());
    dattim->month    = bcdToDec(Wire.receive());
    dattim->year     = bcdToDec(Wire.receive());

    mkTimeString(dattim);
}






int howManyMinutes(int beginHour, int beginMinute, int endHour, int endMinute)
{
    int minutesRunTime = 0, hoursRunTime;
    int hoursFraction, minutesFraction;

    if (beginHour == endHour)
    {
        if(beginMinute == endMinute)
            minutesRunTime = 0;
        else
        {
            if(beginMinute > endMinute)
            {
                minutesRunTime = 23 * 60; // 23 hours
                minutesRunTime += 60 - (beginMinute - endMinute);
            }
            else
                minutesRunTime = endMinute - beginMinute;
        }
    }
    else
    {
        if(beginHour > endHour)
        {
            hoursRunTime = 24 - (beginHour - endHour);
            minutesRunTime = hoursRunTime * 60;

            if(beginMinute > endMinute)
                minutesRunTime -= (beginMinute - endMinute);
            if(beginMinute < endMinute)
                minutesRunTime += (endMinute - beginMinute);
        }
        else // beginHour < endHour
        {
            hoursRunTime = endHour - beginHour;
            minutesRunTime = hoursRunTime * 60;

            if(beginMinute > endMinute)
                minutesRunTime -= (beginMinute - endMinute);
            if(beginMinute < endMinute)
                minutesRunTime += (endMinute - beginMinute);
        }
    }

    return(minutesRunTime);
}






boolean checkTime2Run()
{
    int minutesRunTime, minutesNow2EndTime;

    minutesRunTime = howManyMinutes(theRuntime.startHour, theRuntime.startMinute,
                                    theRuntime.stopHour, theRuntime.stopMinute);

    if(minutesRunTime == 0)
        return(false);

    minutesNow2EndTime = howManyMinutes(theDateTime.hour, theDateTime.minute,
                                        theRuntime.stopHour, theRuntime.stopMinute);

    return((minutesRunTime - minutesNow2EndTime) > 0);
}


/* ********************************* End DS1307 ******************** */








void toggleBackLite()
{
    if(backLiteIsOn)
    {
        digitalWrite(pinBackLite, LOW);
        backLiteIsOn = false;
    }
    else
    {
        digitalWrite(pinBackLite, HIGH);
        backLiteIsOn = true;
    }
}



void toggleSSR()
{
    if(SSRisOn)
    {
        digitalWrite(pinSSR, LOW);
        SSRisOn = false;
    }
    else
    {
        digitalWrite(pinSSR, HIGH);
        SSRisOn = true;
    }
}








void showStStMsg(char *msg1, char *msg2)
{
    int curX, curY;

    doShowMessage = true;

    tft.fillScreen(BLACK);
    tft.setCursor(0,0);
    tft.println("");
    tft.println("");
	tft.println("");


    tft.print("    ");
    curX = tft.getCurPosX();
    curY = tft.getCurPosY();
    tft.setTextSize(2);
    tft.setTextColor(BLACK);

    tft.drawRect(curX-12, curY, tft.width()-50, 160, WHITE);
    tft.fillRect(curX-10, curY+2, tft.width()-54, 154, GREEN);

    tft.println("");
    tft.print("     * Runtime set *");

    tft.println("");
    tft.println("");
    tft.print("     ");
    tft.println(msg1);
    tft.println("");
    tft.print("     ");

    tft.setTextSize(1);
    tft.setTextColor(BLACK);
    if(msg1 != (char *) NULL)
	   tft.println(msg2);

    tft.setTextSize(2);
}



int processStartStopSettings(int beginHour, int beginMinute, int endHour, int endMinute, char *msg)
{
    int minutesRunTime;
    int hoursFraction, minutesFraction;

    minutesRunTime = howManyMinutes(beginHour, beginMinute, endHour, endMinute);

    if(minutesRunTime == 0)
        sprintf(msg, "Invalid runtime:\n\n      -- 0 minutes --\n");
    else
    {
        hoursFraction = minutesRunTime / 60;
        minutesFraction = minutesRunTime % 60;
        sprintf(msg,"Runtime is:\n\n     %2d hrs and %02d min\n",hoursFraction, minutesFraction);
    }

    return(minutesRunTime);
}






void showErrorMsg(int callingMenu, char *msg1, char *msg2)
{
    int curX, curY;

    tft.fillScreen(BLACK);
    tft.setCursor(0,0);
    tft.println("");
    tft.println("");
	tft.println("");


    tft.print("    ");
    curX = tft.getCurPosX();
    curY = tft.getCurPosY();
    tft.setTextSize(2);
    tft.setTextColor(WHITE);

    tft.drawRect(curX-12, curY, tft.width()-50, 160, YELLOW);
    tft.fillRect(curX-10, curY+2, tft.width()-54, 154, RED);

    tft.println("");
    tft.print("     *** E R R O R ***");

    tft.println("");
    tft.println("");
    tft.print("     ");
    tft.println(msg1);
    tft.println("");
    tft.print("     ");

    tft.setTextSize(1);
    tft.setTextColor(BLACK);
    if(msg1 != (char *) NULL)
	    tft.println(msg2);

    tft.setTextSize(2);

    current_menu = callingMenu;

	//processMenuChoice(mMenuChoice[i]);
}





void processChoice(int menuOption)
{
    if(menuOption == 5)
        tft.fillScreen(BLACK);
}



void showMainMenu(int curMenuSelection)
{
    int i;
    int curX, curY;
    int nMenuOptions = 6;

    current_menu = MAIN_MENU;
    doShowMessage = false;

    if(curMenuSelection < -1)
        return;

    if(curMenuSelection == -1) // only at first call
    {
        tft.fillScreen(BLUE);
        tft.setCursor(0,0);

        curX = tft.getCurPosX();
        curY = tft.getCurPosY();

        tft.drawRect(1, curY+2, tft.width()-2, 200, RED);
        tft.fillRect(2, curY+4, tft.width()-4, 196, BLUE);

        getCurrentDateTime(&theDateTime);
        showTime(theDateTime.timeString);
    }

    tft.setCursor(0,0);
    tft.setTextSize(2);
    tft.setTextColor(YELLOW);

    for(i = 0;i < nMenuOptions;i++)
    {
        if(curMenuSelection == -1) // only at first call, just to present this menu
        {
   			tft.println(" ");
            tft.println(mMenuMsg[i]);
        }
        else	// if a certain choice has been made within this menu
        {
            if(i == curMenuSelection)
            {
	          current_menu = mMenuChoice[i];
    		  processMenuChoice(mMenuChoice[i]);
	break;
            }
        }
    }
}


boolean checkDate(int mnth, int mday, int yr, char *returnMsg)
{
	int     leap1;
	int     leap2;
	int     leap3;

	boolean isLeapYear = false;

	if(mday <= 28)
		return(true);

	if ((mnth == 2) && (mday > 28)) // Febr
	{
		if (mday > 29)
		{
			sprintf(returnMsg,"Invalid Date.\n     This month doesn't\n     have %d days !", mday);
			return(false);
		}

		/*A leapyear is any year divisible by 4, unless the year is divisible by 100 but not 400.*/
		leap1 = yr % 4;
		leap2 = yr % 100;
		leap3 = yr % 400;

		if (leap3 == 0 || (leap2 != 0 && leap1 == 0))
			isLeapYear = true;

		if (! isLeapYear)
		{
			sprintf(returnMsg,"Invalid Date.\n     This month has\n     only 28 days !");

			return(false);
		}
		else
			return(true);
	}


	if(mday > 30)
	{
		if ((mnth == 4) || (mnth == 6) || (mnth == 9) || (mnth == 11))
		{
			sprintf(returnMsg,"Invalid Date.\n     this month has only\n     30 days !");
			return(false);
		}
	}

	return(true);
}



void get12HrsClock(int hrs, int mins, char *dat)
{
	int h12;
	char pm[3], am[3], *tod;

	strcpy(pm,"PM");
	strcpy(am,"AM");

	if(hrs < 12)
	{
		tod = am;
		if(hrs == 0)
			h12 = 12;
		else
			h12 = hrs;
	}
	else
	{
		tod = pm;
		h12 = hrs - 12;
	}

	sprintf(dat,"    = %02d:%02d %2s", h12, mins, tod);
}




void showSetTimeMenu(int curMenuSelection)
{
    int curX, curY;
	char dataStr[48];
	char dateErrStr[128];

	current_menu = SETTIME_MENU;
    doShowMessage = false;

    if(curMenuSelection < -1)
        return;

	tft.setTextSize(2);

    if((curMenuSelection == -1) || (errorSetDateTime))// only at first call
    {
        getCurrentDateTime(&tmpDateTime);

		errorSetDateTime = false;

        tft.fillScreen(BLUE);
        tft.setCursor(0,0);

        curX = tft.getCurPosX();
        curY = tft.getCurPosY();

        tft.drawRect(1, curY+2, tft.width()-2, 200, RED);
        tft.fillRect(2, curY+4, tft.width()-4, 196, BLUE);

	    tft.setCursor(0,0);
    	tft.setTextSize(1);
    	tft.setTextColor(WHITE);
   		tft.println("Set current date and time");

    	tft.setTextSize(2);
    	tft.setTextColor(YELLOW);
		tft.println("");

		tft.println(setTimeMsg[0]); // "  +     +    +     +"

		setTimeXorg[0] = tft.getCurPosX();
		setTimeYorg[0] = tft.getCurPosY();
		sprintf(dataStr," %3s", days[tmpDateTime.weekDay]);
		tft.print(dataStr);

		setTimeXorg[1] = tft.getCurPosX();
		setTimeYorg[1] = tft.getCurPosY();
		sprintf(dataStr,"   %2d", tmpDateTime.monthDay);
		tft.print(dataStr);

		setTimeXorg[2] = tft.getCurPosX();
		setTimeYorg[2] = tft.getCurPosY();
		sprintf(dataStr,"   %3s", months[tmpDateTime.month]);
		tft.print(dataStr);

		setTimeXorg[3] = tft.getCurPosX();
		setTimeYorg[3] = tft.getCurPosY();
		sprintf(dataStr,"   %4d", tmpDateTime.year);
		tft.println(dataStr);

		tft.println(setTimeMsg[2]); // "  -     -    -     -"
        tft.println("");
   	    tft.println("");

		tft.println(setTimeMsg[3]); // "  +    +"

		setTimeXorg[4] = tft.getCurPosX();
		setTimeYorg[4] = tft.getCurPosY();
		sprintf(dataStr," %02d", tmpDateTime.hour);
		tft.print(dataStr);

		tft.print(" : ");

		setTimeXorg[5] = tft.getCurPosX();
		setTimeYorg[5] = tft.getCurPosY();
		sprintf(dataStr,"%02d", tmpDateTime.minute);
		tft.print(dataStr);


		setTimeXorg[6] = tft.getCurPosX();
		setTimeYorg[6] = tft.getCurPosY();

		get12HrsClock(tmpDateTime.hour, tmpDateTime.minute, dataStr);
		tft.println(dataStr);

		tft.println(setTimeMsg[5]); // "  -    -"

   		tft.println("");
   		tft.println("    DONE     CANCEL");

		return;

    }

	switch(curMenuSelection)
	{
		case INC_DayOfW:
			if(tmpDateTime.weekDay == 7)
				tmpDateTime.weekDay = 1;
			else
				++tmpDateTime.weekDay;

			sprintf(dataStr," %3s", days[tmpDateTime.weekDay]);
			tft.fillRect(setTimeXorg[0], setTimeYorg[0] , 50 , 20, BLUE);
	    	tft.setCursor(setTimeXorg[0], setTimeYorg[0]);
			delay(20);
			tft.print(dataStr);
		break;

		// Nog controleren of max. dag vd maand klopt (30, 301, 28/29 - schrikkeljaar)
		case INC_DayOfM:
			if(tmpDateTime.monthDay < 31)
				++tmpDateTime.monthDay;
			else
				tmpDateTime.monthDay = 1;

			sprintf(dataStr,"   %2d", tmpDateTime.monthDay);
			tft.fillRect(setTimeXorg[1], setTimeYorg[1] , 70 , 20, BLUE);
    		tft.setCursor(setTimeXorg[1], setTimeYorg[1]);
			delay(20);
			tft.print(dataStr);
		break;

		case INC_Month:
			if(tmpDateTime.month < 12)
				++tmpDateTime.month;
			else
				tmpDateTime.month = 1;

			sprintf(dataStr,"   %3s", months[tmpDateTime.month]);
			tft.fillRect(setTimeXorg[2], setTimeYorg[2] , 70 , 20, BLUE);
	   		tft.setCursor(setTimeXorg[2], setTimeYorg[2]);
			delay(20);
			tft.print(dataStr);
		break;

		case INC_Year:
			if(tmpDateTime.year < 98)
			{
				++tmpDateTime.year;
				sprintf(dataStr,"   20%2d", tmpDateTime.year);
				tft.fillRect(setTimeXorg[3], setTimeYorg[3] , 90 , 20, BLUE);
	    		tft.setCursor(setTimeXorg[3], setTimeYorg[3]);
				delay(20);
				tft.println(dataStr);
			}
		break;

		case DEC_DayOfW:
			if(tmpDateTime.weekDay == 1)
				tmpDateTime.weekDay = 7;
			else
				--tmpDateTime.weekDay;

			sprintf(dataStr," %3s", days[tmpDateTime.weekDay]);

			tft.fillRect(setTimeXorg[0], setTimeYorg[0] , 60 , 20, BLUE);
	    	tft.setCursor(setTimeXorg[0], setTimeYorg[0]);
			delay(20);
			tft.print(dataStr);
		break;

		case DEC_DayOfM:
			if(tmpDateTime.monthDay > 1)
				--tmpDateTime.monthDay;
			else
				tmpDateTime.monthDay = 31;

			sprintf(dataStr,"   %2d", tmpDateTime.monthDay);
			tft.fillRect(setTimeXorg[1], setTimeYorg[1] , 70 , 20, BLUE);
    		tft.setCursor(setTimeXorg[1], setTimeYorg[1]);
			delay(20);
			tft.print(dataStr);
		break;

		case DEC_Month:
			if(tmpDateTime.month > 1)
				--tmpDateTime.month;
			else
				tmpDateTime.month = 12;

			sprintf(dataStr,"   %3s", months[tmpDateTime.month]);
			tft.fillRect(setTimeXorg[2], setTimeYorg[2] , 70 , 20, BLUE);
    		tft.setCursor(setTimeXorg[2], setTimeYorg[2]);
			delay(20);
			tft.print(dataStr);
		break;

		case DEC_Year:
			if(tmpDateTime.year > 12)
			{
				--tmpDateTime.year;
				sprintf(dataStr,"   20%2d", tmpDateTime.year);
				tft.fillRect(setTimeXorg[3], setTimeYorg[3] , 90 , 20, BLUE);
	    		tft.setCursor(setTimeXorg[3], setTimeYorg[3]);
				delay(20);
				tft.println(dataStr);
			}
		break;

		case INC_Hour:
			if(tmpDateTime.hour < 23)
				++tmpDateTime.hour;
			else
				tmpDateTime.hour = 0;

			sprintf(dataStr," %02d", tmpDateTime.hour);
			tft.fillRect(setTimeXorg[4], setTimeYorg[4] , 50 , 20, BLUE);
	   		tft.setCursor(setTimeXorg[4], setTimeYorg[4]);
			delay(20);
			tft.print(dataStr);

			tft.fillRect(setTimeXorg[6], setTimeYorg[6] , 180 , 20, BLUE);
	   		tft.setCursor(setTimeXorg[6], setTimeYorg[6]);

			get12HrsClock(tmpDateTime.hour, tmpDateTime.minute, dataStr);
			tft.println(dataStr);

		break;

		case INC_Minute:
			if(tmpDateTime.minute < 59)
				++tmpDateTime.minute;
			else
				tmpDateTime.minute = 0;

			sprintf(dataStr,"%02d", tmpDateTime.minute);
			tft.fillRect(setTimeXorg[5], setTimeYorg[5] , 50 , 20, BLUE);
	   		tft.setCursor(setTimeXorg[5], setTimeYorg[5]);
			delay(5);
			tft.print(dataStr);

			tft.fillRect(setTimeXorg[6], setTimeYorg[6] , 180 , 20, BLUE);
	   		tft.setCursor(setTimeXorg[6], setTimeYorg[6]);

			get12HrsClock(tmpDateTime.hour, tmpDateTime.minute, dataStr);
			tft.println(dataStr);
		break;

		case DEC_Hour:
			if(tmpDateTime.hour > 0)
				--tmpDateTime.hour;
			else
				tmpDateTime.hour = 23;

			sprintf(dataStr," %02d", tmpDateTime.hour);
			tft.fillRect(setTimeXorg[4], setTimeYorg[4] , 50 , 20, BLUE);
	   		tft.setCursor(setTimeXorg[4], setTimeYorg[4]);
			delay(20);
			tft.print(dataStr);

			tft.fillRect(setTimeXorg[6], setTimeYorg[6] , 180 , 20, BLUE);
	   		tft.setCursor(setTimeXorg[6], setTimeYorg[6]);

			get12HrsClock(tmpDateTime.hour, tmpDateTime.minute, dataStr);
			tft.println(dataStr);
		break;

		case DEC_Minute:
			if(tmpDateTime.minute > 0)
				--tmpDateTime.minute;
			else
				tmpDateTime.minute = 59;

			sprintf(dataStr,"%02d", tmpDateTime.minute);
			tft.fillRect(setTimeXorg[5], setTimeYorg[5] , 50 , 20, BLUE);
	   		tft.setCursor(setTimeXorg[5], setTimeYorg[5]);
			delay(5);
			tft.print(dataStr);

			tft.fillRect(setTimeXorg[6], setTimeYorg[6] , 180 , 20, BLUE);
	   		tft.setCursor(setTimeXorg[6], setTimeYorg[6]);

			get12HrsClock(tmpDateTime.hour, tmpDateTime.minute, dataStr);
			tft.println(dataStr);
		break;

		case SETTIME_Done:
			if(! checkDate(tmpDateTime.month, tmpDateTime.monthDay, tmpDateTime.year, dateErrStr))
			{
	        	errorSetDateTime = true;
                showErrorMsg(SETTIME_MENU, dateErrStr, "TAP TO CONTINUE ...");
			}
			else
			{
				// Set new values of DS1307 and show them on display
                setDateTime(&tmpDateTime);
                getCurrentDateTime(&theDateTime); // copy into global
                write2RunLog("Current DateTime set");
                current_menu = MAIN_MENU;
                showMainMenu(-1);
			}
		break;

		case SETTIME_Cancel:
        	current_menu = MAIN_MENU;
            showMainMenu(-1);
		break;
	}

}





void showStartStopMenu(int curMenuSelection)
{
    int curX, curY;
    int minutesToRun;
    char dataStr[48];
    char startStopMsgStr[128];

    current_menu = SETPERIOD_MENU;
    doShowMessage = false;

    if(curMenuSelection < -1)
        return;

    tft.setTextSize(2);


    if((curMenuSelection == -1) || (errorStartStopTime))// only at first call
    {
        errorStartStopTime = false;

        tft.fillScreen(BLUE);
        tft.setCursor(0,0);

        curX = tft.getCurPosX();
        curY = tft.getCurPosY();

        tft.drawRect(1, curY+2, tft.width()-2, 200, RED);
        tft.fillRect(2, curY+4, tft.width()-4, 196, BLUE);

	    tft.setCursor(0,0);
		tft.println("");

    	tft.setTextSize(1);
    	tft.setTextColor(WHITE);
		tft.println(setStartStopMsg[0]); // " SET START TIME"
		tft.println("");

    	tft.setTextSize(2);
    	tft.setTextColor(YELLOW);

		tft.println(setStartStopMsg[1]); // "  +    +"

		setStStXorg[0] = tft.getCurPosX();
		setStStYorg[0] = tft.getCurPosY();
		sprintf(dataStr," %02d", theRuntime.startHour);
		tft.print(dataStr);

		tft.print(" : ");

		setStStXorg[1] = tft.getCurPosX();
		setStStYorg[1] = tft.getCurPosY();
		sprintf(dataStr,"%02d", theRuntime.startMinute);
		tft.print(dataStr);

		setStStXorg[2] = tft.getCurPosX();
		setStStYorg[2] = tft.getCurPosY();

		get12HrsClock(theRuntime.startHour, theRuntime.startMinute, dataStr);
		tft.println(dataStr);

		tft.println(setStartStopMsg[3]); // "  -    -"
		tft.println("");
		//tft.println("");

    	tft.setTextSize(1);
    	tft.setTextColor(WHITE);
		tft.println(setStartStopMsg[4]); // " SET STOP TIME"
    	tft.setTextSize(2);
    	tft.setTextColor(YELLOW);


		tft.println(setStartStopMsg[5]); // "  +    +"

		setStStXorg[3] = tft.getCurPosX();
		setStStYorg[3] = tft.getCurPosY();
		sprintf(dataStr," %02d", theRuntime.stopHour);
		tft.print(dataStr);

		tft.print(" : ");

		setStStXorg[4] = tft.getCurPosX();
		setStStYorg[4] = tft.getCurPosY();
		sprintf(dataStr,"%02d", theRuntime.stopMinute);
		tft.print(dataStr);

		setStStXorg[5] = tft.getCurPosX();
		setStStYorg[5] = tft.getCurPosY();

		get12HrsClock(theRuntime.stopHour, theRuntime.stopMinute, dataStr);
		tft.println(dataStr);

		tft.println(setStartStopMsg[7]); // "  -    -"


   		tft.println("");
    	tft.setTextSize(1);
   		tft.println("");
    	tft.setTextSize(2);
   		tft.println("    DONE     CANCEL");

        tmpRuntime.stopHour     = theRuntime.stopHour;
        tmpRuntime.stopMinute   = theRuntime.stopMinute;
        tmpRuntime.startHour    = theRuntime.startHour;
        tmpRuntime.startMinute  = theRuntime.startMinute;

		return;

    }


	switch(curMenuSelection)
	{
        case INC_Start_Hour:
            if(tmpRuntime.startHour < 23)
                ++tmpRuntime.startHour;
            else
                tmpRuntime.startHour = 0;

            sprintf(dataStr," %02d", tmpRuntime.startHour);
            tft.fillRect(setStStXorg[0], setStStYorg[0] , 50 , 20, BLUE);
            tft.setCursor(setStStXorg[0], setStStYorg[0]);
            delay(20);
            tft.print(dataStr);

            tft.fillRect(setStStXorg[2], setStStYorg[2] , 180 , 20, BLUE);
            tft.setCursor(setStStXorg[2], setStStYorg[2]);

            get12HrsClock(tmpRuntime.startHour, tmpRuntime.startMinute, dataStr);
            tft.println(dataStr);

        break;

        case INC_Start_Minute:
            if(tmpRuntime.startMinute < 59)
                ++tmpRuntime.startMinute;
            else
                tmpRuntime.startMinute = 0;

            sprintf(dataStr,"%02d", tmpRuntime.startMinute);
            tft.fillRect(setStStXorg[1], setStStYorg[1] , 50 , 20, BLUE);
            tft.setCursor(setStStXorg[1], setStStYorg[1]);
            delay(5);
            tft.print(dataStr);

            tft.fillRect(setStStXorg[2], setStStYorg[2] , 180 , 20, BLUE);
            tft.setCursor(setStStXorg[2], setStStYorg[2]);

            get12HrsClock(tmpRuntime.startHour, tmpRuntime.startMinute, dataStr);
            tft.println(dataStr);
        break;

        case DEC_Start_Hour:
            if(tmpRuntime.startHour > 0)
                --tmpRuntime.startHour;
            else
                tmpRuntime.startHour = 23;

            sprintf(dataStr," %02d", tmpRuntime.startHour);
            tft.fillRect(setStStXorg[0], setStStYorg[0] , 50 , 20, BLUE);
            tft.setCursor(setStStXorg[0], setStStYorg[0]);
            delay(20);
            tft.print(dataStr);

            tft.fillRect(setStStXorg[2], setStStYorg[2] , 180 , 20, BLUE);
            tft.setCursor(setStStXorg[2], setStStYorg[2]);

            get12HrsClock(tmpRuntime.startHour, tmpRuntime.startMinute, dataStr);
            tft.println(dataStr);


        break;

        case DEC_Start_Minute:
            if(tmpRuntime.startMinute > 0)
                --tmpRuntime.startMinute;
            else
                tmpRuntime.startMinute = 59;

            sprintf(dataStr,"%02d", tmpRuntime.startMinute);
            tft.fillRect(setStStXorg[1], setStStYorg[1] , 50 , 20, BLUE);
            tft.setCursor(setStStXorg[1], setStStYorg[1]);
            delay(5);
            tft.print(dataStr);

            tft.fillRect(setStStXorg[2], setStStYorg[2] , 180 , 20, BLUE);
            tft.setCursor(setStStXorg[2], setStStYorg[2]);

            get12HrsClock(tmpRuntime.startHour, tmpRuntime.startMinute, dataStr);
            tft.println(dataStr);

        break;

        case INC_Stop_Hour:
            if(tmpRuntime.stopHour < 23)
                ++tmpRuntime.stopHour;
            else
                tmpRuntime.stopHour = 0;

            sprintf(dataStr," %02d", tmpRuntime.stopHour);
            tft.fillRect(setStStXorg[3], setStStYorg[3] , 50 , 20, BLUE);
            tft.setCursor(setStStXorg[3], setStStYorg[3]);
            delay(20);
            tft.print(dataStr);

            tft.fillRect(setStStXorg[5], setStStYorg[5] , 180 , 20, BLUE);
            tft.setCursor(setStStXorg[5], setStStYorg[5]);

            get12HrsClock(tmpRuntime.stopHour, tmpRuntime.stopMinute, dataStr);
            tft.println(dataStr);

        break;

        case INC_Stop_Minute:
            if(tmpRuntime.stopMinute < 59)
                ++tmpRuntime.stopMinute;
            else
                tmpRuntime.stopMinute = 0;

            sprintf(dataStr,"%02d", tmpRuntime.stopMinute);
            tft.fillRect(setStStXorg[4], setStStYorg[4] , 50 , 20, BLUE);
            tft.setCursor(setStStXorg[4], setStStYorg[4]);
            delay(5);
            tft.print(dataStr);

            tft.fillRect(setStStXorg[5], setStStYorg[5] , 180 , 20, BLUE);
            tft.setCursor(setStStXorg[5], setStStYorg[5]);

            get12HrsClock(tmpRuntime.stopHour, tmpRuntime.stopMinute, dataStr);
            tft.println(dataStr);
        break;

        case DEC_Stop_Hour:
            if(tmpRuntime.stopHour > 0)
                --tmpRuntime.stopHour;
            else
                tmpRuntime.stopHour = 23;

            sprintf(dataStr," %02d", tmpRuntime.stopHour);
            tft.fillRect(setStStXorg[3], setStStYorg[3] , 50 , 20, BLUE);
            tft.setCursor(setStStXorg[3], setStStYorg[3]);
            delay(20);
            tft.print(dataStr);

            tft.fillRect(setStStXorg[5], setStStYorg[5] , 180 , 20, BLUE);
            tft.setCursor(setStStXorg[5], setStStYorg[5]);

            get12HrsClock(tmpRuntime.stopHour, tmpRuntime.stopMinute, dataStr);
            tft.println(dataStr);

        break;

        case DEC_Stop_Minute:
            if(tmpRuntime.stopMinute > 0)
                --tmpRuntime.stopMinute;
            else
                tmpRuntime.stopMinute = 59;

            sprintf(dataStr,"%02d", tmpRuntime.stopMinute);
            tft.fillRect(setStStXorg[4], setStStYorg[4] , 50 , 20, BLUE);
            tft.setCursor(setStStXorg[4], setStStYorg[4]);
            delay(5);
            tft.print(dataStr);

            tft.fillRect(setStStXorg[5], setStStYorg[5] , 180 , 20, BLUE);
            tft.setCursor(setStStXorg[5], setStStYorg[5]);

            get12HrsClock(tmpRuntime.stopHour, tmpRuntime.stopMinute, dataStr);
            tft.println(dataStr);

        break;

        case SETSTST_Done:
            minutesToRun = processStartStopSettings(tmpRuntime.startHour, tmpRuntime.startMinute,
                                                    tmpRuntime.stopHour, tmpRuntime.stopMinute, startStopMsgStr);
            if(! minutesToRun)
            {
                errorStartStopTime = true;
                showErrorMsg(SETPERIOD_MENU, startStopMsgStr, "TAP TO CONTINUE ...");
            }
            else
            {
                theRuntime.stopHour    = tmpRuntime.stopHour;
                theRuntime.stopMinute  = tmpRuntime.stopMinute;
                theRuntime.startHour   = tmpRuntime.startHour;
                theRuntime.startMinute = tmpRuntime.startMinute;

                writeSettings2Eeprom();
                write2RunLog("Start/Stop (runtime) set");

                showStStMsg(startStopMsgStr, "TAP TO CONTINUE ...");
                delay(500);
                // Update/save global values
                current_menu = MAIN_MENU;
                //showMainMenu(-1);
            }
        break;

        case SETSTST_Cancel:
            current_menu = MAIN_MENU;
            showMainMenu(-1);
        break;
	}
}


////////////////////////////////////////////////////////////////////////////////////////////////////////////////



void showCalibrateMenu(int curMenuSelection)
{
    int curX, curY, i;
    char dataStr[48];

    current_menu = CALIBRATE_MENU;
    doShowMessage = false;

    if(curMenuSelection < -1)
        return;

    tft.setTextSize(2);

    if((curMenuSelection == -1))
    {
        tft.fillScreen(BLUE);
        tft.setCursor(0,0);

        curX = tft.getCurPosX();
        curY = tft.getCurPosY();

        tft.drawRect(1, curY+2, tft.width()-2, 200, RED);
        tft.fillRect(2, curY+4, tft.width()-4, 196, BLUE);

	    tft.setCursor(0,0);
    	tft.setTextSize(2);
    	tft.setTextColor(WHITE);
		tft.println("");

        for(i = 0; calibrateMsg[i]; i++)
        {
		  tft.println(calibrateMsg[i]);
        }

		return;

    }


	switch(curMenuSelection)
	{
        case CAL_Done:
            // start measuring current per phase
        break;

        case CAL_Cancel:
        break;

	}
    current_menu = MAIN_MENU;
    showMainMenu(-1);

}


/////////////////////////////////////////////////////////////////////////////////////////////////////////////



void showTime(char *msg)
{
    tft.drawRect(1, 208, tft.width()-2, 30, RED);
    tft.fillRect(2, 210, tft.width()-4, 26, BLUE);

    tft.setTextColor(WHITE);
    tft.setTextSize(1);

    tft.setCursor(10,218);
    tft.print(msg);

    tft.setTextColor(YELLOW);
    tft.setTextSize(2);
}


void showSeconds(int secnd)
{
    char sk[3];

    sprintf(sk,"%02d",secnd);

    tft.fillRect(153, 210, 18, 18, BLUE);
    //tft.fillRect(147, 215, 14, 14, BLUE);

    tft.setTextColor(WHITE);
    tft.setTextSize(1);

    //tft.setCursor(150,218);
    tft.setCursor(153,218);
    tft.print(sk);

    tft.setTextColor(YELLOW);
    tft.setTextSize(2);
}


void processMenuChoice(int menuOfChoice)
{
    switch(menuOfChoice)
    {
        case MAIN_MENU:
            showMainMenu(-1);
        break;

        case SETTIME_MENU:
            showSetTimeMenu(-1);
        break;

        case SETPERIOD_MENU:
            showStartStopMenu(-1);
        break;

        case CALIBRATE_MENU:
            showCalibrateMenu(-1);
        break;

        case BANNED_MENU:
            showMainMenu(-1);
        break;

        case VIEWLOG_MENU:
            showMainMenu(-1);
        break;

        case OFF_MENU:
            showMainMenu(-1);
        break;

        default:
            showMainMenu(-1);
        break;
    }
}




int process_xySetDateTime(int x, int y)
{
	int menuOption = -2;

	if ((x >= 172) && (x <= 385)) // Date-part
	{
		if ((x >=172) && (x<= 258)) // Increase-row
		{
			if ((y >= 820) && (y <= 920)) // DayOfWeek increase
			{
				menuOption = INC_DayOfW;
			}
			else
			{
				if ((y >= 660) && (y <= 760)) // DayOfMonth increase
				{
					menuOption = INC_DayOfM;
				}
				else
				{
					if ((y >= 474) && (y <= 602)) // Month increase
					{
						menuOption = INC_Month;
					}
					else
					{
						if ((y >= 256) && (y <= 416)) // Year increase
						{
							menuOption = INC_Year;
						}
					}
				}

			}
		}
		else
		{
			if ((x >=308) && (x <= 385)) // Decrease row
			{
				if ((y >= 820) && (y <= 920)) // DayOfWeek decrease
				{
					menuOption = DEC_DayOfW;
				}
				else
				{
					if ((y >= 660) && (y <= 760)) // DayOfMonth decrease
					{
						menuOption = DEC_DayOfM;
					}
					else
					{
						if ((y >= 474) && (y <= 602)) // Month decrease
						{
							menuOption = DEC_Month;
						}
						else
						{
							if ((y >= 256) && (y <= 416)) // Year decrease
							{
								menuOption = DEC_Year;
							}
						}
					}

				}
			}
		}

	// ******************** Now comes the Time-part and the Done/Cancel part of the menu
	}
	else
	{
		 if ((x >= 430) && (x <= 630)) // Time-part
		 {
		 	if ((x >= 430) && (x <= 526)) // Increase row
		 	{
		 		if((y >= 855) && (y <= 940)) // Hour increase
		 		{
		 			menuOption = INC_Hour;
		 		}
		 		else
		 		{
		 		 	if ((y >=690) && (y <= 790)) // Minute increase
		 		 	{
		 		 		menuOption = INC_Minute;
		 		 	}
		 		}
		 	}
		 	else
		 	{
		 		if ((x >= 562) && (x <= 630)) // Decrease row
		 		{
			 		if((y >= 855) && (y <= 940)) // Hour decrease
			 		{
			 			menuOption = DEC_Hour;
			 		}
			 		else
			 		{
			 		 	if ((y >=690) && (y <= 790)) // Minute decrease
			 		 	{
			 		 		menuOption = DEC_Minute;
			 		 	}
			 		}
		 		}
		 	}
		 }
		 else
		 {
		 	if ((x >= 680) && (x <= 780)) // Done/Cancel part
		 	{
		 		if ((y >= 688) && (y <= 875 )) // Done
		 		{
		 			menuOption = SETTIME_Done;
		 		}
		 		else if ( (y >= 346) && (y <= 590)) // Cancel
		 		{
		 			menuOption = SETTIME_Cancel;
		 		}
		 	}
		 }
	}

	return(menuOption);
}





int process_xySetStSt(int x, int y)
{
	int menuOption = -2;

	if ((x >= 210) && (x <= 405)) // Start Time part
	{
		if ((x >=210) && (x<= 284)) // Increase-row
		{
			if ((y >= 832) && (y <= 941)) // start hour increase
			{
				menuOption = INC_Start_Hour;
			}
			else
			{
				if ((y >= 682) && (y <= 795)) // INC_Start_Minute increase
				{
					menuOption = INC_Start_Minute;
				}
			}
		}
		else
		{
			if ((x >=328) && (x <= 405)) // Decrease row
			{
				if ((y >= 832) && (y <= 941)) // DayOfWeek decrease
				{
					menuOption = DEC_Start_Hour;
				}
				else
				{
					if ((y >= 682) && (y <= 798)) // DayOfMonth decrease
					{
						menuOption = DEC_Start_Minute;
					}
				}
			}
		}
	}
	else    // ******************** Now comes the Stop Time -part and the Done/Cancel part of the menu
	{
		 if ((x >= 440) && (x <= 638)) // Stop Time part
		 {
		 	if ((x >= 440) && (x <= 520)) // Increase row
		 	{
		 		if((y >= 832) && (y <= 941)) // Hour increase
		 		{
		 			menuOption = INC_Stop_Hour;
		 		}
		 		else
		 		{
		 		 	if ((y >=682) && (y <= 795)) // Minute increase
		 		 	{
		 		 		menuOption = INC_Stop_Minute;
		 		 	}
		 		}
		 	}
		 	else
		 	{
		 		if ((x >= 562) && (x <= 638)) // Decrease row
		 		{
			 		if((y >= 832) && (y <= 941)) // Hour decrease
			 		{
			 			menuOption = DEC_Stop_Hour;
			 		}
			 		else
			 		{
			 		 	if ((y >=682) && (y <= 795)) // Minute decrease
			 		 	{
			 		 		menuOption = DEC_Stop_Minute;
			 		 	}
			 		}
		 		}
		 	}
		 }
		 else
		 {
		 	if ((x >= 675) && (x <= 781)) // Done/Cancel part
		 	{
		 		if ((y >= 685) && (y <= 875 )) // Done
		 		{
		 			menuOption = SETSTST_Done;
		 		}
		 		else if ( (y >= 346) && (y <= 590)) // Cancel
		 		{
		 			menuOption = SETSTST_Cancel;
		 		}
		 	}
		 }
	}

	return(menuOption);
}






int process_xyCalibrate(int x, int y)
{
    int menuOption = -2;

    if ((x >= 662) && (x <= 770))
    {
        if((y >= 610) && (y <= 828))
            menuOption = CAL_Done;
        else
            if((y >= 270) && (y <= 510))
                menuOption = CAL_Cancel;
    }
    return(menuOption);
}








// p.x becomes y and p.y becomes y. setTextCursor(0,0) == upper left corner
void procTouch(int x, int y)
{
    int mappedX, mappedY;
    char msg[40];
    int menuOption = -2;


    if(x <= 255)  menuOption = 0;
    else if((x >= 256) && (x <= 357)) menuOption = 1;
    else if((x >= 358) && (x <= 463)) menuOption = 2;
    else if((x >= 464) && (x <= 560)) menuOption = 3;
    else if((x >= 561) && (x <= 659)) menuOption = 4;
    else if((x >= 660) && (x <= 759)) menuOption = 5;


//sprintf(msg,"x=%d   y=%d", x,y);
//showTime(msg);

    switch(current_menu)
    {
        case MAIN_MENU:
            showMainMenu(menuOption);
        break;

        case SETTIME_MENU:
            if (! errorSetDateTime)
				    menuOption = process_xySetDateTime(x, y);
            else
            {
                menuOption = -1;
                getCurrentDateTime(&theDateTime);
                showTime(theDateTime.timeString);
            }
            showSetTimeMenu(menuOption);

        break;

        case SETPERIOD_MENU:
            if(! errorStartStopTime)
                menuOption = process_xySetStSt(x, y);
            else
            {
                menuOption = -1;
            }
            showStartStopMenu(menuOption);
        break;

        case CALIBRATE_MENU:
             menuOption = process_xyCalibrate(x, y);
             showCalibrateMenu(menuOption);
        break;

        case BANNED_MENU:
            showMainMenu(menuOption);
        break;

        case VIEWLOG_MENU:
            showMainMenu(menuOption);
        break;

        case OFF_MENU:
            showMainMenu(menuOption);
        break;

        default:
            showMainMenu(-1);
        break;
    }

}






// 4096 bytes Eeprom memory in ATmega2560

void readSettingsFromEeprom()
{
    int addr = 0;
    byte runMan = 0, swOff = 0;

    theRuntime.startHour    = (int) EEPROM.read(addr++);
    theRuntime.startMinute  = (int) EEPROM.read(addr++);
    theRuntime.stopHour     = (int) EEPROM.read(addr++);
    theRuntime.stopMinute   = (int) EEPROM.read(addr++);
    runMan                  = EEPROM.read(addr++);
    swOff                   = EEPROM.read(addr);

    if(runMan) runManual = true;
    else runManual = false;

    if(swOff) switchedOff = true;
    else switchedOff = false;
}



void writeSettings2Eeprom()
{
    int addr = 0;
    byte runMan = 0, swOff = 0;

    runMan = runManual == true;
    swOff  = switchedOff == true;

    EEPROM.write(addr++, (byte) theRuntime.startHour);
    EEPROM.write(addr++, (byte) theRuntime.startMinute);
    EEPROM.write(addr++, (byte) theRuntime.stopHour);
    EEPROM.write(addr++, (byte) theRuntime.stopMinute);
    EEPROM.write(addr++, runMan);
    EEPROM.write(addr, swOff);
}



boolean write2RunLog(char *theMsg)
{
    File runFile;
    boolean ret = false;
    char outMsg[80];
    boolean spiEnabled = false;

    disableSPI();
    enableSPI();
    spiEnabled = true;
    delay(10);

    if (!SD.begin(SD_CS))
    {
        showErrorMsg(MAIN_MENU, "Cannot find SD card !", "");
        delay(2500);
    }
    else
    {
        runFile = SD.open("/run.log", FILE_WRITE);
        if(runFile)
        {
            sprintf(outMsg,"%s ==> %s !\n", theDateTime.timeString, theMsg);
            runFile.write(outMsg);
            runFile.close();
            ret = true;
        }
        else
        {
            disableSPI();
            spiEnabled = false;
            showErrorMsg(MAIN_MENU, "Can't open run.log","");
            delay(2500);
        }
    }

    if(spiEnabled)
        disableSPI();

    return(ret);
}



void setup(void)
{
    boolean setupError = false;
    //char setupErrMsg[80], outMsg[60];
    //setupErrMsg[0] = (char) 0;

    Wire.begin();
    delay(10);

    // ACS756 current sensors
    pinMode(pinInRedAcs756, INPUT);
    pinMode(pinInBlueAcs756, INPUT);
    pinMode(pinInYellowAcs756, INPUT);
    pinMode(pinFeedAcs756, OUTPUT);
    digitalWrite(pinFeedAcs756, HIGH);


    // Solid State Relais
    pinMode(pinSSR, OUTPUT);
    digitalWrite(pinSSR, LOW);

    // DS1307 digital clock
    pinMode(pinVccDS1307, OUTPUT); // always on
    digitalWrite(pinVccDS1307, HIGH);


    // Backlight for LCD-screen
    pinMode(pinBackLite, OUTPUT);
    digitalWrite(pinBackLite, HIGH);
    backLiteIsOn = true;
    touchedPrev = touchedCur = millis();


    colorAr[0] = BLACK;
    colorAr[1] = BLUE;
    colorAr[2] = RED;
    colorAr[3] = GREEN;
    colorAr[4] = CYAN;
    colorAr[5] = MAGENTA;
    colorAr[6] = YELLOW;
    colorAr[7] = WHITE;
    tft.reset();
    uint16_t identifier = tft.readRegister(0x0);
    tft.setRotation(1);
    tft.initDisplay();

    getCurrentDateTime(&theDateTime);

    pinMode(SD_CS, OUTPUT);
    write2RunLog("System started");

    readSettingsFromEeprom();

    current_menu = MAIN_MENU;
    prev_menu = -1;

    showMainMenu(-1);
}






void loop(void)
{
    digitalWrite(13, HIGH);
    p = ts.getPoint(); // coordinates of touchScreen are not equal to coordinates of LCDScreen
    digitalWrite(13, LOW);

    pinMode(XM, OUTPUT);
    pinMode(YP, OUTPUT);


    /************* Start Update Clock-display *************************************/
    getCurrentDateTime(&theDateTime);
    if((current_menu != SETTIME_MENU) && (endMillis - startMillis >= 1000UL) ||
       ((startMillis == 0UL) && (endMillis == 0UL)))
    {
        startMillis = endMillis = millis();

        //getCurrentDateTime();
        if((theDateTime.second < 1) || (current_menu != prev_menu))
        {
            showTime(theDateTime.timeString);
            prev_menu = current_menu;


            if(switchedOff)
            {
                if(SSRisOn)
                    toggleSSR();
            }
            else
            if(! runManual)
            {
                if (checkTime2Run() )
                {
                    if(! SSRisOn)
                        toggleSSR();
                }
                else
                {
                    if(SSRisOn)
                        toggleSSR();
                }
            }
        }
        else
        {
            showSeconds(theDateTime.second);
        }
    }
    else
        endMillis = millis();
        /*************** End Update Clock-display *************************************/



    touchedCur = millis();
    if (p.z > MINPRESSURE && p.z < MAXPRESSURE)
    {
        touchedPrev = touchedCur;
        if ( ! backLiteIsOn)
        {
            toggleBackLite();
            delay(500);
        }
        else
            procTouch(p.x, p.y);
    }
    else
    {
        if(backLiteIsOn && (touchedCur - touchedPrev > MAX_IDLE_TIME))
            toggleBackLite();
    }


}


ddutch2001
 
Posts: 11
Joined: Tue Oct 04, 2011 3:41 am

Re: AtMega 2560 + 2.8 TFT touch Shield + SD card == Problem

Post by ddutch2001 »

Sorry, I used Quote instead of Code tags.

User avatar
adafruit_support_bill
 
Posts: 88088
Joined: Sat Feb 07, 2009 10:11 am

Re: AtMega 2560 + 2.8 TFT touch Shield + SD card == Problem

Post by adafruit_support_bill »

I'm not able to compile your code. What version of the libraries are you using?

The most recent version of the TFTLCD library has no getCurPosX() or getCurPosY().

Code: Select all

        curX = tft.getCurPosX();
        curY = tft.getCurPosY();

ddutch2001
 
Posts: 11
Joined: Tue Oct 04, 2011 3:41 am

Re: AtMega 2560 + 2.8 TFT touch Shield + SD card == Problem

Post by ddutch2001 »

Ach sorry, I added some code to that library:

In tftlcd.h:

Code: Select all

  int getCurPosX(void);
  int getCurPosY(void);
And in tftlcd.cpp:

Code: Select all

int TFTLCD::getCurPosX()
{
  return(cursor_x);
}


int TFTLCD::getCurPosY()
{
  return(cursor_y);
}


ddutch2001
 
Posts: 11
Joined: Tue Oct 04, 2011 3:41 am

Re: AtMega 2560 + 2.8 TFT touch Shield + SD card == Problem

Post by ddutch2001 »

The TFTLCD library was packed in adafruit-TFTLCD-Library-164456f.zip. The files it contains are from 2 December 2011.

User avatar
adafruit_support_bill
 
Posts: 88088
Joined: Sat Feb 07, 2009 10:11 am

Re: AtMega 2560 + 2.8 TFT touch Shield + SD card == Problem

Post by adafruit_support_bill »

It compiles with those changes, but doesn't run. I suspect it is hanging up on the RTC calls since I don't have a DS1307 on this testbed.
If you had used RTCLib, it would be pretty simple to switch to the internal millis() timer.

ddutch2001
 
Posts: 11
Joined: Tue Oct 04, 2011 3:41 am

Re: AtMega 2560 + 2.8 TFT touch Shield + SD card == Problem

Post by ddutch2001 »

I removed the ds1307 and also removed all code which calls the ds1307 (wire calls) and still cannot write to the sd card (only once). Seems the problem is not caused by ds1307/wire

ddutch2001
 
Posts: 11
Joined: Tue Oct 04, 2011 3:41 am

Re: AtMega 2560 + 2.8 TFT touch Shield + SD card == Problem

Post by ddutch2001 »

Maybe your version hangs because the call to readSettingsFromEeprom() in setup() returns strange values. Might skip that call.

ddutch2001
 
Posts: 11
Joined: Tue Oct 04, 2011 3:41 am

Re: AtMega 2560 + 2.8 TFT touch Shield + SD card == Problem

Post by ddutch2001 »

I can't understand why I can write only once to the file. Tomorrow (local time her now is 23:55) I'll play with adafruits TFT_BMP_Shield example, but instead of reading/displaying I will try to write several times to a file. Good night !

User avatar
adafruit_support_bill
 
Posts: 88088
Joined: Sat Feb 07, 2009 10:11 am

Re: AtMega 2560 + 2.8 TFT touch Shield + SD card == Problem

Post by adafruit_support_bill »

It helps to reduce the code to the absolute minimum amount needed to reproduce the problem. That eliminates irrelevant variables and allows others to test it out - even if they don't have your complete hardware/software configuration.

Locked
Please be positive and constructive with your questions and comments.

Return to “Arduino Shields from Adafruit”