Tuesday, 28 November 2017

ESP8266 Multiple Timer

ESP8266 Maximum upto 7 OS_Timer

Source code :

#include <Arduino.h>

extern "C" {
#include "user_interface.h"
}

os_timer_t Timer1;
os_timer_t Timer2;
os_timer_t Timer3;
os_timer_t Timer4;
os_timer_t Timer5;
os_timer_t Timer6;
os_timer_t Timer7;

void Timer_1_Callback(void *pArg)
{
  Serial.println("Timer 1 Event");
}
void Timer_2_Callback(void *pArg)
{
  Serial.println("Timer 2 Event");
}
void Timer_3_Callback(void *pArg)
{
  Serial.println("Timer 3 Event");
}
void Timer_4_Callback(void *pArg)
{
  Serial.println("Timer 4 Event");
}
void Timer_5_Callback(void *pArg)
{
  Serial.println("Timer 5 Event");
}
void Timer_6_Callback(void *pArg)
{
  Serial.println("Timer 6 Event");
}
void Timer_7_Callback(void *pArg)
{
  Serial.println("Timer 7 Event");
}

void setup() {
  Serial.begin(115200);
  delay(3000);
  // put your setup code here, to run once:
  //=================== Create OS timer1
  os_timer_setfn(&Timer1, Timer_1_Callback, NULL);
  os_timer_arm(&Timer1, 1000, true);

  //=================== Create OS timer2
  os_timer_setfn(&Timer2, Timer_2_Callback, NULL);
  os_timer_arm(&Timer2, 1000, true);

    //=================== Create OS timer3
  os_timer_setfn(&Timer3, Timer_3_Callback, NULL);
  os_timer_arm(&Timer3, 1000, true);

    //=================== Create OS timer4
  os_timer_setfn(&Timer4, Timer_4_Callback, NULL);
  os_timer_arm(&Timer4, 1000, true);

    //=================== Create OS timer5
  os_timer_setfn(&Timer5, Timer_5_Callback, NULL);
  os_timer_arm(&Timer5, 1000, true);

    //=================== Create OS timer6
  os_timer_setfn(&Timer6, Timer_6_Callback, NULL);
  os_timer_arm(&Timer6, 1000, true);

    //=================== Create OS timer7
  os_timer_setfn(&Timer7, Timer_7_Callback, NULL);
  os_timer_arm(&Timer7, 1000, true);

}

void loop() {
  // put your main code here, to run repeatedly:

}

video Link : https://youtu.be/-k0KrUYsIqw

Tuesday, 25 July 2017

Analog to Digital Conversion using ESP8266

Analog to Digital Conversion


The datasheet describes the ADC pin as having 10 bit resolution. This means 0 to 1024. You should get a value somewhere within this range.
Here the fun begins! Apparently, the module only converts voltage between 0 and 1 volt.
As an example, I have a 10k rheostat hooked up to the ADC pin. Fully moving the slider to the position where I would expect a 0 reading, the ADC TOUT pins reads 13~15, not 0 but encouraging!
However, as I slide the slider to the right, I see the ADC TOUT reaches the maximum reading of 1024 in about 1/3 the distance.
Ideally, I want the slider to register 0 to 1024 increasing or decreasing over 100% of the slider travel.
Reaching the maximum reading in 1/3 of the travel makes sense, the ADC pin only reads up to 1 volt. Any reading over that, say 1.1v to Vcc of 3.3v will be maxed out to 1024.
So, I need to supply the ADC pin a voltage between 0 and 1 volt only.
Using a voltage divider greatly improves the situation.


Voltage Divider 




Source Code 

void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);
}

void loop() {
  // put your main code here, to run repeatedly:
Get_Anolog_Process();
delay(100);
}


int ADC_Sum=0;
int Battery_Value=0;
int ADC_Count=0;
int Round_OFF=0;

