/*==============================================================================
 * Шаблон проекта для К1921ВК035 с использованием бибилотеки PLIB035
 *------------------------------------------------------------------------------
 * ЦНИИ СЭТ, Разваляев Алексей <wot890089@mail.ru>
 *==============================================================================
 *                                  ЦНИИ СЭТ
 *==============================================================================
 */

//-- Includes ------------------------------------------------------------------
#include "main.h"

void restart_receive(void);
void heartbit(void);
//-- Defines -------------------------------------------------------------------
uint8_t rxbuff[10] = {0};
uint16_t adc_buff[2][100];
//-- Peripheral init functions -------------------------------------------------
void periph_init()
{
  sysclk_init();
  uart_init_first();
  adc_init_first();
  tmr_init_first();
  gpio_init();
#ifdef RETARGET
  retarget_init();
#endif
  printf("\nAll peripherals inited, SYSCLK = %3d MHz\n", (int)(SystemCoreClock / 1E6));
  
  
  uart_set_callback(&huart1, UART_Callback_Rx, &restart_receive);
  uart_start(&huart1, UART_FIFOLevel_1_8, UART_FIFOLevel_1_8);
  
  tmr_set_callback(&htmr2, 0, &heartbit);
  tmr_start(&htmr0);
  tmr_start(&htmr1);
  tmr_start(&htmr2);
  adc_seq_start(&hadc, ADC_SEQ_Num_0, adc_buff, 100);
}

//-- Main ----------------------------------------------------------------------
int main()
{
  periph_init();
  uint8_t cnt;
  uart_receive_it(&huart1, rxbuff, sizeof(rxbuff));
  uint32_t prev_tick;
  tmr_delay_start(&htmr0, &prev_tick);
  while (1) {
    if(tmr_delay_done(&htmr0, 1000000, &prev_tick))
    {
      tmr_delay_start(&htmr0, &prev_tick);
      GPIO_ToggleBits(GPIOA, GPIO_Pin_8);
      adc_sw_start();
    }
    tmr_delay(&htmr0, 100000);
    GPIO_ToggleBits(GPIOA, GPIO_Pin_7);
//    uart_transmit_it(&huart1, (uint8_t*)"Hello World: ", sizeof("Hello World: ")-1);
//    uart_transmit_it(&huart1, (uint8_t*)"delay 500\r\n", sizeof("delay 500\r\n")-1);
  };
  //return 0;
}

void restart_receive(void)
{
  uart_receive_it(&huart1, rxbuff, sizeof(rxbuff));
  uart_transmit_it(&huart1, rxbuff, sizeof(rxbuff));
}

void heartbit(void)
{
  uart_transmit(&huart1, (uint8_t *)"\r\nTick 1 sec\r\n", sizeof("\r\nTick 1 sec\r\n")-1, 1000);
}

//-- Assert --------------------------------------------------------------------
void Error_Handler(void)
{
  __disable_irq();
  while (1)
  {
  }
}

#if defined USE_FULL_ASSERT
void assert_failed(uint8_t* file, uint32_t line)
{
  printf("Assert failed: file %s on line %d\n", file, (int)line);
  while (1) {
  };
}
#endif /* USE_FULL_ASSERT */
