#define _XTAL_FREQ 4000000
//Set the config bits
#pragma config WDT = OFF, BOR = OFF, LVP = OFF, OSC = XT
// setting up BUTTONS
void InitialiseButtons(void);
unsigned char ReadButton(void);
#define UP 0
#define DOWN 1
#define BUTTON_S2 0x01
#define BUTTON_S3 0x10
#define BUTTON_S2_S3 0x00
void InitialiseButtons(void)
{
TRISA |= 0x10;
TRISB |= 0x01;
}
//Detects a change of state of buttons
// Buttons are active low
unsigned char ReadButton(void)
{
char ButtonState;
static char ButtonFlag = 0x11;
//Read State of both buttons
ButtonState = (PORTA & 0x10) | (PORTB & 0x01);
if(ButtonFlag != ButtonState) //there has been a change
{
ButtonFlag = ButtonState;
return ButtonFlag;
}
return 0x11;
}
// setting up LEDs
#define LED0 0x01
#define LED1 0x02
#define LED2 0x04
#define LED3 0x08
void InitialiseLED(void); //prototype functions
void LEDOn(unsigned char TheLED);
void LEDOff(unsigned char TheLED);
void LEDToggle(unsigned char TheLED);
void LEDWrite(unsigned char LEDValue);
void InitialiseLED(void)
{
TRISB = 0xF0; //Set the port direction register
LATB = 0x00; //Clear the port
}
void LEDOn(unsigned char TheLED)
{
LATB |= TheLED; //Set the required bit on PORTB
}
void LEDOff(unsigned char TheLED)
{
LATB &= (~TheLED); //Clear the required bit on PORTB
}
void LEDToggle(unsigned char TheLED)
{
LATB ^= TheLED; //XOR the required bit on PORTB
}
void LEDWrite(unsigned char LEDValue)
{
LATB = LEDValue; //Store a value on PORTB
}
// setting up TIMER
void ResetSeconds(void)
{
seconds = 0;
}
unsigned char TimerOverflow(void)
{
char flag = 0;
if(INTCONbits.TMR0IF)
{
INTCONbits.TMR0IF = 0;
//flag = 1;
seconds++;
}
//return flag;
return seconds;
// setting up STATEMACHINE with TIMER
enum
{
S_OFF
S_STATE1
S_STATE2
}States;
enum
{
E_T1,
E_T2,
E_BUTTON
}Events;
#define T3s 3
#define T5s 5
unsigned char GetEvent(void);
unsigned char State = S_OFF;
void DoStateMachine(void)
{
unsigned char Event;
Event = GetEvent();
switch(State)
{
case S_OFF:
LEDOff(LED3);
LEDOff(LED2);
if(Event == E_BUTTON)
{
ResetSeconds();
State = S_STATE1;
}
break;
case S_STATE1:
LEDOn(LED3);
LEDOff(LED2);
if(Event == E_T1)
{
ResetSeconds();
State = S_STATE2;
}
if(Event == E_BUTTON)
State = S_OFF;
break;
case S_STATE2:
LEDOff(LED3);
LEDOn(LED2);
if(Event == E_T2)
{
ResetSeconds();
State = S_STATE1;
}
if(Event == E_BUTTON)
State = S_OFF;
break;
}
}
unsigned char GetEvent(void)
{
if(TimerOverflow() == T3s)
return E_T1;
if(TimerOverflow() == T5s)
return E_T2;
if(ReadButton() == BUTTON_S2)
return E_BUTTON;
void main(void)
{
InitialiseLED();
InitialiseButtons();
InitialiseTimer();
Lcd_Init();
while(1)
{
DoStateMachine();
}
}