#include "ets_sys.h"
#include "uart.h"
#include "osapi.h"
#include "adc.h"
#include "user_config.h"
#include "version.h"
#include "gpio.h"

extern uint8_t at_wifiMode;

void user_init(void)
{
  uint32 adc_value;
  char temp[128];
  
  // no os_printf
  system_set_os_print(0x00);
  
  // disable WiFi modem
  // not implemented in SDK v0.9.1
  
  // change baud rate from 74880 to 115200 
  uart_init(BIT_RATE_115200, BIT_RATE_115200);
  
  // print welcome msg and FW/SDK versions on UART0
  uart0_sendStr("\rESP8266EX ready! \r\n");
  os_sprintf(temp,"FW:%04X SDK:%04X\r\n\n", FW_VERSION,SDK_VERSION);
  
  // init LED on GPIO4
  // disable pullup and pulldown
  PIN_PULLUP_DIS(PERIPHS_IO_MUX_GPIO4_U);
  PIN_PULLDWN_DIS(PERIPHS_IO_MUX_GPIO4_U);
  // set unction GPIO (well, GPIO4 know anyway only GPIO)
  PIN_FUNC_SELECT(PERIPHS_IO_MUX_GPIO4_U, FUNC_GPIO4);
  // set pin to high
  GPIO_OUTPUT_SET(GPIO_ID_PIN(4), 1);
  
  // init LED on GPIO5
  // disable pullup and pulldown
   PIN_PULLUP_DIS(PERIPHS_IO_MUX_GPIO5_U);
   PIN_PULLDWN_DIS(PERIPHS_IO_MUX_GPIO5_U);
  // set unction GPIO (well, GPIO5 know anyway only GPIO)
  PIN_FUNC_SELECT(PERIPHS_IO_MUX_GPIO5_U, FUNC_GPIO5);
  // set pin to high
  GPIO_OUTPUT_SET(GPIO_ID_PIN(5), 1);
  
  // init LED on GPIO16
  // GPIO16 is "bit special", check gpio16.c
  gpio16_output_conf();
  // set pin to high
  gpio16_output_set(1);
  
  uart0_sendStr(temp);
  adc_value = 0;
  while(1)
  {
	  // get ADC value
	  adc_value = adc_read();
	  os_delay_us(50000);
	  // print ADC value on UART0
	  os_sprintf(temp," ADC value: %4d mV \r ", adc_value * 1000 / 1024 );
	  uart0_sendStr(temp);
	  
	  // ADC low LED on
	  if (adc_value < 1) GPIO_OUTPUT_SET(GPIO_ID_PIN(4), 0);
	  // or off
	  	else GPIO_OUTPUT_SET(GPIO_ID_PIN(4), 1);

	  //  ADC in range LED on
	  if ((0 < adc_value) & (adc_value < 1024)) gpio16_output_set(0);
	  // or off
	  	else gpio16_output_set(1);
	  
	  // ADC high LED on
	  if (adc_value > 1023) GPIO_OUTPUT_SET(GPIO_ID_PIN(5), 0);
	  // or off
	  	else GPIO_OUTPUT_SET(GPIO_ID_PIN(5), 1);
	  	  
	  os_delay_us(49995);
  }
}
