#include "SEMAPHORE.h"
#include "gpio.h"

char stato = 0;
char dir = 0;

void SEMAPHORE_init(void){
  TIM7 -> ARR = ON_time;
  TIM7 -> PSC = 24000;	// set single timer ticks to 100us (240MHz/24000 = 10kHz) - 240MHz is APB1 clock freq.
  TIM7 -> CR1 |= TIM_CR1_CEN;
  TIM7 -> CNT = 0;
  TIM7 -> DIER |= TIM_DIER_UIE;
  //inizia con UNO acceso
  GPIOB -> BSRR = on_0;
}

void SEMAPHORE_TIM7_interrupt(void){
  // spegni tutto
    GPIOB -> BSRR = off_0;
    GPIOE -> BSRR = off_1;
    GPIOB -> BSRR = off_2;

    TIM7->SR = 0;

    switch(stato){
      case 0:
        GPIOE -> BSRR = on_1;
        stato = 1;
        TIM7 -> ARR = ON_time;
        break;
      case 1:
	if(!dir){
	    GPIOB -> BSRR = on_2;
	    stato = 2;
	    dir = 1;
	}else{
	    GPIOB -> BSRR = on_0;
	    stato = 0;
	    dir = 0;
	}
	TIM7 -> ARR = OFF_time;
        break;
      case 2:
        GPIOE -> BSRR = on_1;
        stato = 1;
        TIM7 -> ARR = ON_time;
        break;
    }
}
