Exemple #1
0
/**
 * Handle a GPIO interrupt.
 * We have arrived in this callback function because the state of a GPIO pin has changed
 * and it is time to record that change.
 */
static void CALLED_FROM_INTERRUPT intrHandlerCB(
    uint32 interruptMask, //!< A mask indicating which GPIOs have changed.
    void *arg             //!< Optional argument.
  ) {
  // Given the interrupt mask, we as if bit "x" is on.  If it is, then that is defined as meaning
  // that the state of GPIO "x" has changed so we want to raised an event that indicates that this
  // has happened...
  // Once we have handled the interrupt flags, we need to acknowledge the interrupts so
  // that the ESP8266 will once again cause future interrupts to be processed.

  //os_printf_plus(">> intrHandlerCB\n");
  gpio_intr_ack(interruptMask);
  // We have a mask of interrupts that have happened.  Go through each bit in the mask
  // and, if it is on, then an interrupt has occurred on the corresponding pin.
  int pin;
  for (pin=0; pin<JSH_PIN_COUNT; pin++) {
    if ((interruptMask & (1<<pin)) != 0) {
      // Pin has changed so push the event that says pin has changed.
      jshPushIOWatchEvent(pinToEV_EXTI(pin));
      gpio_pin_intr_state_set(GPIO_ID_PIN(pin), GPIO_PIN_INTR_ANYEDGE);
    }
  }
  //os_printf_plus("<< intrHandlerCB\n");
}
/******************************************************************************
 * FunctionName : user_humiture_init
 * Description  : init humiture function, include key and mvh3004
 * Parameters   : none
 * Returns      : none
*******************************************************************************/
void ICACHE_FLASH_ATTR
user_sensor_init(uint8 active)
{
    user_link_led_init();

    wifi_status_led_install(SENSOR_WIFI_LED_IO_NUM, SENSOR_WIFI_LED_IO_MUX, SENSOR_WIFI_LED_IO_FUNC);

    if (wifi_get_opmode() != SOFTAP_MODE) {
        single_key[0] = key_init_single(SENSOR_KEY_IO_NUM, SENSOR_KEY_IO_MUX, SENSOR_KEY_IO_FUNC,
                                        user_sensor_long_press, NULL);

        keys.key_num = SENSOR_KEY_NUM;
        keys.single_key = single_key;

        key_init(&keys);

        if (GPIO_INPUT_GET(GPIO_ID_PIN(SENSOR_KEY_IO_NUM)) == 0) {
            user_sensor_long_press();
        }
    }

#if HUMITURE_SUB_DEVICE
    user_mvh3004_init();
    user_mvh3004_read_th(humiture_data);
#endif

#ifdef SENSOR_DEEP_SLEEP
    if (wifi_get_opmode() != STATIONAP_MODE) {
        if (active == 1) {
            user_sensor_deep_sleep_init(SENSOR_DEEP_SLEEP_TIME / 1000 / 3);
        } else {
            user_sensor_deep_sleep_init(SENSOR_DEEP_SLEEP_TIME / 1000 / 3 * 2);
        }
    }
#endif
}
Exemple #3
0
static void ICACHE_FLASH_ATTR stledIsr(void)
{
	switch (opState) {
	case STLED_OFF:
		GPIO_OUTPUT_SET(GPIO_ID_PIN(STLED_GPIO), 1); 
		break;
	case STLED_ON:
		GPIO_OUTPUT_SET(GPIO_ID_PIN(STLED_GPIO), 0); 
		break;
	case STLED_BLINK_SLOW:
		GPIO_OUTPUT_SET(GPIO_ID_PIN(STLED_GPIO), ((counter>>2)&1u)); 
		break;
	case STLED_BLINK_FAST:
		GPIO_OUTPUT_SET(GPIO_ID_PIN(STLED_GPIO), (counter&1u)); 
		break;
	case STLED_BLINK_HB:
		if ((counter&7u) ==0 || (counter&7u) == 2 || (counter&7u) == 4)
			GPIO_OUTPUT_SET(GPIO_ID_PIN(STLED_GPIO), 0);
		else
			GPIO_OUTPUT_SET(GPIO_ID_PIN(STLED_GPIO), 1);
		break;
	}
	++counter;
}
void ICACHE_FLASH_ATTR SEND_WS_0()
{
	uint8_t time;
	time = 4; while(time--) WRITE_PERI_REG( PERIPHS_GPIO_BASEADDR + GPIO_ID_PIN(0), 1 );
	time = 9; while(time--) WRITE_PERI_REG( PERIPHS_GPIO_BASEADDR + GPIO_ID_PIN(0), 0 );
}
Exemple #5
0
void ICACHE_FLASH_ATTR
supla_esp_gpio_init(void) {

	switch_cfgbtn_state_check = 0;
	switch_cfgbtn_last_state = -1;
	switch_cfgbtn_counter = 0;

	#if defined(USE_GPIO3) || defined(UART_SWAP)
		 system_uart_swap ();
	#endif

	ETS_GPIO_INTR_DISABLE();

	GPIO_PORT_INIT;

    #ifdef USE_GPIO16_INPUT
	gpio16_input_conf();
    #endif

	#ifdef USE_GPIO16_OUTPUT
	gpio16_output_conf();
	#endif


    #ifdef USE_GPIO3
	   PIN_FUNC_SELECT(PERIPHS_IO_MUX_U0RXD_U, FUNC_GPIO3);
	   PIN_PULLUP_DIS(PERIPHS_IO_MUX_U0RXD_U);
    #endif

    #ifdef BTN_PULLUP
        #if CFG_PORT == 0
	      PIN_PULLUP_EN(PERIPHS_IO_MUX_GPIO0_U);
        #elif CFG_PORT == 2
          PIN_PULLUP_EN(PERIPHS_IO_MUX_GPIO2_U);
        #elif CFG_PORT == 4
	      PIN_PULLUP_EN(PERIPHS_IO_MUX_GPIO4_U);
		#elif CFG_PORT == 12
	     PIN_PULLUP_EN(PERIPHS_IO_MUX_MTDI_U);
		#elif CFG_PORT == 13
	      PIN_PULLUP_EN(PERIPHS_IO_MUX_MTCK_U);
		#elif CFG_PORT == 14
	      PIN_PULLUP_EN(PERIPHS_IO_MUX_MTMS_U);
       #endif
    #endif

    #ifdef LED_RED_PORT
      #if LED_RED_PORT != 16
	    gpio_pin_intr_state_set(GPIO_ID_PIN(LED_RED_PORT), GPIO_PIN_INTR_DISABLE);
      #endif
    #endif

    #ifdef LED_GREEN_PORT
    gpio_pin_intr_state_set(GPIO_ID_PIN(LED_GREEN_PORT), GPIO_PIN_INTR_DISABLE);
    #endif

    #ifdef LED_BLUE_PORT
    gpio_pin_intr_state_set(GPIO_ID_PIN(LED_BLUE_PORT), GPIO_PIN_INTR_DISABLE);
    #endif


    #ifdef RELAY1_PORT
    gpio_pin_intr_state_set(GPIO_ID_PIN(RELAY1_PORT), GPIO_PIN_INTR_DISABLE);
    #endif

    #ifdef RELAY2_PORT
    gpio_pin_intr_state_set(GPIO_ID_PIN(RELAY2_PORT), GPIO_PIN_INTR_DISABLE);
    #endif

	#ifdef ZAM_INPUT1
	supla_esp_gpio_enable_input_port(ZAM_INPUT1);
	#endif

	#ifdef ZAM_INPUT2
	supla_esp_gpio_enable_input_port(ZAM_INPUT2);
	#endif

	ETS_GPIO_INTR_ENABLE();

	keys.key_num = 0;

	single_key[0] = key_init_single(CFG_PORT, supla_esg_gpio_cfg_pressed, supla_esg_gpio_manual_pressed);
	keys.key_num++;

    #if defined(BUTTON1_PORT) && defined(RELAY1_PORT)

		single_key[keys.key_num] = key_init_single(BUTTON1_PORT, NULL, supla_esg_gpio_button1_pressed);
		keys.key_num++;

    #endif

	#if defined(BUTTON1_PORT) && defined(RELAY1_PORT)

		single_key[keys.key_num] = key_init_single(BUTTON2_PORT, NULL, supla_esg_gpio_button2_pressed);
		keys.key_num++;

	#endif

	keys.single_key = single_key;
	keys.handler = supla_esp_key_intr_handler;

    #ifdef RELAY_STATE_RESTORE

		struct rst_info *rtc_info = system_get_rst_info();

		#ifdef RELAY1_PORT
			if ( rtc_info->reason == 0 ) {
				   supla_esp_gpio_relay1_hi(supla_esp_state.Relay1);
			}
		#endif

		#ifdef RELAY2_PORT
		    if ( rtc_info->reason == 0 ) {
			   supla_esp_gpio_relay2_hi(supla_esp_state.Relay2);
			}
		#endif

    #elif defined(RESET_RELAY_PORT)

		#ifdef RELAY1_PORT
		   supla_esp_gpio_relay1_hi(RELAY_INIT_VALUE);
		#endif

		#ifdef RELAY2_PORT
		   supla_esp_gpio_relay2_hi(RELAY_INIT_VALUE);
		#endif

    #endif

	key_init(&keys);


    GPIO_PORT_POST_INIT;

    supla_esp_gpio_init_time = system_get_time();

}
void Softuart_Intr_Handler(Softuart *s)
{
	uint8_t level, gpio_id;
// clear gpio status. Say ESP8266EX SDK Programming Guide in  5.1.6. GPIO interrupt handler

    uint32_t gpio_status = GPIO_REG_READ(GPIO_STATUS_ADDRESS);
	gpio_id = Softuart_Bitcount(gpio_status);

	//if interrupt was by an attached rx pin
    if (gpio_id != 0xFF)
    {
		//load instance which has rx pin on interrupt pin attached
		s = _Softuart_GPIO_Instances[gpio_id];

// disable interrupt for GPIO0
        gpio_pin_intr_state_set(GPIO_ID_PIN(s->pin_rx.gpio_id), GPIO_PIN_INTR_DISABLE);

// Do something, for example, increment whatyouwant indirectly
		//check level
		level = GPIO_INPUT_GET(GPIO_ID_PIN(s->pin_rx.gpio_id));
		if(!level) {
			//pin is low
			//therefore we have a start bit

			//wait till start bit is half over so we can sample the next one in the center
			os_delay_us(s->bit_time/2);	

			//now sample bits
			unsigned i;
			unsigned d = 0;
			unsigned start_time = 0x7FFFFFFF & system_get_time();

			for(i = 0; i < 8; i ++ )
			{
				while ((0x7FFFFFFF & system_get_time()) < (start_time + (s->bit_time*(i+1))))
				{
					//If system timer overflow, escape from while loop
					if ((0x7FFFFFFF & system_get_time()) < start_time){break;}
				}
				//shift d to the right
				d >>= 1;

				//read bit
				if(GPIO_INPUT_GET(GPIO_ID_PIN(s->pin_rx.gpio_id))) {
					//if high, set msb of 8bit to 1
					d |= 0x80;
				}
			}

			//store byte in buffer

			// if buffer full, set the overflow flag and return
			uint8 next = (s->buffer.receive_buffer_tail + 1) % SOFTUART_MAX_RX_BUFF;
			if (next != s->buffer.receive_buffer_head)
			{
			  // save new data in buffer: tail points to where byte goes
			  s->buffer.receive_buffer[s->buffer.receive_buffer_tail] = d; // save new byte
			  s->buffer.receive_buffer_tail = next;
			} 
			else 
			{
			  s->buffer.buffer_overflow = 1;
			}

			//wait for stop bit
			os_delay_us(s->bit_time);	

			//done
		}
Exemple #7
0
//-----------------------------------------------------------------------------------------
void static dht11_protocol(uint32 gpio_status,int cause)
{
    static int actual_bit;

    switch(cause) // 0 = gpio interrupt, 1=timer
    {
        case 0: // gpio edge
        {
// disable interrupt for GPIO
            gpio_pin_intr_state_set(GPIO_ID_PIN(dht11_gpio), GPIO_PIN_INTR_DISABLE);
// clear interrupt status for GPIO
            GPIO_REG_WRITE(GPIO_STATUS_W1TC_ADDRESS, gpio_status & GPIO_Pin(dht11_gpio));
// Reactivate interrupts for GPIO0
            gpio_pin_intr_state_set(GPIO_ID_PIN(dht11_gpio), GPIO_PIN_INTR_ANYEGDE);

            switch(sStatus)
            {
                case dht11_connecting:
                    if(GPIO_INPUT_GET(dht11_gpio))
                    {
// Rising edge ?? Error.
                        dht11_set_read_nok();
                        dht11_set_standby();
                    }
                    else
                    {
                        sStatus = dht11_mark_connecting;
                    }
                break;
                case dht11_mark_connecting:
                    if(!GPIO_INPUT_GET(dht11_gpio))
                    {
// Falling edge ?? Error.
                        dht11_set_read_nok();
                        dht11_set_standby();
                    }
                    else
                    {
                        sStatus = dht11_waiting_bit;
                    }
                break;
                case dht11_waiting_bit:
                    if(GPIO_INPUT_GET(dht11_gpio))
                    {
// Rising edge ?? Error.
                        dht11_set_read_nok();
                        dht11_set_standby();
                    }
                    else
                    {
                        sStatus = dht11_mark_bit;
                        actual_bit=0;
                    }
                break;
                case dht11_mark_bit:
                    if(! GPIO_INPUT_GET(dht11_gpio))
                    {
// Falling edge ?? Error.
                        dht11_set_read_nok();
                        dht11_set_standby();
                    }
                    else
                    {
                        if(actual_bit >= 40)
                        {
                            dht11_set_standby();     // finish OK
                        }
                        else
                        {
                            last_timer = system_get_time();
                            sStatus = dht11_read_bit;
                        }
                    }
                break;
                case dht11_read_bit:
                    if(GPIO_INPUT_GET(dht11_gpio))
                    {
// Rising edge ?? Error.
                        dht11_set_read_nok();
                        dht11_set_standby();
                    }
                    else
                    {
// 26-28 uS means 0.   70 uS means 1
                        int bit_data = ((system_get_time()-last_timer) > 40) ? 1:0;
                        int actual_byte = actual_bit / 8;
                        sRead[actual_byte] <<= 1;
                        sRead[actual_byte] |= bit_data;
                        actual_bit++;
                        sStatus = dht11_mark_bit;
                    }
                break;
                case dht11_standby:
                case dht11_mark:
                default:
                    dht11_set_standby();
                break;
            }
        }
        break;
        case 1: //timer
            switch(sStatus)
            {
                case dht11_mark: // end of mark
                    sStatus = dht11_connecting;
                    // GPIO as Output to high level by default.
                    GPIO_OUTPUT_SET(dht11_gpio,1);
                    GPIO_AS_INPUT(dht11_gpio);

                    ETS_GPIO_INTR_DISABLE();

                    gpio_register_set(GPIO_PIN_ADDR(dht11_gpio),
                                       GPIO_PIN_INT_TYPE_SET(GPIO_PIN_INTR_DISABLE)  |
                                       GPIO_PIN_PAD_DRIVER_SET(GPIO_PAD_DRIVER_DISABLE) |
                                       GPIO_PIN_SOURCE_SET(GPIO_AS_PIN_SOURCE));

                    GPIO_REG_WRITE(GPIO_STATUS_W1TC_ADDRESS, BIT(dht11_gpio));

                    gpio_pin_intr_state_set(GPIO_ID_PIN(dht11_gpio), GPIO_PIN_INTR_ANYEGDE);

                    ETS_GPIO_INTR_ENABLE();

                    os_timer_disarm(&dht11_timer);
                    os_timer_arm(&dht11_timer,6,0); // maximun frame time 4.8 ms
                break;
                case dht11_connecting:
                case dht11_mark_connecting:
                case dht11_waiting_bit:
                case dht11_mark_bit:
                case dht11_read_bit:
                default:
                    dht11_set_read_nok();
                    dht11_set_standby();
                break;
            }

        default:
        break;
    }
}
Exemple #8
0
void ICACHE_FLASH_ATTR
user_link_led_output(uint8 level)
{
    GPIO_OUTPUT_SET(GPIO_ID_PIN(PLUG_LINK_LED_IO_NUM), level);
}
Exemple #9
0
void ICACHE_FLASH_ATTR
user_link_led_timer_done(void)
{
    os_timer_disarm(&link_led_timer);
    GPIO_OUTPUT_SET(GPIO_ID_PIN(PLUG_LINK_LED_IO_NUM), 0);
}
Exemple #10
0
/**
 * Sends a ping, and returns the number of microseconds it took to receive a response.
 * Will give up after maxPeriod (with false as return value)
 */
bool ICACHE_FLASH_ATTR
ping_pingUs(Ping_Data *pingData, uint32_t maxPeriod, uint32_t* response) {
  uint32_t timeOutAt = system_get_time() + maxPeriod;
  ping_echoEnded = false;
  ping_echoStarted = false;
  ping_timeStamp0 = system_get_time();

  if (!pingData->isInitiated) {
    *response = 0;
    os_printf("ping_pingUs: Error: not initiated properly.\n");
    return false;
  }
  if (ping_currentEchoPin >= 0) {
    // this should not really happend, how did you end up here?
    *response = 0;
    os_printf("ping_pingUs: Error: another ping is already running.\n");
    return false;
  }

  uint32_t echoPin = pingData->echoPin;
  uint32_t triggerPin = pingData->triggerPin;
  ping_currentEchoPin = pingData->echoPin;

  while (GPIO_INPUT_GET(echoPin)) {
    if (system_get_time() > timeOutAt) {
      // echo pin never went low, something is wrong.
      // turns out this happens whenever the sensor doesn't receive any echo at all.

      //os_printf("ping_ping: Error: echo pin %d permanently high %d?.\n", echoPin, GPIO_INPUT_GET(echoPin));
      *response = system_get_time() - ping_timeStamp0;

      // Wake up a sleeping device
      GPIO_OUTPUT_SET(triggerPin, PING_TRIGGER_DEFAULT_STATE);
      os_delay_us(50);
      GPIO_OUTPUT_SET(triggerPin, !PING_TRIGGER_DEFAULT_STATE);
      os_delay_us(50);
      GPIO_OUTPUT_SET(triggerPin, PING_TRIGGER_DEFAULT_STATE);
      ping_disableInterrupt(ping_currentEchoPin);
      ping_currentEchoPin = -1;
      return false;
    }
    os_delay_us(PING_POLL_PERIOD);
  }

  GPIO_OUTPUT_SET(triggerPin, 1);
  os_delay_us(PING_TRIGGER_LENGTH);
  GPIO_OUTPUT_SET(triggerPin, 0);
  
  if (echoPin == triggerPin) {
    // force the trigger pin low for 50us. This helps stabilise echo pin when 
    // running in single pin mode. 
    os_delay_us(50);
  }
  
  GPIO_DIS_OUTPUT(echoPin);
  gpio_pin_intr_state_set(GPIO_ID_PIN(echoPin), GPIO_PIN_INTR_POSEDGE);

  while (!ping_echoEnded) {
    if (system_get_time() > timeOutAt) {
      *response = system_get_time() - ping_timeStamp0;
      ping_disableInterrupt(ping_currentEchoPin);
      ping_currentEchoPin = -1;
      return false;
    }
    os_delay_us(PING_POLL_PERIOD);
  }

  *response = ping_timeStamp1 - ping_timeStamp0;
  if (ping_timeStamp1 < ping_timeStamp0 || *response < 50) {
    // probably a previous echo or clock overflow - false result
    ping_disableInterrupt(ping_currentEchoPin);
    ping_currentEchoPin = -1;
    return false;
  }
  return true;
}
int platform_gpio_mode( unsigned pin, unsigned mode, unsigned pull )
{
  // NODE_DBG("Function platform_gpio_mode() is called. pin_mux:%d, func:%d\n",pin_mux[pin],pin_func[pin]);
  if (pin >= NUM_GPIO)
    return -1;
  if(pin == 0){
    if(mode==PLATFORM_GPIO_INPUT)
      gpio16_input_conf();
    else
      gpio16_output_conf();
    return 1;
  }

  platform_pwm_close(pin);    // closed from pwm module, if it is used in pwm

  switch(pull){
    case PLATFORM_GPIO_PULLUP:
      PIN_PULLDWN_DIS(pin_mux[pin]);
      PIN_PULLUP_EN(pin_mux[pin]);
      break;
    case PLATFORM_GPIO_PULLDOWN:
      PIN_PULLUP_DIS(pin_mux[pin]);
      PIN_PULLDWN_EN(pin_mux[pin]);
      break;
    case PLATFORM_GPIO_FLOAT:
      PIN_PULLUP_DIS(pin_mux[pin]);
      PIN_PULLDWN_DIS(pin_mux[pin]);
      break;
    default:
      PIN_PULLUP_DIS(pin_mux[pin]);
      PIN_PULLDWN_DIS(pin_mux[pin]);
      break;
  }

  switch(mode){
    case PLATFORM_GPIO_INPUT:
#if defined( LUA_USE_MODULES_GPIO ) && defined( GPIO_INTERRUPT_ENABLE )
      lua_gpio_unref(pin);    // unref the lua ref call back.
#endif
      GPIO_DIS_OUTPUT(pin_num[pin]);
    case PLATFORM_GPIO_OUTPUT:
      ETS_GPIO_INTR_DISABLE();
#ifdef GPIO_INTERRUPT_ENABLE
      pin_int_type[pin] = GPIO_PIN_INTR_DISABLE;
#endif
      PIN_FUNC_SELECT(pin_mux[pin], pin_func[pin]);
      //disable interrupt
      gpio_pin_intr_state_set(GPIO_ID_PIN(pin_num[pin]), GPIO_PIN_INTR_DISABLE);
      //clear interrupt status
      GPIO_REG_WRITE(GPIO_STATUS_W1TC_ADDRESS, BIT(pin_num[pin]));
      GPIO_REG_WRITE(GPIO_PIN_ADDR(GPIO_ID_PIN(pin_num[pin])), GPIO_REG_READ(GPIO_PIN_ADDR(GPIO_ID_PIN(pin_num[pin]))) & (~ GPIO_PIN_PAD_DRIVER_SET(GPIO_PAD_DRIVER_ENABLE))); //disable open drain; 
      ETS_GPIO_INTR_ENABLE();
      break;
#ifdef GPIO_INTERRUPT_ENABLE
    case PLATFORM_GPIO_INT:
      ETS_GPIO_INTR_DISABLE();
      PIN_FUNC_SELECT(pin_mux[pin], pin_func[pin]);
      GPIO_DIS_OUTPUT(pin_num[pin]);
      gpio_register_set(GPIO_PIN_ADDR(GPIO_ID_PIN(pin_num[pin])), GPIO_PIN_INT_TYPE_SET(GPIO_PIN_INTR_DISABLE)
                        | GPIO_PIN_PAD_DRIVER_SET(GPIO_PAD_DRIVER_DISABLE)
                        | GPIO_PIN_SOURCE_SET(GPIO_AS_PIN_SOURCE));
      ETS_GPIO_INTR_ENABLE();
      break;
#endif
    default:
      break;
  }
  return 1;
}
LOCAL void ICACHE_FLASH_ATTR user_link_led_init(void) {
    PIN_FUNC_SELECT(SENSOR_LINK_LED_IO_MUX, SENSOR_LINK_LED_IO_FUNC);
    PIN_FUNC_SELECT(SENSOR_UNUSED_LED_IO_MUX, SENSOR_UNUSED_LED_IO_FUNC);
    GPIO_OUTPUT_SET(GPIO_ID_PIN(SENSOR_UNUSED_LED_IO_NUM), 0);
}
Exemple #13
0
// initialize the custom stuff that goes beyond esp-link
void user_init()
{
	// Initialize the GPIO subsystem.
	gpio_init();

	/* ====================================== */
	/* UART                                   */
	/* ====================================== */

	// Initialize UART0 and UART1
	/* NOTE: UART1 and I2S share same GPIO. Cannot use simultaneously. */
	uart_init( BIT_RATE_115200, BIT_RATE_115200 );

//	uart0_sendStr( "\nUART0 - USED TO PROGRAM THE MODULE\n" );

	os_printf("\n===================\nUART1 - DEBUG OUPUT\n===================\n");

	/* NOTE: PWM CANNOT BE USED SIMULTANEOUSLY WITH HW TIMER */
#if 0
	/* ====================================== */
	/* PWM                                    */
	/* ====================================== */

    uint32  pwm_period = 1000;
	uint32 pwm_duty[PWM_CHANNEL] = {0};


    uint32 io_info[][3] = {   {PWM_0_OUT_IO_MUX,PWM_0_OUT_IO_FUNC,PWM_0_OUT_IO_NUM},
    		                  {PWM_1_OUT_IO_MUX,PWM_1_OUT_IO_FUNC,PWM_1_OUT_IO_NUM},
    		              };

	/* PIN FUNCTION INIT FOR PWM OUTPUT */
	pwm_init(pwm_period, pwm_duty, PWM_CHANNEL, io_info);

	/* set pwm_duty cycle */
	pwm_set_duty (14185, 0);
	pwm_set_duty (22222, 1); // todo: explain why 22222 is the highest possible value

	/* start PWM */
	pwm_start(); // NOTE: PWM causes spikes in other GPIOs
#endif


	/* ====================================== */
	/* GPIO INTERRPUT                         */
	/* ====================================== */

	/* Set GPIO12 in GPIO mode */
	PIN_FUNC_SELECT( PERIPHS_IO_MUX_MTDI_U, FUNC_GPIO12 );

	/* Set GPIO12 as input */
	GPIO_DIS_OUTPUT( GPIO_ID_PIN(12) );

	/* Disable all GPIO interrupts */
	ETS_GPIO_INTR_DISABLE();

	/* Set a GPIO callback function */
	ETS_GPIO_INTR_ATTACH( gpioCallback, NULL );

	/* Configure the type of edge */
	gpio_pin_intr_state_set( GPIO_ID_PIN(12), GPIO_PIN_INTR_ANYEDGE );

	ETS_GPIO_INTR_ENABLE();


	/* ====================================== */
	/* SOFTWARE TIMER                         */
	/* ====================================== */

	// Set GPIO0 to output mode
	PIN_FUNC_SELECT(PERIPHS_IO_MUX_GPIO0_U, FUNC_GPIO0);

	//Set GPIO0 low
	gpio_output_set(0, RELAY_PIN, RELAY_PIN, 0);

	/* disarm timer */
	os_timer_disarm((ETSTimer*)&some_timer);

	/* set callback */
	os_timer_setfn((ETSTimer*)&some_timer, (os_timer_func_t *) softwareTimerCallback, NULL);

	/* arm the timer -> os_timer_arm(<pointer>, <period in ms>, <fire periodically>) */
	os_timer_arm((ETSTimer*)&some_timer, 10, 1);

	/* ====================================== */
	/* OS TASK                                */
	/* ====================================== */

	/* setup OS task */
//	system_os_task(user_procTask, user_procTaskPrio, user_procTaskQueue, user_procTaskQueueLen);

	/* send a message to OS task (fire task) */
//	system_os_post(user_procTaskPrio, 0, 0 );


	/* ====================================== */
	/* HARDWARE TIMER                         */
	/* ====================================== */

	/* The hardware timer is used to indicate when a complete IR message frame should have
	 * arrived in order to process the received data and calculate the IR command.
	 *
	 * It is configured in "one-shot" mode. It is started when the beginning of an
	 * IR message frame is detected and stopped after the complete message frame has been read.
	 * This means that the duration of the HW timer should be longer than the duration of
	 * the longest message frame. In the NEC IR tranmission protocol all message frames have
	 * a duration of approximately 67.5ms.
	 */

	/* load the HW TIMER */
	uint32 ticks = usToTicks(70000); // 70ms
	RTC_REG_WRITE(FRC1_LOAD_ADDRESS, ticks);

	/* register callback function */
	ETS_FRC_TIMER1_INTR_ATTACH( hwTimerCallback, NULL );

	/* enable interrupts */
	TM1_EDGE_INT_ENABLE();
	ETS_FRC1_INTR_ENABLE();

	/* don't start timer yet */
	/* the timer is started inside the GPIO INT callback */


	/* ====================================== */
	/* UDP SERVER                         	  */
	/* ====================================== */

	/* usage:	echo <data> | nc -wl -u <ip address> <port>
	 * example: echo "foo" | nc -w1 -u 192.168.1.187 7777 */

	/* allocate space for server */
	pUdpServer = (struct espconn *) os_zalloc(sizeof(struct espconn));

	/* clear allocated memory */
	ets_memset(pUdpServer, 0, sizeof(struct espconn));

	/* create the server */
	espconn_create(pUdpServer);

	/* set the type of server */
	pUdpServer->type = ESPCONN_UDP;

	/* allocate memory for UDP settings */
	pUdpServer->proto.udp = (esp_udp *) os_zalloc(sizeof(esp_udp));

	/* set the port that the server will be listening to */
	pUdpServer->proto.udp->local_port = 7777;

	/* register the callback */
	espconn_regist_recvcb(pUdpServer, udpServerRxCb);

	/* start listening */
	if (espconn_create(pUdpServer))
	{
		while (1) { os_printf("Error creating a UDP server\n"); }
	}


	/* ====================================== */
	/* WIFI                         	  	  */
	/* ====================================== */

	wifi_set_opmode(STATION_MODE);

	wifi_station_get_config_default(&stconf);

//	os_strncpy((char*) stconf.ssid, "TP-LINK_2.4GHz_FC2E51", 32);
//	os_strncpy((char*) stconf.password, "tonytony", 64);

	os_strncpy((char*) stconf.ssid, "WLAN-PUB", 32);
	os_strncpy((char*) stconf.password, "", 64);

//	os_strncpy((char*) stconf.ssid, "MAD air", 32);
//	os_strncpy((char*) stconf.password, "glioninlog", 64);

	stconf.bssid_set = 0;
	wifi_station_set_config(&stconf);

//	/* ====================================== */
//	/* WS2812 LED STRIP                	  	  */
//	/* ====================================== */
//
//	/* NOTE: UART1 and I2S share same GPIO. Cannot use simultaneously. */
//	ws2812_init();
//
//	/*						G		R		B			*/
//	uint8_t ledout[] = 	{
//							0xff,	0x00,	0x00, 		//4th
////							0xff,	0x00,	0x00,		//3rd
////							0x00,	0xff,	0x00,		//2nd
////							0x00,	0x00,	0xff, 		//1st
//						};
//
//#if 0
//		os_printf("\r\nB R G: %x %x %x\r\n", ledout[0], ledout[1],ledout[2]);
//#endif
//
//	ws2812_push( ledout, sizeof( ledout ) );

	/* ====================================== */
	/* TCP CONNECTION                    	  */
	/* ====================================== */

	/* allocate space for server */
	pTcpConn = (struct espconn *) os_zalloc(sizeof(struct espconn));

	/* clear allocated memory */
	ets_memset(pTcpConn, 0, sizeof(struct espconn));

	/* set the type of connection */
	pTcpConn->type = ESPCONN_TCP;

	/* set state to NONE */
	pTcpConn->state = ESPCONN_NONE;

	/* allocate memory for TCP settings */
	pTcpConn->proto.tcp = (esp_tcp *) os_zalloc(sizeof(esp_tcp));

	/* set the port that the connection will be listening to */
	pTcpConn->proto.tcp->local_port = espconn_port();

	/* set the remote port and IP address */
	pTcpConn->proto.tcp->remote_port = 80;
	os_memcpy(pTcpConn->proto.tcp->remote_ip, server_ip_address, sizeof(server_ip_address));

	/* register callbacks */
	espconn_regist_connectcb(pTcpConn, tcpConnCb);
	espconn_regist_reconcb(pTcpConn, tcpReconnCb);

	/* disarm timer */
	os_timer_disarm((ETSTimer*)&wifi_setup_timer);

	/* set callback */
	os_timer_setfn((ETSTimer*)&wifi_setup_timer, (os_timer_func_t *) wifiConnectTimerCb, NULL);

	/* arm the timer -> os_timer_arm(<pointer>, <period in ms>, <fire periodically>) */
	os_timer_arm((ETSTimer*)&wifi_setup_timer, 5000, 1);

	return;

}
FUN_ATTRIBUTE
void plug_power_change(void)
{
	uint8 pin_state = GPIO_INPUT_GET(GPIO_ID_PIN(PLUG_POWR_PIN));
	product_power_control(!pin_state);
}
void gpio_intr_handler(struct base_key_param **keys_param)
{
    uint8 i;
    uint32 gpio_status = GPIO_REG_READ(GPIO_STATUS_ADDRESS);
	uint8 gpio_id;

	struct base_key_param * single_key = NULL;

    PRINTF("Get into gpio_intr_handler, gpio_status:%u\n", gpio_status);

	for(i = 0; i < KEY_MAX_NUM; i++)
	{
		single_key = keys_param[i];

		if(single_key == NULL)
		{
			PRINTF("\r\nintr sinle_key is NULL, i:%d\r\n",i);
			continue;
		}

		gpio_id = single_key->gpio_id;
		PRINTF("\r\ngpio_id:%d, BIT(gpio_id):%d\r\n",gpio_id, BIT(gpio_id));
		if(gpio_status & BIT(gpio_id))
		{
			PRINTF("\r\n key config start....\r\n");
			//disable interrupt
			gpio_pin_intr_state_set(GPIO_ID_PIN(gpio_id), GPIO_PIN_INTR_DISABLE);
			//clear interrupt status
			GPIO_REG_WRITE(GPIO_STATUS_W1TC_ADDRESS, gpio_status & BIT(gpio_id));

			//if need to manage special gpio event,  manage here
			//example: manage key config wifi connect, need call config_key_init() first
			if(i == 0)
			{
				if(single_key->level == 1)
				{// 5s, restart & enter softap mode
					PRINTF("\r\n sinle_key->level:%d....\r\n", single_key->level);
					os_timer_disarm(&single_key->k_timer1);
					os_timer_setfn(&single_key->k_timer1, (os_timer_func_t *)key_5s_cb,
							single_key);
					os_timer_arm(&single_key->k_timer1, LONG_PRESS_COUNT, 0);
					single_key->level = 0;
					gpio_pin_intr_state_set(GPIO_ID_PIN(gpio_id), GPIO_PIN_INTR_POSEDGE);
				}
				else
				{
					// 50ms, check if this is a real key up
					PRINTF("\r\n50ms sinle_key->level:%d....\r\n", single_key->level);
					os_timer_disarm(&single_key->k_timer2);
					os_timer_setfn(&single_key->k_timer2, (os_timer_func_t *)key_50ms_cb,
							single_key);
					os_timer_arm(&single_key->k_timer2, 50, 0);
				}

				continue;
			}

			//other manage

		}
	}


}
/******************************************************************************
 * FunctionName : i2c_master_getCL
 * Description  : Internal used function -
 *					get i2c SCL bit value
 * Parameters   : NONE
 * Returns	  : uint8 - SCL bit value
*******************************************************************************/
LOCAL uint8 i2c_master_getCL(void)
{
	uint8 scl_out;
	scl_out = GPIO_INPUT_GET(GPIO_ID_PIN(pinSCL));
	return scl_out;
}
/******************************************************************************
 * FunctionName : i2c_master_getDC
 * Description  : Internal used function -
 *					get i2c SDA bit value
 * Parameters   : NONE
 * Returns	  : uint8 - SDA bit value
*******************************************************************************/
LOCAL uint8 i2c_master_getDC(void)
{
	return GPIO_INPUT_GET(GPIO_ID_PIN(pinSDA));
}
Exemple #18
0
/* ICACHE_FLASH_ATTR macro: put functions in .irom0 segment in flash */

#define MESSAGE_QUEUE_DEPTH 1

static os_timer_t os_timer;
static os_event_t queue[MESSAGE_QUEUE_DEPTH];

__attribute__((unused)) static void ICACHE_FLASH_ATTR user_rf_preinit()
{
}

static void timer(__attribute__((unused)) void *param)
{
	if (GPIO_REG_READ(GPIO_OUT_ADDRESS) & BIT2) {
		GPIO_OUTPUT_SET(GPIO_ID_PIN(2), 0);
	} else {
		GPIO_OUTPUT_SET(GPIO_ID_PIN(2), 1);
	}
}

static void ICACHE_FLASH_ATTR os_task(__attribute__((unused)) os_event_t *event)
{
	os_delay_us(10);
}

void ICACHE_FLASH_ATTR user_init()
{
	/* select GPIO2 function of pin 14
	 * (see ESP8266__Pin_List*.xlsx, ESP8266_Interface_GPIO*.pdf) */
	gpio_init();
Exemple #19
0
static void
ping_disableInterrupt(int8_t pin) {
  if (pin>0){
    gpio_pin_intr_state_set(GPIO_ID_PIN(pin), GPIO_PIN_INTR_DISABLE);
  }
}
Exemple #20
0
void ICACHE_FLASH_ATTR user_relay_init() {
	PIN_FUNC_SELECT(relay_hardware.gpio_name, relay_hardware.gpio_func);
	relay_state = GPIO_INPUT_GET(GPIO_ID_PIN(relay_hardware.gpio_id));
	webserver_register_handler_callback(RELAY_URL, relay_handler);
	device_register(NATIVE, 0, ESP8266, RELAY_URL, NULL, NULL);
}
Exemple #21
0
bool DHTRead(DHT_Sensor *sensor, DHT_Sensor_Data* output)
{
	int counter = 0;
	int laststate = 1;
	int i = 0;
	int j = 0;
	int checksum = 0;
	int data[100];
	data[0] = data[1] = data[2] = data[3] = data[4] = 0;
	uint8_t pin = GPIO_ID_PIN(sensor->port);

	// Wake up device, 250ms of high
	GPIO_OUTPUT_SET(pin, 1);
	sleepms(250);
	// Hold low for 20ms
	GPIO_OUTPUT_SET(pin, 0);
	sleepms(20);
	// High for 40ns
	GPIO_OUTPUT_SET(pin, 1);
	os_delay_us(40);
	// Set DHT_PIN pin as an input
	GPIO_DIS_OUTPUT(pin);

	// wait for pin to drop?
	while (GPIO_INPUT_GET(pin) == 1 && i < DHT_MAXCOUNT) {
		os_delay_us(1);
		i++;
	}

	if(i == DHT_MAXCOUNT)
	{
		DHT_DEBUG("DHT: Failed to get reading from GPIO%d, dying\r\n", pin);
	    return false;
	}

	// read data
	for (i = 0; i < DHT_MAXTIMINGS; i++)
	{
		// Count high time (in approx us)
		counter = 0;
		while (GPIO_INPUT_GET(pin) == laststate)
		{
			counter++;
			os_delay_us(1);
			if (counter == 1000)
				break;
		}
		laststate = GPIO_INPUT_GET(pin);
		if (counter == 1000)
			break;
		// store data after 3 reads
		if ((i>3) && (i%2 == 0)) {
			// shove each bit into the storage bytes
			data[j/8] <<= 1;
			if (counter > DHT_BREAKTIME)
				data[j/8] |= 1;
			j++;
		}
	}

	if (j >= 39) {
		checksum = (data[0] + data[1] + data[2] + data[3]) & 0xFF;
	    DHT_DEBUG("DHT%s: %02x %02x %02x %02x [%02x] CS: %02x (GPIO%d)\r\n",
	              sensor->type==DHT11?"11":"22",
	              data[0], data[1], data[2], data[3], data[4], checksum, pin);
		if (data[4] == checksum) {
			// checksum is valid
			output->temperature = scale_temperature(sensor->type, data);
			output->humidity = scale_humidity(sensor->type, data);
			//DHT_DEBUG("DHT: Temperature =  %d *C, Humidity = %d %%\r\n", (int)(reading.temperature * 100), (int)(reading.humidity * 100));
			DHT_DEBUG("DHT: Temperature*100 =  %d *C, Humidity*100 = %d %% (GPIO%d)\n",
		          (int) (output->temperature * 100), (int) (output->humidity * 100), pin);
		} else {
			//DHT_DEBUG("Checksum was incorrect after %d bits. Expected %d but got %d\r\n", j, data[4], checksum);
			DHT_DEBUG("DHT: Checksum was incorrect after %d bits. Expected %d but got %d (GPIO%d)\r\n",
		                j, data[4], checksum, pin);
		    return false;
		}
	} else {
		//DHT_DEBUG("Got too few bits: %d should be at least 40\r\n", j);
	    DHT_DEBUG("DHT: Got too few bits: %d should be at least 40 (GPIO%d)\r\n", j, pin);
	    return false;
	}
	return true;
}
Exemple #22
0
/******************************************************************************
 * FunctionName : get_key_status
 * Description  : get single key status
 * Parameters   : single_key - single key pointer parameter
 * Returns      : none
*******************************************************************************/
BOOL  
get_key_status(struct single_key_param *single_key)
{
    return GPIO_INPUT_GET(GPIO_ID_PIN(single_key->gpio_id));
}
Exemple #23
0
int ICACHE_FLASH_ATTR set_gpio_mode(unsigned pin, unsigned mode, unsigned pull)
{
	if (pin >= GPIO_PIN_NUM)
		return -1;
	if(pin == 0) {
		if(mode == GPIO_INPUT)
			gpio16_input_conf();
		else
			gpio16_output_conf();
		return 1;
	}

	switch(pull) {
		case GPIO_PULLUP:
			// PIN_PULLDWN_DIS(pin_mux[pin]);
			PIN_PULLUP_EN(pin_mux[pin]);
			break;
		case GPIO_PULLDOWN:
			PIN_PULLUP_DIS(pin_mux[pin]);
			// PIN_PULLDWN_EN(pin_mux[pin]);
			break;
		case GPIO_FLOAT:
			PIN_PULLUP_DIS(pin_mux[pin]);
			// PIN_PULLDWN_DIS(pin_mux[pin]);
			break;
		default:
			PIN_PULLUP_DIS(pin_mux[pin]);
			// PIN_PULLDWN_DIS(pin_mux[pin]);
			break;
	}

	switch(mode) {
		case GPIO_INPUT:
			GPIO_DIS_OUTPUT(pin_num[pin]);
			break;
		case GPIO_OUTPUT:
			ETS_GPIO_INTR_DISABLE();
#ifdef GPIO_INTERRUPT_ENABLE
			pin_int_type[pin] = GPIO_PIN_INTR_DISABLE;
#endif
			PIN_FUNC_SELECT(pin_mux[pin], pin_func[pin]);
			//disable interrupt
			gpio_pin_intr_state_set(GPIO_ID_PIN(pin_num[pin]), GPIO_PIN_INTR_DISABLE);
			//clear interrupt status
			GPIO_REG_WRITE(GPIO_STATUS_W1TC_ADDRESS, BIT(pin_num[pin]));
			GPIO_REG_WRITE(GPIO_PIN_ADDR(GPIO_ID_PIN(pin_num[pin])), GPIO_REG_READ(GPIO_PIN_ADDR(GPIO_ID_PIN(pin_num[pin]))) & (~ GPIO_PIN_PAD_DRIVER_SET(GPIO_PAD_DRIVER_ENABLE))); //disable open drain;
			ETS_GPIO_INTR_ENABLE();
			break;
#ifdef GPIO_INTERRUPT_ENABLE
		case GPIO_INT:
			ETS_GPIO_INTR_DISABLE();
			PIN_FUNC_SELECT(pin_mux[pin], pin_func[pin]);
			GPIO_DIS_OUTPUT(pin_num[pin]);
			gpio_register_set(GPIO_PIN_ADDR(GPIO_ID_PIN(pin_num[pin])), GPIO_PIN_INT_TYPE_SET(GPIO_PIN_INTR_DISABLE)
                        | GPIO_PIN_PAD_DRIVER_SET(GPIO_PAD_DRIVER_DISABLE)
                        | GPIO_PIN_SOURCE_SET(GPIO_AS_PIN_SOURCE));
			ETS_GPIO_INTR_ENABLE();
			break;
#endif
		default:
			break;
	}
	return 1;
}
Exemple #24
0
	void becomesOn(){
		GPIO_OUTPUT_SET(GPIO_ID_PIN(gpio), 1);
	}
Exemple #25
0
LOCAL void ICACHE_FLASH_ATTR
user_link_led_timer_cb(void)
{
    link_led_level = (~link_led_level) & 0x01;
    GPIO_OUTPUT_SET(GPIO_ID_PIN(PLUG_LINK_LED_IO_NUM), link_led_level);
}
Exemple #26
0
	void becomesOff(){
		GPIO_OUTPUT_SET(GPIO_ID_PIN(gpio), 0);
	}
			else 
			{
			  s->buffer.buffer_overflow = 1;
			}

			//wait for stop bit
			os_delay_us(s->bit_time);	

			//done
		}

		//clear interrupt
        GPIO_REG_WRITE(GPIO_STATUS_W1TC_ADDRESS, gpio_status);

// Reactivate interrupts for GPIO0
        gpio_pin_intr_state_set(GPIO_ID_PIN(s->pin_rx.gpio_id), 3);
	} else {
		//clear interrupt, no matter from which pin
		//otherwise, this interrupt will be called again forever
        GPIO_REG_WRITE(GPIO_STATUS_W1TC_ADDRESS, gpio_status);
	}
}



