HAL_COMP(io);

HAL_PIN(fan) = 0.0;
HAL_PIN(red) = 0.0;
HAL_PIN(green) = 0.0;
HAL_PIN(brake) = 0.0;

INIT(
   GPIO_InitStructure.GPIO_Mode  = GPIO_Mode_OUT;
   GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
   GPIO_InitStructure.GPIO_Speed = GPIO_Speed_2MHz;
   GPIO_InitStructure.GPIO_PuPd  = GPIO_PuPd_NOPULL;
   
   //fan
   GPIO_InitStructure.GPIO_Pin   = FAN_PIN;
   GPIO_Init(FAN_PORT, &GPIO_InitStructure);

   //led
   GPIO_InitStructure.GPIO_Pin   = LED_R_PIN;
   GPIO_Init(LED_R_PORT, &GPIO_InitStructure);

   GPIO_InitStructure.GPIO_Pin   = LED_G_PIN;
   GPIO_Init(LED_G_PORT, &GPIO_InitStructure);

   //brake
   RCC_APB2PeriphClockCmd(RCC_APB2Periph_TIM8, ENABLE);
   TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV4;
   TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
   TIM_TimeBaseStructure.TIM_Period = 8400; // 168e6 / 8400 = 20kHz
   TIM_TimeBaseStructure.TIM_Prescaler = 0;
   TIM_TimeBaseStructure.TIM_RepetitionCounter = 0;
   TIM_TimeBaseInit(TIM8, &TIM_TimeBaseStructure);
   TIM_ARRPreloadConfig(TIM8,ENABLE);
   TIM_Cmd(TIM8, ENABLE);
   
   GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9;
   GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;
   GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
   GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
   GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL;
   GPIO_Init(GPIOC, &GPIO_InitStructure);
   GPIO_PinAFConfig(GPIOC, GPIO_PinSource9, GPIO_AF_TIM8);
   
   TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1;
   TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
   TIM_OCInitStructure.TIM_OutputNState = TIM_OutputNState_Disable;
   TIM_OCInitStructure.TIM_Pulse = 0;
   TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High;
   TIM_OCInitStructure.TIM_OCIdleState = TIM_OCIdleState_Set;

   TIM_OC4Init(TIM8, &TIM_OCInitStructure);
   TIM_OC4PreloadConfig(TIM8, TIM_OCPreload_Enable);
   TIM_CtrlPWMOutputs(TIM8, ENABLE);
   
);

NRT(
   if(PIN(fan) > 0)
      GPIO_SetBits(FAN_PORT, FAN_PIN);
   else
      GPIO_ResetBits(FAN_PORT, FAN_PIN);

   if(PIN(red) > 0)
      GPIO_SetBits(LED_R_PORT, LED_R_PIN);
   else
      GPIO_ResetBits(LED_R_PORT, LED_R_PIN);

   if(PIN(green) > 0)
      GPIO_SetBits(LED_G_PORT, LED_G_PIN);
   else
      GPIO_ResetBits(LED_G_PORT, LED_G_PIN);

   TIM8->CCR4 = (int)CLAMP(PIN(brake) * 8400, 0, TIM8->ARR - 1);

);

ENDCOMP;