void Get_Anolog_Process(void)
{
 
       ADC_Sum+=analogRead(A0);ADC_Count++;
        if(Battery_Value==0){
            Battery_Value=(int)(3000*((ADC_Sum/ADC_Count)/1024.0));
         }
        if(ADC_Count>=10)
        {                
            Battery_Value=(int)(3000*((ADC_Sum/ADC_Count)/1024.0));
            ADC_Count=0;ADC_Sum=0;
             Serial.print("Voltage: ");
           Serial.print(Battery_Value);
           Serial.println(" mV");
        } 

Thursday, 20 July 2017

ESP8266 interface with SPI Flash (W25Q32FV )

Hardware Connection :


In W25Q32FV pin no 3 and Pin No 7 pullup with 4.7K

Complete Source From : https://github.com/Marzogh/SPIFlash

Tuesday, 18 July 2017

PCF8563 interface with nRF51822


File Name : main.c
#include <stdio.h>
#include "boards.h"
#include "app_util_platform.h"
#include "app_uart.h"
#include "app_error.h"
#include "nrf_drv_twi.h"
#include "PCF8563.h"
#include "nrf_delay.h"

/* UART buffer size */
#define UART_TX_BUF_SIZE 256
#define UART_RX_BUF_SIZE 1

#warning "!**** ARE YOU ABSOLUTELY SURE YOU HAVE CHOSEN THE CORRECT SCL AND SDA PINS? ****!"

#define DEVICE_SCL_PIN 5
#define DEVICE_SDA_PIN 6

nrf_drv_twi_t twi_instance = NRF_DRV_TWI_INSTANCE(0);

uint8_t device_address = 0; // Address used to temporarily store the current address being checked
bool device_found = false;


/**
 * @brief UART events handler.
 */
static void uart_events_handler(app_uart_evt_t * p_event)
{
    switch (p_event->evt_type)
    {
        case APP_UART_COMMUNICATION_ERROR:
            APP_ERROR_HANDLER(p_event->data.error_communication);
            break;

        case APP_UART_FIFO_ERROR:
            APP_ERROR_HANDLER(p_event->data.error_code);
            break;

        default:
            break;
    }
}


/**
 * @brief UART initialization.
 */
static void uart_config(void)
{
    uint32_t                     err_code;
    const app_uart_comm_params_t comm_params =
    {
        RX_PIN_NUMBER,
        TX_PIN_NUMBER,
        RTS_PIN_NUMBER,
        CTS_PIN_NUMBER,
        APP_UART_FLOW_CONTROL_DISABLED,
        false,
        UART_BAUDRATE_BAUDRATE_Baud115200
    };

    APP_UART_FIFO_INIT(&comm_params,
                       UART_RX_BUF_SIZE,
                       UART_TX_BUF_SIZE,
                       uart_events_handler,
                       APP_IRQ_PRIORITY_LOW,
                       err_code);

    APP_ERROR_CHECK(err_code);
}

/**
 * @brief TWI events handler.
 */
void twi_handler(nrf_drv_twi_evt_t const * p_event, void * p_context)
{  
    switch(p_event->type)
    {
        case NRF_DRV_TWI_EVT_DONE:
            // If EVT_DONE (event done) is received a device is found and responding on that particular address
            //printf("\r\n!****************************!\r\nDevice found at 7-bit address: %#x!\r\n!****************************!\r\n\r\n", device_address);
            //device_found = true;
                                                   
            break;
        case NRF_DRV_TWI_EVT_ADDRESS_NACK:
            printf("No address ACK on address: %#x!\r\n", device_address);
            break;
        case NRF_DRV_TWI_EVT_DATA_NACK:
            printf("No data ACK on address: %#x!\r\n", device_address);
            break;
        default:
            break;       
    }  
}

/**
 * @brief UART initialization.
 */
void twi_init (void)
{
    ret_code_t err_code;
   
    const nrf_drv_twi_config_t twi_config = {
       .scl                = DEVICE_SCL_PIN,
       .sda                = DEVICE_SDA_PIN,
       .frequency          = NRF_TWI_FREQ_400K,
       .interrupt_priority = APP_IRQ_PRIORITY_HIGH
    };
    err_code = nrf_drv_twi_init(&twi_instance, &twi_config, twi_handler, NULL);
    APP_ERROR_CHECK(err_code);   
    nrf_drv_twi_enable(&twi_instance);
}

/**
 * @brief Function for main application entry.
 */
int main(void)
{
    date_time_t dt;
    nrf_gpio_cfg_output(LED_1);
    nrf_gpio_pin_set(LED_1);
    uart_config();
    printf("PCF8563 RTC Test...........\r\n");
    twi_init();
             Initialize_PCF8563();
                  nrf_delay_ms(1000);    // nrf_delay_ms(1000);
                 dt.month   = 7;    // December
      dt.day     = 18;    // 31
      dt.year    = 17;    // 2006
      dt.hours   = 11;    // 23 hours (11pm in 24-hour time)
      dt.minutes = 49;    // 59 minutes 
      dt.seconds = 45;    // 50 seconds
      dt.weekday = 0;     // 0 = Sunday, 1 = Monday, etc.

      PCF8563_set_datetime(&dt);  

    while(1){
      nrf_delay_ms(1000);
                                       PCF8563_read_datetime(&dt);
                                       printf("Time: %d:%d:%d\r\n", dt.hours,dt.minutes,dt.seconds);
                                       printf("Date: %d:%d:%d\r\n", dt.day,dt.month,dt.year);
                                      
    }
}

/** @} */
File Name : PCF8563.c
#include "app_error.h"
#include "nrf_drv_twi.h"
#include "nrf_delay.h"
#include "string.h"
#include "PCF8563.h" 

nrf_drv_twi_t twi_dist_pcf8563 = NRF_DRV_TWI_INSTANCE(0);

uint8_t _rm_bcd(uint8_t data);
uint8_t _get_bcd(uint8_t data);

//======================================================================================
uint8_t bin2bcd(uint8_t binary_value)
{
  uint8_t temp;
  uint8_t retval;

  temp = binary_value;
  retval = 0;

  while(1)
  {
    // Get the tens digit by doing multiple subtraction
    // of 10 from the binary value.
    if(temp >= 10)
    {
      temp -= 10;
      retval += 0x10;
    }
    else // Get the ones digit by adding the remainder.
    {
      retval += temp;
      break;
    }
  }

  return(retval);
}
//====================================================================================================

// Input range - 00 to 99.
uint8_t bcd2bin(uint8_t bcd_value)
{
  uint8_t temp;

  temp = bcd_value;
  // Shifting upper digit right by 1 is same as multiplying by 8.
  temp >>= 1;
  // Isolate the bits for the upper digit.
  temp &= 0x78;

  // Now return: (Tens * 8) + (Tens * 2) + Ones

  return(temp + (temp >> 2) + (bcd_value & 0x0f));
            

/*
   temp=bcd_value;
   bcd_value=(temp>>4)*10;
   bcd_value=bcd_value+(temp&0x0F);
             return bcd_value;
             */
}
//======================================================================================

void PCF8563_writeReg(uint8_t W_reg, uint8_t value)
{
   ret_code_t ret;
    do
    {
        uint8_t buffer[2]; /* Addr + data */
        buffer[0] = W_reg;
        buffer[1] = value;
        ret = nrf_drv_twi_tx(&twi_dist_pcf8563, I2C_PCF8563_SLAVE_ADDR , buffer, 2, false);
    }while (0);
   nrf_delay_ms(5);
}
//======================================================================================
uint8_t PCF8563_readReg(uint8_t W_reg)
{
  ret_code_t ret;
  uint8_t W_data;
    do
    {
       ret = nrf_drv_twi_tx(&twi_dist_pcf8563, I2C_PCF8563_SLAVE_ADDR, &W_reg, 1, true);
       if (NRF_SUCCESS != ret)
       {
                                                     printf("Error 1\r\n");
          return 0;
       }
                                        nrf_delay_ms(5);
       ret = nrf_drv_twi_rx(&twi_dist_pcf8563, I2C_PCF8563_SLAVE_ADDR, &W_data, 1);
       if (NRF_SUCCESS != ret)
       {
                                                     printf("Error 2\r\n");
          return 0;
       }
    }while (0);
                          nrf_delay_ms(5);
      return W_data;
}
//======================================================================================
void PCF8563_writeMulti(uint8_t W_reg, uint8_t const * src, uint8_t count)
{
      ret_code_t ret;

   do{
      uint8_t buffer[1 + count]; /* index + data */
      buffer[0] = (uint8_t)W_reg;
      memcpy(buffer + 1, src, count);
      ret = nrf_drv_twi_tx(&twi_dist_pcf8563, I2C_PCF8563_SLAVE_ADDR, buffer, count + 1, false);
   } while (0);
              nrf_delay_ms(5);
 }
//======================================================================================
 void PCF8563_readMulti(uint8_t W_reg, uint8_t * dst, uint8_t count)
{
  
       ret_code_t ret; 

    do
    {
       ret = nrf_drv_twi_tx(&twi_dist_pcf8563, I2C_PCF8563_SLAVE_ADDR, &W_reg, 1, true);
       if (NRF_SUCCESS != ret)
       {
                                                      //printf("Return with Error \r\n");
          break;
       }
                                       nrf_delay_ms(5);
       ret = nrf_drv_twi_rx(&twi_dist_pcf8563, I2C_PCF8563_SLAVE_ADDR, dst, count);
                                         if (NRF_SUCCESS != ret)
       {
                                                      printf("Return with Error \r\n");
          break;
       }
    }while (0);
   nrf_delay_ms(5);
}
//======================================================================================
void Initialize_PCF8563(void){
             PCF8563_writeReg(PCF8563_CTRL_STATUS_REG1,PCF8563_START_COUNTING);
             //PCF8563_writeReg(0x0D,0x83);
}
//======================================================================================
void PCF8563_set_datetime(date_time_t *dt) {

  PCF8563_writeReg(PCF8563_SECONDS_REG,bin2bcd(dt->seconds));  
             PCF8563_writeReg(PCF8563_MINUTES_REG,bin2bcd(dt->minutes)); 
             PCF8563_writeReg(PCF8563_HOURS_REG,bin2bcd(dt->hours));
             PCF8563_writeReg(PCF8563_DAY_REG,bin2bcd(dt->day));
             PCF8563_writeReg(PCF8563_WEEK_REG,dt->weekday);
             PCF8563_writeReg(PCF8563_MONTH_REG,bin2bcd(dt->month));
             PCF8563_writeReg(PCF8563_WEEK_REG,bin2bcd(dt->year));
}
//======================================================================================
void PCF8563_read_datetime(date_time_t *dt)
{
             unsigned char LCu_Array[7]={0};
             PCF8563_readMulti(PCF8563_SECONDS_REG,LCu_Array,7);
             dt->seconds = bcd2bin(LCu_Array[0]&0x7F);
             dt->minutes = bcd2bin(LCu_Array[1]&0x7F);     
             dt->hours   = bcd2bin(LCu_Array[2] & 0x3F);
             dt->day     = bcd2bin(LCu_Array[3] & 0x3F);
             dt->month   = bcd2bin(LCu_Array[5] & 0x1F);
             dt->weekday =    LCu_Array[4] & 0x07;
             dt->year    = bcd2bin(LCu_Array[6]); 
}
//======================================================================================

File Name : PCF8563.h
#ifndef PCF8563_H__
#define PCF8563_H__
 
#include "nordic_common.h"
#include "nrf_drv_config.h"
#include "app_error.h"

typedef struct
{
uint8_t seconds;    // 0 to 59
uint8_t minutes;    // 0 to 59
uint8_t hours;      // 0 to 23  (24-hour time)
uint8_t day;        // 1 to 31
uint8_t weekday;    // 0 = Sunday, 1 = Monday, etc.
uint8_t month;      // 1 to 12
uint8_t year;       // 00 to 99
}date_time_t;

             #define I2C_PCF8563_SLAVE_ADDR                       0x51
// registers //
#define PCF8563_CONTROL1   0x00     //control/status 1
#define PCF8563_CONTROL2   0x01     //control/status 2
#define PCF8563_CLKOUT     0x0D     //CLKOUT control
#define PCF8563_TCONTROL   0x0E     //timer control
#define PCF8563_TIMER      0x0F     //timer countdown value

#define PCF8563_SECONDS    0x02     //0..59 BCD (bit7 is VL)
#define PCF8563_MINUTES    0x03     //0..59 BCD
#define PCF8563_HOURS      0x04     //0..23 bcd
#define PCF8563_DAYS       0x05     //1..31 bcd
#define PCF8563_WEEKDAY    0x06     //0..6
#define PCF8563_MONTHS     0x07     //0..12 (bit7 is Century, leave clear for 20xx)
#define PCF8563_YEARS      0x08     //0..99 bcd

#define PCF8563_MINUTE_ALARM  0x09  //0..59 BCD
#define PCF8563_HOUR_ALARM    0x0A  //0..23 BCD
#define PCF8563_DAY_ALARM     0x0B  //0..31 BCD
#define PCF8563_WEEKDAY_ALARM 0x0C  //0..6
            
            
// Register addresses
#define PCF8563_CTRL_STATUS_REG1   0x00
#define PCF8563_CTRL_STATUS_REG2   0x01
#define PCF8563_SECONDS_REG        0x02
#define PCF8563_MINUTES_REG        0x03
#define PCF8563_HOURS_REG          0x04
#define PCF8563_DAY_REG            0x05
#define PCF8563_WEEK_REG           0x06
#define PCF8563_MONTH_REG          0x07
#define PCF8563_YEAR_REG           0x08
#define PCF8563_ALARM_MINS_REG     0x09
#define PCF8563_ALARM_HOURS_REG    0x0A
#define PCF8563_ALARM_DAY_REG      0x0B
#define PCF8563_ALARM_WEEKDAY_REG  0x0C
#define PCF8563_CTRL_CLKOUT_REG    0x0D
#define PCF8563_CTRL_TIMER_REG     0x0E
#define PCF8563_TIMER_REG          0x0F

// Commands for the Control/Status register.
#define PCF8563_START_COUNTING     0x08
#define PCF8563_STOP_COUNTING      0x28


//*************************************  for Set_Alarm()
#define PCF8563_Alarm_off          0x00
#define PCF8563_M_Mode             0x01
#define PCF8563_MH_Mode            0x04
#define PCF8563_MHW_Mode           0x07
#define PCF8563_MHD_Mode           0x0B 

//*************************************  for config_CLKOUT()
#define PCF8563_CLKOUT_off         0x00
#define PCF8563_CLKOUT_32KHz       0x80
#define PCF8563_CLKOUT_1KHz        0x81
#define PCF8563_CLKOUT_32Hz        0x82
#define PCF8563_CLKOUT_1Hz         0x83

//*************************************  for config_PCF8563_Timer()
#define PCF8563_Timer_off          0x00
#define PCF8563_Timer_4KHz         0x80
#define PCF8563_Timer_64Hz         0x81
#define PCF8563_Timer_1Hz          0x82
#define PCF8563_Timer_1_60Hz       0x83

//*************************************  for config_PCF8563_Interrupt()
#define Alarm_Interrupt_Enable     0x01
#define Timer_Interrupt_Enable     0x02
#define A_T_Interrupt_Enable       0x03
#define Timer_INT_Pulse_on         0x10
#define Timer_INT_Pulse_off        0x00

uint8_t bin2bcd(uint8_t binary_value) ;
uint8_t bcd2bin(uint8_t bcd_value) ;
void PCF8563_writeReg(uint8_t W_reg, uint8_t value);
uint8_t PCF8563_readReg(uint8_t W_reg);
void PCF8563_writeMulti(uint8_t W_reg, uint8_t const * src, uint8_t count);
void PCF8563_readMulti(uint8_t W_reg, uint8_t * dst, uint8_t count);
void Initialize_PCF8563(void);
void PCF8563_set_datetime(date_time_t *dt);
void PCF8563_read_datetime(date_time_t *dt) ;


#endif /* PCF8563_H_ */

Wednesday, 5 July 2017

ESP8266 NTP Server Time update

Source Code for NTP server time update:
video: https://youtu.be/Zx7hk7hxabM

/*
 * TimeNTP_ESP8266WiFi.ino
 * Example showing time sync to NTP time source
 *
 * This sketch uses the ESP8266WiFi library
 */

#include "TimeLib.h"
#include <ESP8266WiFi.h>
#include <WiFiUdp.h>

const char ssid[] = "xxxx";       //  your network SSID (name)
const char pass[] = "xxxxxxxxx";   //  your network password

/*

// NTP Servers:
//static const char ntpServerName[] = "us.pool.ntp.org";
//static const char ntpServerName[] = "time.nist.gov";
//static const char ntpServerName[] = "time-a.timefreq.bldrdoc.gov";
//static const char ntpServerName[] = "time-b.timefreq.bldrdoc.gov";
//static const char ntpServerName[] = "time-c.timefreq.bldrdoc.gov";

*/

// NTP Servers:
const char * ntpServerName;
String ntpServerName1 = "us.pool.ntp.org";
String ntpServerName2 = "time.nist.gov";
String ntpServerName3 = "time-a.timefreq.bldrdoc.gov";
String ntpServerName4 = "time-b.timefreq.bldrdoc.gov";
String ntpServerName5 = "time-c.timefreq.bldrdoc.gov";

const int timeZone = 5;     // Indian Time Zone (+5.30)
//const int timeZone = -5;  // Eastern Standard Time (USA)
//const int timeZone = -4;  // Eastern Daylight Time (USA)
//const int timeZone = -8;  // Pacific Standard Time (USA)
//const int timeZone = -7;  // Pacific Daylight Time (USA)

WiFiUDP Udp;
unsigned int localPort = 8888;  // local port to listen for UDP packets

time_t getNtpTime();
void digitalClockDisplay();
void printDigits(int digits);
void sendNTPpacket(IPAddress &address);
int Status=0;

void setup()
{
  Serial.begin(115200);
  while (!Serial) ; // Needed for Leonardo only
  delay(250);
  Serial.println("TimeNTP Example");
  Serial.print("Connecting to ");
  Serial.println(ssid);
  WiFi.begin(ssid, pass);

  while (WiFi.status() != WL_CONNECTED){
    delay(500);
    Serial.print(".");
  }

  for(int Loop=0;Loop<5;Loop++)
  {
    if(Loop==0) ntpServerName = ntpServerName1.c_str();
    if(Loop==1)  ntpServerName = ntpServerName2.c_str();
    if(Loop==2)  ntpServerName = ntpServerName3.c_str();
    if(Loop==3)  ntpServerName = ntpServerName4.c_str();
    if(Loop==4)  ntpServerName = ntpServerName5.c_str();
 
    Serial.print("IP number assigned by DHCP is ");
    Serial.println(WiFi.localIP());
    Serial.println("Starting UDP");
    Udp.begin(localPort);
    Serial.print("Local port: ");
    Serial.println(Udp.localPort());
    Serial.println("waiting for sync");
    setSyncProvider(getNtpTime);
    setSyncInterval(300);

    if(Status==1){
      if(Loop==0) Serial.println("Ressponse from URL 1");
      if(Loop==1) Serial.println("Ressponse from URL 2");
      if(Loop==2) Serial.println("Ressponse from URL 3");
      if(Loop==3) Serial.println("Ressponse from URL 4");
      if(Loop==4) Serial.println("Ressponse from URL 5");
      break;
    }
  }
}

time_t prevDisplay = 0; // when the digital clock was displayed
int ADC_Values=0;
int ADC_Count=0;
int ADC_Sum=0;
int check=0;

void loop()
{
    if(timeStatus()!=timeNotSet)
  {
      if(now()!= prevDisplay){ //update the display only if time has changed
        prevDisplay = now();
        digitalClockDisplay();
       /*
        ADC_Sum+=analogRead(A0);ADC_Count++;
        if(ADC_Values==0)
        {
              ADC_Values=ADC_Values=(int)(4200*((ADC_Sum/ADC_Count)/1024.0));
              check=(ADC_Values/10)%10;
              ADC_Values=ADC_Values/100;
              if(check>=5)ADC_Values++;
              Serial.print("Battery: ");
              Serial.print(ADC_Values/10);
              Serial.print(".");
              Serial.print(ADC_Values%10);
              Serial.println(" V");
         }
        if(ADC_Count>=10)
        {        
              //Serial.print("Adc Values: ");
              //Serial.println(ADC_Values);      
              ADC_Values=(int)(4200*((ADC_Sum/ADC_Count)/1024.0));
              Serial.print("Battery: ");
              Serial.print(ADC_Values);
              Serial.println(" mV");
              check=(ADC_Values/10)%10;
              ADC_Values=ADC_Values/100;
              if(check>=5)ADC_Values++;
              Serial.print("Battery: ");
              Serial.print(ADC_Values/10);
              Serial.print(".");
              Serial.print(ADC_Values%10);
              Serial.println(" V");  ADC_Count=0;ADC_Sum=0;
        }*/
     
      }
   }
}
String validPacket = "Time:";
void digitalClockDisplay()
{
  // digital clock display of the time

  Serial.print("DATE:");
    Serial.print(day());
  Serial.print(".");
  Serial.print(month());
  Serial.print(".");
  Serial.print(year());
  Serial.println();
  Serial.print("TIME:");
  Serial.print(hour());
  printDigits(minute());
  printDigits(second());
  Serial.println(" ");
  Serial.println(" ");

}

void printDigits(int digits)
{
  // utility for digital clock display: prints preceding colon and leading 0
  Serial.print(":");
  if (digits < 10)
    Serial.print('0');
  Serial.print(digits);
}

/*-------- NTP code ----------*/

const int NTP_PACKET_SIZE = 48; // NTP time is in the first 48 bytes of message
byte packetBuffer[NTP_PACKET_SIZE]; //buffer to hold incoming & outgoing packets

time_t getNtpTime()
{
  IPAddress ntpServerIP; // NTP server's ip address

  while (Udp.parsePacket() > 0) ; // discard any previously received packets
  Serial.println("Transmit NTP Request");
  // get a random server from the pool
  WiFi.hostByName(ntpServerName, ntpServerIP);
  Serial.print(ntpServerName);
  Serial.print(": ");
  Serial.println(ntpServerIP);
  sendNTPpacket(ntpServerIP);
  uint32_t beginWait = millis();
  while (millis() - beginWait < 1500) {
    int size = Udp.parsePacket();
    if (size >= NTP_PACKET_SIZE) {
      Serial.println("Receive NTP Response");
      Udp.read(packetBuffer, NTP_PACKET_SIZE);  // read packet into the buffer
      unsigned long secsSince1900;
      // convert four bytes starting at location 40 to a long integer
      secsSince1900 =  (unsigned long)packetBuffer[40] << 24;
      secsSince1900 |= (unsigned long)packetBuffer[41] << 16;
      secsSince1900 |= (unsigned long)packetBuffer[42] << 8;
      secsSince1900 |= (unsigned long)packetBuffer[43];Status=1;
      return (secsSince1900 - 2208988800UL + timeZone * SECS_PER_HOUR)+1800;
    }
  }
  Serial.println("No NTP Response :-(");Status=0;
  return 0; // return 0 if unable to get the time
}

// send an NTP request to the time server at the given address
void sendNTPpacket(IPAddress &address)
{
  // set all bytes in the buffer to 0
  memset(packetBuffer, 0, NTP_PACKET_SIZE);
  // Initialize values needed to form NTP request
  // (see URL above for details on the packets)
  packetBuffer[0] = 0b11100011;   // LI, Version, Mode
  packetBuffer[1] = 0;     // Stratum, or type of clock
  packetBuffer[2] = 6;     // Polling Interval
  packetBuffer[3] = 0xEC;  // Peer Clock Precision
  // 8 bytes of zero for Root Delay & Root Dispersion
  packetBuffer[12] = 49;
  packetBuffer[13] = 0x4E;
  packetBuffer[14] = 49;
  packetBuffer[15] = 52;
  // all NTP fields have been given values, now
  // you can send a packet requesting a timestamp:
  Udp.beginPacket(address, 123); //NTP requests are to port 123
  Udp.write(packetBuffer, NTP_PACKET_SIZE);
  Udp.endPacket();
}


//=======================================================================
/* DateStrings.cpp
 * Definitions for date strings for use with the Time library
 *
 * Updated for Arduino 1.5.7 18 July 2014
 *
 * No memory is consumed in the sketch if your code does not call any of the string methods
 * You can change the text of the strings, make sure the short strings are each exactly 3 characters
 * the long strings can be any length up to the constant dt_MAX_STRING_LEN defined in TimeLib.h
 *
 */

#if defined(__AVR__)
#include <avr/pgmspace.h>
#else
// for compatiblity with Arduino Due and Teensy 3.0 and maybe others?
#define PROGMEM
#define PGM_P  const char *
#define pgm_read_byte(addr) (*(const unsigned char *)(addr))
#define pgm_read_word(addr) (*(const unsigned char **)(addr))
#define strcpy_P(dest, src) strcpy((dest), (src))
#endif
#include <string.h> // for strcpy_P or strcpy
#include "TimeLib.h"

// the short strings for each day or month must be exactly dt_SHORT_STR_LEN
#define dt_SHORT_STR_LEN  3 // the length of short strings

static char buffer[dt_MAX_STRING_LEN+1];  // must be big enough for longest string and the terminating null

const char monthStr0[] PROGMEM = "";
const char monthStr1[] PROGMEM = "January";
const char monthStr2[] PROGMEM = "February";
const char monthStr3[] PROGMEM = "March";
const char monthStr4[] PROGMEM = "April";
const char monthStr5[] PROGMEM = "May";
const char monthStr6[] PROGMEM = "June";
const char monthStr7[] PROGMEM = "July";
const char monthStr8[] PROGMEM = "August";
const char monthStr9[] PROGMEM = "September";
const char monthStr10[] PROGMEM = "October";
const char monthStr11[] PROGMEM = "November";
const char monthStr12[] PROGMEM = "December";

const PROGMEM char * const PROGMEM monthNames_P[] =
{
    monthStr0,monthStr1,monthStr2,monthStr3,monthStr4,monthStr5,monthStr6,
    monthStr7,monthStr8,monthStr9,monthStr10,monthStr11,monthStr12
};

const char monthShortNames_P[] PROGMEM = "ErrJanFebMarAprMayJunJulAugSepOctNovDec";

const char dayStr0[] PROGMEM = "Err";
const char dayStr1[] PROGMEM = "Sunday";
const char dayStr2[] PROGMEM = "Monday";
const char dayStr3[] PROGMEM = "Tuesday";
const char dayStr4[] PROGMEM = "Wednesday";
const char dayStr5[] PROGMEM = "Thursday";
const char dayStr6[] PROGMEM = "Friday";
const char dayStr7[] PROGMEM = "Saturday";

const PROGMEM char * const PROGMEM dayNames_P[] =
{
   dayStr0,dayStr1,dayStr2,dayStr3,dayStr4,dayStr5,dayStr6,dayStr7
};

const char dayShortNames_P[] PROGMEM = "ErrSunMonTueWedThuFriSat";

/* functions to return date strings */

char* monthStr(uint8_t month)
{
    strcpy_P(buffer, (PGM_P)pgm_read_word(&(monthNames_P[month])));
    return buffer;
}

char* monthShortStr(uint8_t month)
{
   for (int i=0; i < dt_SHORT_STR_LEN; i++)    
      buffer[i] = pgm_read_byte(&(monthShortNames_P[i+ (month*dt_SHORT_STR_LEN)]));
   buffer[dt_SHORT_STR_LEN] = 0;
   return buffer;
}

char* dayStr(uint8_t day)
{
   strcpy_P(buffer, (PGM_P)pgm_read_word(&(dayNames_P[day])));
   return buffer;
}

char* dayShortStr(uint8_t day)
{
   uint8_t index = day*dt_SHORT_STR_LEN;
   for (int i=0; i < dt_SHORT_STR_LEN; i++)    
      buffer[i] = pgm_read_byte(&(dayShortNames_P[index + i]));
   buffer[dt_SHORT_STR_LEN] = 0;
   return buffer;
}
//====================================================================
/*
  time.c - low level time and date functions
  Copyright (c) Michael Margolis 2009-2014

  This library is free software; you can redistribute it and/or
  modify it under the terms of the GNU Lesser General Public
  License as published by the Free Software Foundation; either
  version 2.1 of the License, or (at your option) any later version.

  This library is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  Lesser General Public License for more details.

  You should have received a copy of the GNU Lesser General Public
  License along with this library; if not, write to the Free Software
  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA

  1.0  6  Jan 2010 - initial release
  1.1  12 Feb 2010 - fixed leap year calculation error
  1.2  1  Nov 2010 - fixed setTime bug (thanks to Korman for this)
  1.3  24 Mar 2012 - many edits by Paul Stoffregen: fixed timeStatus() to update
                     status, updated examples for Arduino 1.0, fixed ARM
                     compatibility issues, added TimeArduinoDue and TimeTeensy3
                     examples, add error checking and messages to RTC examples,
                     add examples to DS1307RTC library.
  1.4  5  Sep 2014 - compatibility with Arduino 1.5.7
*/

#if ARDUINO >= 100
#include <Arduino.h>
#else
#include <WProgram.h>
#endif

#include "TimeLib.h"

static tmElements_t tm;          // a cache of time elements
static time_t cacheTime;   // the time the cache was updated
static uint32_t syncInterval = 300;  // time sync will be attempted after this many seconds

void refreshCache(time_t t) {
  if (t != cacheTime) {
    breakTime(t, tm);
    cacheTime = t;
  }
}

int hour() { // the hour now
  return hour(now());
}

int hour(time_t t) { // the hour for the given time
  refreshCache(t);
  return tm.Hour;
}

int hourFormat12() { // the hour now in 12 hour format
  return hourFormat12(now());
}

int hourFormat12(time_t t) { // the hour for the given time in 12 hour format
  refreshCache(t);
  if( tm.Hour == 0 )
    return 12; // 12 midnight
  else if( tm.Hour  > 12)
    return tm.Hour - 12 ;
  else
    return tm.Hour ;
}

uint8_t isAM() { // returns true if time now is AM
  return !isPM(now());
}

uint8_t isAM(time_t t) { // returns true if given time is AM
  return !isPM(t);
}

uint8_t isPM() { // returns true if PM
  return isPM(now());
}

uint8_t isPM(time_t t) { // returns true if PM
  return (hour(t) >= 12);
}

int minute() {
  return minute(now());
}

int minute(time_t t) { // the minute for the given time
  refreshCache(t);
  return tm.Minute;
}

int second() {
  return second(now());
}

int second(time_t t) {  // the second for the given time
  refreshCache(t);
  return tm.Second;
}

int day(){
  return(day(now()));
}

int day(time_t t) { // the day for the given time (0-6)
  refreshCache(t);
  return tm.Day;
}

int weekday() {   // Sunday is day 1
  return  weekday(now());
}

int weekday(time_t t) {
  refreshCache(t);
  return tm.Wday;
}
 
int month(){
  return month(now());
}

int month(time_t t) {  // the month for the given time
  refreshCache(t);
  return tm.Month;
}

int year() {  // as in Processing, the full four digit year: (2009, 2010 etc)
  return year(now());
}

int year(time_t t) { // the year for the given time
  refreshCache(t);
  return tmYearToCalendar(tm.Year);
}

/*============================================================================*/
/* functions to convert to and from system time */
/* These are for interfacing with time serivces and are not normally needed in a sketch */

// leap year calulator expects year argument as years offset from 1970
#define LEAP_YEAR(Y)     ( ((1970+Y)>0) && !((1970+Y)%4) && ( ((1970+Y)%100) || !((1970+Y)%400) ) )

static  const uint8_t monthDays[]={31,28,31,30,31,30,31,31,30,31,30,31}; // API starts months from 1, this array starts from 0

void breakTime(time_t timeInput, tmElements_t &tm){
// break the given time_t into time components
// this is a more compact version of the C library localtime function
// note that year is offset from 1970 !!!

  uint8_t year;
  uint8_t month, monthLength;
  uint32_t time;
  unsigned long days;

  time = (uint32_t)timeInput;
  tm.Second = time % 60;
  time /= 60; // now it is minutes
  tm.Minute = time % 60;
  time /= 60; // now it is hours
  tm.Hour = time % 24;
  time /= 24; // now it is days
  tm.Wday = ((time + 4) % 7) + 1;  // Sunday is day 1

  year = 0;
  days = 0;
  while((unsigned)(days += (LEAP_YEAR(year) ? 366 : 365)) <= time) {
    year++;
  }
  tm.Year = year; // year is offset from 1970

  days -= LEAP_YEAR(year) ? 366 : 365;
  time  -= days; // now it is days in this year, starting at 0

  days=0;
  month=0;
  monthLength=0;
  for (month=0; month<12; month++) {
    if (month==1) { // february
      if (LEAP_YEAR(year)) {
        monthLength=29;
      } else {
        monthLength=28;
      }
    } else {
      monthLength = monthDays[month];
    }
 
    if (time >= monthLength) {
      time -= monthLength;
    } else {
        break;
    }
  }
  tm.Month = month + 1;  // jan is month 1
  tm.Day = time + 1;     // day of month
}

time_t makeTime(tmElements_t &tm){
// assemble time elements into time_t
// note year argument is offset from 1970 (see macros in time.h to convert to other formats)
// previous version used full four digit year (or digits since 2000),i.e. 2009 was 2009 or 9

  int i;
  uint32_t seconds;

  // seconds from 1970 till 1 jan 00:00:00 of the given year
  seconds= tm.Year*(SECS_PER_DAY * 365);
  for (i = 0; i < tm.Year; i++) {
    if (LEAP_YEAR(i)) {
      seconds +=  SECS_PER_DAY;   // add extra days for leap years
    }
  }

  // add days for this year, months start from 1
  for (i = 1; i < tm.Month; i++) {
    if ( (i == 2) && LEAP_YEAR(tm.Year)) {
      seconds += SECS_PER_DAY * 29;
    } else {
      seconds += SECS_PER_DAY * monthDays[i-1];  //monthDay array starts from 0
    }
  }
  seconds+= (tm.Day-1) * SECS_PER_DAY;
  seconds+= tm.Hour * SECS_PER_HOUR;
  seconds+= tm.Minute * SECS_PER_MIN;
  seconds+= tm.Second;
  return (time_t)seconds;
}
/*=====================================================*/
/* Low level system time functions  */

static uint32_t sysTime = 0;
static uint32_t prevMillis = 0;
static uint32_t nextSyncTime = 0;
static timeStatus_t Status = timeNotSet;

getExternalTime getTimePtr;  // pointer to external sync function
//setExternalTime setTimePtr; // not used in this version

#ifdef TIME_DRIFT_INFO   // define this to get drift data
time_t sysUnsyncedTime = 0; // the time sysTime unadjusted by sync
#endif


time_t now() {
// calculate number of seconds passed since last call to now()
  while (millis() - prevMillis >= 1000) {
// millis() and prevMillis are both unsigned ints thus the subtraction will always be the absolute value of the difference
    sysTime++;
    prevMillis += 1000;
#ifdef TIME_DRIFT_INFO
    sysUnsyncedTime++; // this can be compared to the synced time to measure long term drift  
#endif
  }
  if (nextSyncTime <= sysTime) {
    if (getTimePtr != 0) {
      time_t t = getTimePtr();
      if (t != 0) {
        setTime(t);
      } else {
        nextSyncTime = sysTime + syncInterval;
        Status = (Status == timeNotSet) ?  timeNotSet : timeNeedsSync;
      }
    }
  }
  return (time_t)sysTime;
}

void setTime(time_t t) {
#ifdef TIME_DRIFT_INFO
 if(sysUnsyncedTime == 0)
   sysUnsyncedTime = t;   // store the time of the first call to set a valid Time
#endif

  sysTime = (uint32_t)t;
  nextSyncTime = (uint32_t)t + syncInterval;
  Status = timeSet;
  prevMillis = millis();  // restart counting from now (thanks to Korman for this fix)
}

void setTime(int hr,int min,int sec,int dy, int mnth, int yr){
 // year can be given as full four digit year or two digts (2010 or 10 for 2010);
 //it is converted to years since 1970
  if( yr > 99)
      yr = yr - 1970;
  else
      yr += 30;
  tm.Year = yr;
  tm.Month = mnth;
  tm.Day = dy;
  tm.Hour = hr;
  tm.Minute = min;
  tm.Second = sec;
  setTime(makeTime(tm));
}

void adjustTime(long adjustment) {
  sysTime += adjustment;
}

// indicates if time has been set and recently synchronized
timeStatus_t timeStatus() {
  now(); // required to actually update the status
  return Status;
}

void setSyncProvider( getExternalTime getTimeFunction){
  getTimePtr = getTimeFunction;
  nextSyncTime = sysTime;
  now(); // this will sync the clock
}

void setSyncInterval(time_t interval){ // set the number of seconds between re-sync
  syncInterval = (uint32_t)interval;
  nextSyncTime = sysTime + syncInterval;
}

//=====================================================================
#include "TimeLib.h"
//====================================================================
/*
  time.h - low level time and date functions
*/

/*
  July 3 2011 - fixed elapsedSecsThisWeek macro (thanks Vincent Valdy for this)
              - fixed  daysToTime_t macro (thanks maniacbug)
*/  

#ifndef _Time_h
#ifdef __cplusplus
#define _Time_h

#include <inttypes.h>
#ifndef __AVR__
#include <sys/types.h> // for __time_t_defined, but avr libc lacks sys/types.h
#endif


#if !defined(__time_t_defined) // avoid conflict with newlib or other posix libc
typedef unsigned long time_t;
#endif


// This ugly hack allows us to define C++ overloaded functions, when included
// from within an extern "C", as newlib's sys/stat.h does.  Actually it is
// intended to include "time.h" from the C library (on ARM, but AVR does not
// have that file at all).  On Mac and Windows, the compiler will find this
// "Time.h" instead of the C library "time.h", so we may cause other weird
// and unpredictable effects by conflicting with the C library header "time.h",
// but at least this hack lets us define C++ functions as intended.  Hopefully
// nothing too terrible will result from overriding the C library header?!
extern "C++" {
typedef enum {timeNotSet, timeNeedsSync, timeSet
}  timeStatus_t ;

typedef enum {
    dowInvalid, dowSunday, dowMonday, dowTuesday, dowWednesday, dowThursday, dowFriday, dowSaturday
} timeDayOfWeek_t;

typedef enum {
    tmSecond, tmMinute, tmHour, tmWday, tmDay,tmMonth, tmYear, tmNbrFields
} tmByteFields;

typedef struct  {
  uint8_t Second;
  uint8_t Minute;
  uint8_t Hour;
  uint8_t Wday;   // day of week, sunday is day 1
  uint8_t Day;
  uint8_t Month;
  uint8_t Year;   // offset from 1970;
} tmElements_t, TimeElements, *tmElementsPtr_t;

//convenience macros to convert to and from tm years
#define  tmYearToCalendar(Y) ((Y) + 1970)  // full four digit year
#define  CalendarYrToTm(Y)   ((Y) - 1970)
#define  tmYearToY2k(Y)      ((Y) - 30)    // offset is from 2000
#define  y2kYearToTm(Y)      ((Y) + 30)

typedef time_t(*getExternalTime)();
//typedef void  (*setExternalTime)(const time_t); // not used in this version


/*==============================================================================*/
/* Useful Constants */
#define SECS_PER_MIN  ((time_t)(60UL))
#define SECS_PER_HOUR ((time_t)(3600UL))
#define SECS_PER_DAY  ((time_t)(SECS_PER_HOUR * 24UL))
#define DAYS_PER_WEEK ((time_t)(7UL))
#define SECS_PER_WEEK ((time_t)(SECS_PER_DAY * DAYS_PER_WEEK))
#define SECS_PER_YEAR ((time_t)(SECS_PER_WEEK * 52UL))
#define SECS_YR_2000  ((time_t)(946684800UL)) // the time at the start of y2k

/* Useful Macros for getting elapsed time */
#define numberOfSeconds(_time_) (_time_ % SECS_PER_MIN)
#define numberOfMinutes(_time_) ((_time_ / SECS_PER_MIN) % SECS_PER_MIN)
#define numberOfHours(_time_) (( _time_% SECS_PER_DAY) / SECS_PER_HOUR)
#define dayOfWeek(_time_)  ((( _time_ / SECS_PER_DAY + 4)  % DAYS_PER_WEEK)+1) // 1 = Sunday
#define elapsedDays(_time_) ( _time_ / SECS_PER_DAY)  // this is number of days since Jan 1 1970
#define elapsedSecsToday(_time_)  (_time_ % SECS_PER_DAY)   // the number of seconds since last midnight
// The following macros are used in calculating alarms and assume the clock is set to a date later than Jan 1 1971
// Always set the correct time before settting alarms
#define previousMidnight(_time_) (( _time_ / SECS_PER_DAY) * SECS_PER_DAY)  // time at the start of the given day
#define nextMidnight(_time_) ( previousMidnight(_time_)  + SECS_PER_DAY )   // time at the end of the given day
#define elapsedSecsThisWeek(_time_)  (elapsedSecsToday(_time_) +  ((dayOfWeek(_time_)-1) * SECS_PER_DAY) )   // note that week starts on day 1
#define previousSunday(_time_)  (_time_ - elapsedSecsThisWeek(_time_))      // time at the start of the week for the given time
#define nextSunday(_time_) ( previousSunday(_time_)+SECS_PER_WEEK)          // time at the end of the week for the given time


/* Useful Macros for converting elapsed time to a time_t */
#define minutesToTime_t ((M)) ( (M) * SECS_PER_MIN)
#define hoursToTime_t   ((H)) ( (H) * SECS_PER_HOUR)
#define daysToTime_t    ((D)) ( (D) * SECS_PER_DAY) // fixed on Jul 22 2011
#define weeksToTime_t   ((W)) ( (W) * SECS_PER_WEEK)

/*============================================================================*/
/*  time and date functions   */
int     hour();            // the hour now
int     hour(time_t t);    // the hour for the given time
int     hourFormat12();    // the hour now in 12 hour format
int     hourFormat12(time_t t); // the hour for the given time in 12 hour format
uint8_t isAM();            // returns true if time now is AM
uint8_t isAM(time_t t);    // returns true the given time is AM
uint8_t isPM();            // returns true if time now is PM
uint8_t isPM(time_t t);    // returns true the given time is PM
int     minute();          // the minute now
int     minute(time_t t);  // the minute for the given time
int     second();          // the second now
int     second(time_t t);  // the second for the given time
int     day();             // the day now
int     day(time_t t);     // the day for the given time
int     weekday();         // the weekday now (Sunday is day 1)
int     weekday(time_t t); // the weekday for the given time
int     month();           // the month now  (Jan is month 1)
int     month(time_t t);   // the month for the given time
int     year();            // the full four digit year: (2009, 2010 etc)
int     year(time_t t);    // the year for the given time

time_t now();              // return the current time as seconds since Jan 1 1970
void    setTime(time_t t);
void    setTime(int hr,int min,int sec,int day, int month, int yr);
void    adjustTime(long adjustment);

/* date strings */
#define dt_MAX_STRING_LEN 9 // length of longest date string (excluding terminating null)
char* monthStr(uint8_t month);
char* dayStr(uint8_t day);
char* monthShortStr(uint8_t month);
char* dayShortStr(uint8_t day);

/* time sync functions */
timeStatus_t timeStatus(); // indicates if time has been set and recently synchronized
void    setSyncProvider( getExternalTime getTimeFunction); // identify the external time provider
void    setSyncInterval(time_t interval); // set the number of seconds between re-sync

/* low level functions to convert to and from system time                     */
void breakTime(time_t time, tmElements_t &tm);  // break time_t into elements
time_t makeTime(tmElements_t &tm);  // convert time elements into time_t

} // extern "C++"
#endif // __cplusplus
#endif /* _Time_h */

Friday, 26 May 2017

8051timer0Mode_1(16Bit mode)

Circuit Diagram : 




Source code :

#include <reg52.h>
#include <stdio.h>

sbit LED = P1^0;            // Defining LED pin
static unsigned long overflow_count = 0;
bit flag=0;
void timer0_ISR (void) interrupt 1
{
  overflow_count++;   /* Increment the overflow count */

if(overflow_count>=10){    // for 500ms seconds loop
if(flag==1){LED=1;flag=0;}
else if(flag==0){LED=0;flag=1;}
overflow_count=0;
}
TF0=0;    // clear timer interrupt
}


void main (void)
{

TMOD=0x01;
TL0=0xFD;
TH0=0x4B;                     // load Calculated value for 50ms delay
ET0 = 1;                      /* Enable Timer 0 Interrupts */
TR0 = 1;                      /* Start Timer 0 Running */
EA = 1;                       /* Global Interrupt Enable */

while (1)
  {
  }
}


Simulation Link : https://youtu.be/70hKILTVs1M


Thursday, 25 May 2017

8051 LED Blink With Simulation

Circuit Diagram :





Code: 

#include<reg52.h>           // special function register declarations
                            // for the intended 8051 derivative

sbit LED = P1^0;            // Defining LED pin

void Delay(void);           // Function prototype declaration

void main (void)
{
    while(1)                // infinite loop
    {
        LED = 0;            // LED ON
        Delay();
        LED = 1;            // LED OFF
        Delay();
    }
}

void Delay(void)
{
    int j;
    int i;
    for(i=0;i<10;i++)
    {
        for(j=0;j<10000;j++)
        {
        }
    }

}


Video : https://youtu.be/gbn-Owuf7dk

ESP8266 Multiple Timer

ESP8266 Maximum upto 7 OS_Timer Source code : #include <Arduino.h> extern "C" { #include "user_interface.h...