#include "Libraries/stm32l1xx_nucleo/stm32l1xx_nucleo.h"
#include "stm32l1xx_nucleo.h"
#include "stm32l1xx_it.h"

void wait_500ms(void);
void init_timer2();
void config_IT_TIM2();
void TIM2_IRQHandler();


int NUM_OF_PATTERN = 8; //nbr de led (il y a 8 leds)
int a=0;
uint16_t tmp = 0x00;
uint16_t tmp1;
//Tableau pour faire la chenille
uint16_t myTable[]={0x0000,0x0002,0x0004,0x0400,0x0800,0x1000,0x2000,0x4000,0x8000};//Tableau pour allumage led
uint8_t i;




int main()
{
    
    RCC->AHBENR|=RCC_AHBENR_GPIOBEN;
    
    RCC->AHBENR |= RCC_AHBPeriph_GPIOB; // affecte l'horloge au BPIOA
    RCC->AHBENR |= RCC_AHBPeriph_GPIOA; // affecte l'horloge au BPIOA
    
    GPIOA->MODER |= 0x00000000;
    GPIOB->MODER |= 0x55555555; 
    
    GPIOB->OTYPER |= 0x00000000;
    
    GPIOB->OSPEEDR=1;
    GPIOA->OSPEEDR=1;


   /* while (1)
    {
        wait_500ms();
        GPIOB->ODR ^=(1<<1);
         
       // GPIOB->ODR^=(1<<10);
       // GPIOB->ODR|=(1<<10);
       // GPIOB->ODR|=(1<<11);
       // GPIOB->ODR|=(1<<12);
       // GPIOB->ODR|=(1<<13);
       // GPIOB->ODR|=(1<<14);
       // GPIOB->ODR|=(1<<15);
       // GPIOB->ODR|=(1<<1);
    }*/
    
    //Ne pas supp
    /*for(i=0;i<NUM_OF_PATTERN; i++){
      uint16_t tmp;
      tmp = myTable[i];
      GPIOB->ODR=tmp; //mask ???
      de1500ms();
    }*/
    
    //Ne pas supp
   /* for(i=0;i<NUM_OF_PATTERN; i++){
      uint16_t tmp;
      GPIOB->BSRRL |=tmp;
      GPIOB->BSRRH |=myTable[i];
      tmp = myTable[i];
      wait_500ms();
    } */
    
    
    config_IT_TIM2();
      while(1){}

    return 0;
}



void wait_500ms(void)
{
  
  TIM2->CR1 |= (1<<0);
  //TIM_Cmd(TIM2, ENABLE);
  while((TIM2->SR) & (1<<0) != 1 ){}
  TIM2->CR1 |= (0<<0);
  TIM2->SR &= (0<<0);
}


//Interruption sur "28"
void config_IT_TIM2(void){
   NVIC->ISER[0] |= 1<<28; 
   RCC->APB1ENR |= RCC_APB1ENR_TIM2EN;
   TIM2->ARR = 1000;
   TIM2->PSC = 2999;
   TIM2->CR1 |=0x01; // CEN= 1
   TIM2->DIER |=0x01;
  }

void TIM2_IRQHandler(void){
  TIM2->SR &= ~(0x01);
  GPIOB->ODR = myTable[i];
  i++;
  if(i>NUM_OF_PATTERN){
    i=0; //remet à 0
  }
  
}

void config_motor(void){
  RCC->APB1ENR |=0x02;
  GPIOB->MODER |=2<<8;
  GPIOB->AFR[0] |= 2<<16;
  
  RCC->APB1ENR |= RCC_APB1ENR_TIM3EN;
  TIM3->PSC = 120;
  TIM3->ARR = 120; 
  TIM3->CR1 |=0x01; //CEN = 1
  
  TIM3->PSC = 120;
  TIM3->ARR = 120; 
  TIM3->CR1 |=0x01; //CEN = 1
  
  TIM3->CR1 |= 0x01; //CEN = 1
  TIM3->CCMR1 |= 6<<4;
  TIM3->CCER |= 1<<0;
  
  
}


  