#include "stm32f10x.h"

/****** project hardware ******/
#define PCOUT   GPIOC->ODR    // for output LEDs PC8 PC9
#define PAIN    GPIOA->IDR    // for input push button PA0
#define PADDR_HIGH GPIOA->CRH
#define PADDR_LOW  GPIOA->CRL
#define PBDDR_HIGH GPIOB->CRH
#define PBDDR_LOW  GPIOB->CRL
#define PCDDR_HIGH GPIOC->CRH
#define PCDDR_LOW  GPIOC->CRL

#define LED 8 // port C, bit 8
#define LED2 9
inline void gpio_set(int bitPosition, int value) {
  if (value)
    PCOUT |= (1<<bitPosition);
  else
    PCOUT &= ~(1<<bitPosition);
}

/************ events ************/
void newEvent(char e);
#define NUM_EVENTS 10
volatile char events[NUM_EVENTS];	// starts full of zeros EVT_NONE

#define EVT_NONE 0
#define EVT_TICK 1
#define EVT_BUTTON 2

/********** tasks ***********/
void ledTask(char evt);
void respondToButtonTask(char evt);

/********** interrupts **************/
volatile int tick;	// increasing at 100 ticks/sec
			// takes a year to roll-over

#define eint() asm volatile("cpsie i")
#define dint() asm volatile("cpsid i")

void timer_isr(void) {
	tick++;
	newEvent(EVT_TICK);
	// this interrupt is auto-ack'd
}

void button_isr(void) {
  newEvent(EVT_BUTTON);
  EXTI->PR |= 1;    // ack both 
}

/** newEvent
 * add the event to the event queue
 * wrapped in critical section
 * 
 * @param the event
 */
void newEvent(char e) {
	static unsigned char nextEvent;
    if (events[nextEvent]) 
      return;
	dint();	// critical section
	events[nextEvent++] = e;
	if (nextEvent==NUM_EVENTS)
		nextEvent = 0;
	eint();
}

/***** init ******/
/* called by newlib startup */
void _init(void) {
  // startup code

  // turn on all the GPIO's
  RCC->APB2ENR = 0x74A3D; // enable the GPIO devices and timers
  RCC -> APB1ENR = 0x1ff; // enable timers 2-14
  AFIO -> MAPR |= 0x02008C00;   // remap osc to PD0/1 and tim3 to PB4/5/0/1

  PADDR_HIGH = 0x44444444;      // PortA all inputs
  PCDDR_HIGH = 0x11111111;      // PortC all outputs

  // keep the clocking system simple: just use the 8MHz HSI everywhere
  SysTick->LOAD = 10000;		// 10 msec
  SysTick->Val  = 0;
  SysTick->CTRL = 3;			// count at 1usec, use interrupts
  
  /* configure the blue button on the discovery module, PA0 */
  EXTI->IMR |= 1;         // enable interrupt from line 0
  EXTI->RTSR |= 1;        // interrupt on rising edge
  AFIO->EXTICR[0] |= 0x0;       // select port A

  /* enable all interrupt sources */
  NVIC->ISER[0] = 0xFFFFFFFF;     // enable in NVIC
  NVIC->ISER[1] = 0x00FFFFFF;     // enable in NVIC

  gpio_set(9,0);
  gpio_set(8,0);   
	
}


void main(void) {

	eint();

	while(1) {
		int j;
		for (j=0; j<NUM_EVENTS; j++) {
			while (events[j]==EVT_NONE)
				{}

            ledTask(events[j]);
            respondToButtonTask(events[j]);
			events[j] = EVT_NONE;
		}
	}
}

/*********** state code ************/
#define RTB_IDLE 0
#define RTB_ON 1
#define TIMER_LIMIT 150
static int rtbState = RTB_IDLE;
static int rtbTimerCount = 0;

void respondToButtonTask(char evt) {
  switch(rtbState) {
    case RTB_IDLE:
      if (evt == EVT_BUTTON) {
        rtbState = RTB_ON;
        gpio_set(LED, 1);
      }
      break;
    case RTB_ON:
      if (evt == EVT_TICK) {
        if (++rtbTimerCount > TIMER_LIMIT) {
          gpio_set(LED, 0);
          rtbState = RTB_IDLE;
          rtbTimerCount = 0;
        }
      }
      break;
    }
}

#define LED_OFF 0
#define LED_ON 1
#define LED_ON_TIME 150
#define LED_OFF_TIME 50
static int ledState = LED_OFF;
static int ledTimerCount = 0;

void ledTask(char evt) {
  switch(ledState) {
    case LED_OFF:
      if (evt == EVT_TICK) {
        if (++ledTimerCount > LED_OFF_TIME) {
          gpio_set(LED2, LED_ON);
          ledTimerCount = 0;
          ledState = LED_ON;
        }
      }
      break;
    case LED_ON:
      if (evt == EVT_TICK) {
        if (++ledTimerCount > LED_ON_TIME) {
          gpio_set(LED2, LED_OFF);
          ledTimerCount = 0;
          ledState = LED_OFF;
        }
      }
      break;
    }
}



/* vector table */
#define STACK_TOP 0x20002000
void default_isr(void) {}
extern void _start(void);

void (*myvectors[])(void) __attribute__ ((section(".vectors")))= {
	(void(*)(void)) STACK_TOP,     // stack pointer
	_start,        // code entry point
	default_isr,   // handle non-maskable interrupts
	default_isr, // handle hard faults
	0,0,0,0,                /* 10...1f */
	0,0,0,0,                /* 20...2f */
	0,0,0,timer_isr,        /* 30...3f */
	0,0,0,0,                /* 40...4f */
	0,0,button_isr,0,       /* 50...5f */
	0,0,0,0,                /* 60...6f */
	0,0,0,0,                /* 70...7f */
	0,0,0,0,                /* 80...8f */
	0,0,0,0,                /* 90...9f */
	0,0,0,0,                /* a0...af */
	0,0,0,0,                /* b0...bf */
	0,0,0,0,                /* c0...cf */
	0,0,0,0,                /* d0...df */
    0,0,0,0,  	            /* e0...ef */
	0,0,0,0,                /* f0...ff */
	0,0,0,0,				/* 100.10f */
	0,0,0,0                 /* 110.11f */
};