// Read data from buffer
uint8_t Softuart_Read(Softuart *s)
{
  // Empty buffer?
  if (s->buffer.receive_buffer_head == s->buffer.receive_buffer_tail)
    return 0;
static uint8_t irom i2c_get_dc(void)
{
	uint8_t sda_out;
	sda_out = GPIO_INPUT_GET(GPIO_ID_PIN(I2C_MASTER_SDA_GPIO));
	return sda_out;
}
void Softuart_Init(Softuart *s, uint16_t baudrate)
{
	//disable rs485
	s->is_rs485 = 0;

	if(! _Softuart_Instances_Count) {
		os_printf("SOFTUART initialize gpio\r\n");
		//Initilaize gpio subsystem
		gpio_init();
	}

	//set bit time
	s->bit_time = (1000000 / baudrate);
	os_printf("SOFTUART bit_time is %d\r\n",s->bit_time);


	//init tx pin
	if(!s->pin_tx.gpio_mux_name) {
		os_printf("SOFTUART ERROR: Set tx pin (%d)\r\n",s->pin_tx.gpio_mux_name);
	} else {
		//enable pin as gpio
    	PIN_FUNC_SELECT(s->pin_tx.gpio_mux_name, s->pin_tx.gpio_func);

		//set pullup (UART idle is VDD)
		PIN_PULLUP_EN(s->pin_tx.gpio_mux_name);
		
		//set high for tx idle
		GPIO_OUTPUT_SET(GPIO_ID_PIN(s->pin_tx.gpio_id), 1);
		os_delay_us(100000);
		
		os_printf("SOFTUART TX INIT DONE\r\n");
	}

	//init rx pin
	if(!s->pin_rx.gpio_mux_name) {
		os_printf("SOFTUART ERROR: Set rx pin (%d)\r\n",s->pin_rx.gpio_mux_name);
	} else {
		//enable pin as gpio
    	PIN_FUNC_SELECT(s->pin_rx.gpio_mux_name, s->pin_rx.gpio_func);

		//set pullup (UART idle is VDD)
		PIN_PULLUP_EN(s->pin_rx.gpio_mux_name);
		
		//set to input -> disable output
		GPIO_DIS_OUTPUT(GPIO_ID_PIN(s->pin_rx.gpio_id));

		//set interrupt related things

		//disable interrupts by GPIO
		ETS_GPIO_INTR_DISABLE();

		//attach interrupt handler and a pointer that will be passed around each time
		ETS_GPIO_INTR_ATTACH(Softuart_Intr_Handler, s);

		//not sure what this does... (quote from example):
		//    void gpio_register_set(uint32 reg_id, uint32 value);
		//
		// From include file
		//   Set the specified GPIO register to the specified value.
		//   This is a very general and powerful interface that is not
		//   expected to be used during normal operation.  It is intended
		//   mainly for debug, or for unusual requirements.
		//
		// All people repeat this mantra but I don't know what it means
		//
		gpio_register_set(GPIO_PIN_ADDR(s->pin_rx.gpio_id),
							   GPIO_PIN_INT_TYPE_SET(GPIO_PIN_INTR_DISABLE)  |
							   GPIO_PIN_PAD_DRIVER_SET(GPIO_PAD_DRIVER_DISABLE) |
							   GPIO_PIN_SOURCE_SET(GPIO_AS_PIN_SOURCE));
		
		//clear interrupt handler status, basically writing a low to the output
		GPIO_REG_WRITE(GPIO_STATUS_W1TC_ADDRESS, BIT(s->pin_rx.gpio_id));

		//enable interrupt for pin on any edge (rise and fall)
		//@TODO: should work with ANYEDGE (=3), but complie error
		gpio_pin_intr_state_set(GPIO_ID_PIN(s->pin_rx.gpio_id), 3);

		//globally enable GPIO interrupts
		ETS_GPIO_INTR_ENABLE();
	
		os_printf("SOFTUART RX INIT DONE\r\n");
	}

	//add instance to array of instances
	_Softuart_GPIO_Instances[s->pin_rx.gpio_id] = s;
	_Softuart_Instances_Count++;
		
	os_printf("SOFTUART INIT DONE\r\n");
}
Exemple #30
0
//Main routine. Initialize stdout, the I/O and the webserver and we're done.
void user_init(void) {
// my stuff
	dBR_BOILER_SET=65; // default setting 65C boiler temperature on reboot
	dBR_TEMP_ROOM_SET=18; // default setting 18C room temperature on reboot
	dBR_HUMIDITY_SET=60; // default setting 65% humidity target on reboot
	dBR_MODE=2; // default BR MODE is AUTO
	dDEVICE_MODE=1; // This mode defines if device uses remote (MQTT) management or uses local logics - 0 for remote, 1 for local mode. DEFAULT is 0 - remote

// HTTPD
	stdoutInit();
	ioInit();
	httpdInit(builtInUrls, 80);
//MQTT
	uart_init(115200, 115200);
	CFG_Load();
	sleepms(1000);

	MQTT_InitConnection(&mqttClient, sysCfg.mqtt_host, sysCfg.mqtt_port, SEC_NONSSL);
	//MQTT_InitConnection(&mqttClient, "192.168.11.122", 1880, 0);
	MQTT_InitClient(&mqttClient, sysCfg.device_id, sysCfg.mqtt_user, sysCfg.mqtt_pass, sysCfg.mqtt_keepalive, 1);
	//MQTT_InitClient(&mqttClient, "client_id", "user", "pass", 120, 1);

//	MQTT_InitLWT(&mqttClient, "/lwt", "offline", 0, 0);
	MQTT_OnConnected(&mqttClient, mqttConnectedCb);
	MQTT_OnDisconnected(&mqttClient, mqttDisconnectedCb);
	MQTT_OnPublished(&mqttClient, mqttPublishedCb);
	MQTT_OnData(&mqttClient, mqttDataCb);

	INFO("device_ID:%s\r\n",sysCfg.device_id);
	INFO("MQTTHOST:%s\r\n",sysCfg.mqtt_host);
//DS18B20 timers
	os_timer_disarm(&ds18b20_timer);
	os_timer_setfn(&ds18b20_timer, (os_timer_func_t *)ds18b20_cb, (void *)0);
	os_timer_arm(&ds18b20_timer, DELAY, 1);
// DHT22 initialize
	DHTInit(DHT22, DELAY);
	os_timer_disarm(&dht22_timer);
	os_timer_setfn(&dht22_timer, (os_timer_func_t *)dht22_cb, (void *)0);
	os_timer_arm(&dht22_timer, DELAY, 1);
// INPUT PIN initialize
	ETS_GPIO_INTR_DISABLE(); // Disable gpio interrupts
	ETS_GPIO_INTR_ATTACH(read_input_pin, 13); // GPIO13 interrupt handler
	PIN_FUNC_SELECT(PIN_GPIO13_MUX, PIN_GPIO13_FUNC);
	gpio_output_set(0, 0, 0, BIT13); // Set GPIO13 as input
	PIN_PULLUP_EN(PIN_GPIO13_MUX); // Enable pullup
	GPIO_REG_WRITE(GPIO_STATUS_W1TC_ADDRESS, BIT(13)); // Clear GPIO12 status
	gpio_pin_intr_state_set(GPIO_ID_PIN(13), GPIO_PIN_INTR_NEGEDGE); // Interrupt on NEGATIVE GPIO13 edge
	ETS_GPIO_INTR_ENABLE(); // Enable gpio interrupts
//	INFO("Input pin INITIALIZED ! ! !");

// initialize GPIO12
	PIN_FUNC_SELECT(PIN_GPIO12_MUX, PIN_GPIO12_FUNC);
	GPIO_OUTPUT_SET(PIN_GPIO12, 0);
//	INFO("GPIO12 set to OFF\r\n");
// initialize GPIO5
	GPIO_OUTPUT_SET(PIN_GPIO5, 0);
//	INFO("GPIO5 set to OFF\r\n");
// initialize GPIO14
	PIN_FUNC_SELECT(PIN_GPIO14_MUX, PIN_GPIO14_FUNC);
	GPIO_OUTPUT_SET(PIN_GPIO14, 0);
//	INFO("GPIO14 set to OFF\r\n");
	WIFI_Connect(sysCfg.sta_ssid, sysCfg.sta_pwd, wifiConnectCb);

	os_printf("\nReady\n");
}