Arduino Programming | Sample Programs

Home Arduino Programming | Course Home Arduino Programming | Sample Programs

Arduino Programming – Sample Programs

Sample programs is the first step you take to transition from theory to practical. These sample programs typically demonstrated in a classroom will ensure you are able to immediately see it running in front of your eyes. Added to that our mentors will provide you some exercises where you will be modifying the code in the class itself. By doing this fill-in-the-blank approach, will take out your fear of coding.

Programs

Brief:

A simple program to control (Toggle) the Builtin LED connected at GPIO2.
 

Source Code:

 /*------------------------------------------------------------------------------------------------- 
 *   Author         : Emertxe (https://emertxe.com) 
 *   Date           : Wed 23 Jun 2021 10:00:00 IST
 *   Sketch         : Blinky.ino
 *   Title          : Blinky
 *   Description    : A simple program to control (Toggle) the Builtin LED connected at GPIO2
 *-----------------------------------------------------------------------------------------------*/

#define LED_BUILTIN         2

void setup() {
  pinMode(LED_BUILTIN, OUTPUT);
}

void loop() {
  digitalWrite(LED_BUILTIN, LOW);
  delay(1000);
  digitalWrite(LED_BUILTIN, HIGH);
  delay(1000);
}

 

 Example output:

 

Brief:

A simple sketch to detect the change in signal level on port pin.
 
 
Source Code:
 /*-------------------------------------------------------------------------------------------------          		    
 *   Author         : Emertxe (https://emertxe.com) 
 *   Date           : Wed 23 Jun 2021 10:00:00 IST
 *   Sketch         : LevelTrigger.ino
 *   Title          : Level Detection 
 *   Description    : A simple sketch to detect the change in signal level on port pin
 *-----------------------------------------------------------------------------------------------*/

#define GPIO0               0
#define GPIO2               2

#define SWITCH_BUILTIN      GPIO0
#define LED_BUILTIN         GPIO2

void setup() { 
  pinMode(LED_BUILTIN, OUTPUT);
  pinMode(SWITCH_BUILTIN, INPUT_PULLUP);
}

void loop() {
  static bool key;
  key = digitalRead(SWITCH_BUILTIN);
  digitalWrite(LED_BUILTIN, key); 
}

 

Arduino Programming Example output:

 

Brief:

A simple sketch to detect the signal stage change.
 
Source Code:
/*------------------------------------------------------------------------------------------------- 			    
 *   Author         : Emertxe (https://emertxe.com) 
 *   Date           : Wed 23 Jun 2021 10:00:00 IST
 *   Sketch         : StateChange.ino
 *   Title          : State Change Detection
 *   Description    : A simple sketch to detect the signal stage change
 *-----------------------------------------------------------------------------------------------*/

#define GPIO0               0
#define GPIO2               2

#define SWITCH_BUILTIN      GPIO0
#define LED_BUILTIN         GPIO2

#define OFF                 1

void setup() {
  digitalWrite(LED_BUILTIN, OFF);
  pinMode(LED_BUILTIN, OUTPUT);
  pinMode(SWITCH_BUILTIN, INPUT);
}

bool read_key(void)
{
  static bool key;
  static bool once;
  key = digitalRead(SWITCH_BUILTIN);
  if (key && once)
  {
    once = 0;
    return 1;
  }
  else if (key == 0)
  {
    once = 1;
  }
  return 0;
}

void loop() {
  static bool state = OFF;
  if (read_key())
  {
    state = !state;
    digitalWrite(LED_BUILTIN, state);
  }
}

 

 Example output:

 

Brief:

A sketch to setup the timer to generate an event every second.
 
Source Code:
 /*------------------------------------------------------------------------------------------------- 			    
 *   Author         : Emertxe (https://emertxe.com) 
 *   Date           : Wed 23 Jun 2021 10:00:00 IST
 *   Sketch         : EventTrigger.ino
 *   Title          : Event Trigger using Timer
 *   Description    : A sketch to setup the timer to generate an event every second
 *-----------------------------------------------------------------------------------------------*/

#define EDGE            true
#define UP_TICK         true
#define AUTO_RELOAD     true

volatile bool alr_triggered;
 
hw_timer_t *timer = NULL;
 
void IRAM_ATTR tmr_isr() {
  alr_triggered = 1;
}
 
void setup() {
 
  Serial.begin(115200);
 
  timer = timerBegin(0, 80, UP_TICK);
  timerAttachInterrupt(timer, &tmr_isr, EDGE);
  timerAlarmWrite(timer, 1000000, AUTO_RELOAD);
  timerAlarmEnable(timer);
}
 
void loop() {
  static int count;

  if (alr_triggered) {
    Serial.print("An interrupt as occurred. Total number: ");
    Serial.println(++count);

    alr_triggered = 0;
  }
}

 

Arduino Programming Example output:

 

Brief:

A simple sketch to configure a GPIO pin in Interrupt mode to detect falling edge.
 
Source Code:
 /*------------------------------------------------------------------------------------------------- 			    
 *   Author         : Emertxe (https://emertxe.com) 
 *   Date           : Wed 23 Jun 2021 10:00:00 IST
 *   Sketch         : ExternalInterrupt.ino
 *   Title          : External Interrupt
 *   Description    : A simple sketch to configure a GPIO pin in Interrupt mode to detect falling 
 *                    edge
 *-----------------------------------------------------------------------------------------------*/

#define GPIO0         0

const byte int_pin = GPIO0;

volatile bool int_triggered;
volatile int count;
 
void IRAM_ATTR int_isr() {
  int_triggered = 1;
  count++;
}

void setup() {
  Serial.begin(115200);
 
  Serial.println("Press Boot Pin to Trigger Interrupt");
  pinMode(int_pin, INPUT_PULLUP);

  attachInterrupt(digitalPinToInterrupt(int_pin), int_isr, FALLING);
}

void loop() {
  if (int_triggered) {
    Serial.print("Total event triggered: ");
    Serial.println(count);

    int_triggered = 0;
  }
}

 

Example output:

 

Brief:

A simple sketch to read the analog input and trigger an event once the set threshold is reached.
 
 
Source Code:
 /*-------------------------------------------------------------------------------------------------  
 *   Author         : Emertxe (https://emertxe.com) 
 *   Date           : Wed 23 Jun 2021 10:00:00 IST
 *   Sketch         : AnalogInput.ino
 *   Title          : Analog Signal Detection
 *   Description    : A simple sketch to read the analog input and trigger an event once the set 
 *                    threshold is reached
 *-----------------------------------------------------------------------------------------------*/

#define CHANNEL0        A0

#define LED_BUILTIN     2

void setup() {
  pinMode(LED_BUILTIN, OUTPUT);
}

void glow_led(unsigned short adc_reg_val)
{
  if (adc_reg_val > 2048)
  {
    digitalWrite(LED_BUILTIN, 1);
  }
  else
  {
    digitalWrite(LED_BUILTIN, 0);
  }
}

void loop() {
  static int adc_val;
  
  adc_val = analogRead(CHANNEL0);

  glow_led(adc_val);
}

 

Schematic

 
Arduino Programming Example output:

 

Arduino Programming Example output:

 

Brief:

A simple sketch to generate a PWM signal to control the LED brightness using LED PWM control module supported by ESP32 module.
 
 
Source Code:
 /*------------------------------------------------------------------------------------------------- 			    
 *   Author         : Emertxe (https://emertxe.com) 
 *   Date           : Wed 23 Jun 2021 10:00:00 IST
 *   Sketch         : LEDC.ino
 *   Title          : Pulse Width Modulation (LED PWM)
 *   Description    : A simple sketch to generate a PWM signal to control the LED brightness using
 *                    LED PWM control module supported by ESP32 module
 *-----------------------------------------------------------------------------------------------*/

#define LED_CHANNEL         0
#define FREQ                25000
#define RESOLUTION          12

#define LED_BUILTIN         2

#define CHANNEL0            A0
#define NO_OF_SAMPLE        100

void setup_led_pwm(void)
{
  /* The below function set even the pin direction */
  ledcSetup(LED_CHANNEL, FREQ, RESOLUTION);
  ledcAttachPin(LED_BUILTIN, LED_CHANNEL);
}

void setup()
{
  setup_led_pwm();
}

int read_knob(void)
{
  float adc_val = 0;
  int samples;

  samples = 0;
  while (samples < NO_OF_SAMPLE)
  {
    adc_val = adc_val + analogRead(CHANNEL0);
    samples++;
  }

  adc_val = adc_val / samples;

  return (int) adc_val;
}

void loop()
{
  int duty_cycle;

  duty_cycle = read_knob();

  ledcWrite(LED_CHANNEL, duty_cycle);
}

 

Schematic

 
Embedded Systems Course | Emertxe | Bengaluru

 

Example output:

Brief:

A simple sketch to drive a CLCD module in 4 bit mode.
 
 

Source Code:

clcd.cpp

/*------------------------------------------------------------------------------------------------- 			   
 *   Author         : Emertxe (https://emertxe.com) 
 *   Date           : Wed 23 Jun 2021 10:00:00 IST
 *   code           : clcd.cpp
 *   Title          : CLCD driver
 *   Description    : CLCD driver code with works in 4 bit mode
 *-----------------------------------------------------------------------------------------------*/

#include 
#include "clcd.h"
#include "Arduino.h"

CLCD::CLCD(uint8_t d4, uint8_t d5, uint8_t d6, uint8_t d7, uint8_t rs, uint8_t en)
{
  clcd_rs_pin = rs;
  clcd_en_pin = en;

  clcd_data_pin[0] = d4;
  clcd_data_pin[1] = d5;
  clcd_data_pin[2] = d6;
  clcd_data_pin[3] = d7;
}

void CLCD::write(uint8_t data, bool rs_bit_val, uint16_t exec_time_us)
{
  digitalWrite(clcd_rs_pin, rs_bit_val);

  digitalWrite(clcd_data_pin[0], (data >> 4) & 0x01);
  digitalWrite(clcd_data_pin[1], (data >> 5) & 0x01);
  digitalWrite(clcd_data_pin[2], (data >> 6) & 0x01);
  digitalWrite(clcd_data_pin[3], (data >> 7) & 0x01);

  digitalWrite(clcd_en_pin, HI);
  delayMicroseconds(1); // Requires the delay of 200 nsecs
  digitalWrite(clcd_en_pin, LO);

  digitalWrite(clcd_data_pin[0], (data >> 0) & 0x01);
  digitalWrite(clcd_data_pin[1], (data >> 1) & 0x01);
  digitalWrite(clcd_data_pin[2], (data >> 2) & 0x01);
  digitalWrite(clcd_data_pin[3], (data >> 3) & 0x01);

  digitalWrite(clcd_en_pin, HI);
  delayMicroseconds(1); // Requires the delay of 200 nsecs
  digitalWrite(clcd_en_pin, LO);

  delayMicroseconds(exec_time_us);
}

void CLCD::command(uint8_t data, uint16_t exec_time_us)
{
  write(data, 0, exec_time_us);
}

void CLCD::begin(void)
{
  digitalWrite(clcd_en_pin, LO);

  pinMode(clcd_rs_pin, OUTPUT);
  pinMode(clcd_en_pin, OUTPUT);
  pinMode(clcd_data_pin[0], OUTPUT);
  pinMode(clcd_data_pin[1], OUTPUT);
  pinMode(clcd_data_pin[2], OUTPUT);
  pinMode(clcd_data_pin[3], OUTPUT);

  /*
     Refer page 45/46 of HD44780U ADE-207-272(Z)
     "If the power supply conditions for correctly operating the internal reset 
     circuit are not met, initialization by instructions becomes necessary"
     As per the flow chart, we need at least 40ms after power rises above 2.7V
     So waiting forapprox 50 msecs
  */
  delayMicroseconds(50000);

  write(0x03, 0, 4500); // We start in 8 bit mode, try to set 4 bit mode
  write(0x03, 0, 4500);
  write(0x03, 0, 150);

  write(TWO_LINE_5x7_MATRIX_4_BIT, 0, 37);
  write(CURSOR_HOME, 0, 1640);
  write(DISP_ON_AND_CURSOR_OFF, 0, 37);
  write(CLEAR_DISP_SCREEN, 0, 1640);
}
  
void CLCD::print(const char *s, uint8_t addr)
{
  write(addr, 0, 37);

  while (*s != '\0')
  {
    write(*s++, 1, 37);
  }
}

void CLCD::putch(int8_t data , uint8_t addr)
{
  write(addr, 0, 37);
  write(data, 1, 37);
}


clcd.ino

   /*------------------------------------------------------------------------------------------------- 			    
 *   Author         : Emertxe (https://emertxe.com) 
 *   Date           : Wed 23 Jun 2021 10:00:00 IST
 *   Sketch         : CLCD.ino
 *   Title          : CLCD Demo
 *   Description    : A simple sketch to drive a CLCD module in 4 bit mode
 *-----------------------------------------------------------------------------------------------*/

#include "clcd.h"

CLCD clcd(D4, D5, D6, D7, RS, EN);

void setup()
{
  clcd.begin();

  clcd.print("Hello  World", LINE1(2));
  clcd.print("CLCD  with ESP32", LINE2(0));
}

void loop() {
    /* Nothing here yet */
}

 

Schematic

 
Arduino Programming Example output:

 

Arduino Programming Example output:

 

Brief:

A simple sketch to demonstrate the serial functions.
 
 

Source Code:

/*------------------------------------------------------------------------------------------------- 			    
 *   Author         : Emertxe (https://emertxe.com)
 *   Date           : Wed 23 Jun 2021 10:00:00 IST
 *   Sketch         : UART.ino
 *   Title          : UART Demo
 *   Description    : A simple sketch to demonstrate the serial functions
 *-----------------------------------------------------------------------------------------------*/

int get_c(void)
{
  bool user_acked = 0;

  while (!user_acked)
  {
    if (Serial.available())
    {
      user_acked = 1;

      return Serial.read();
    }
  }

  return 0;
}

void setup() {
  Serial.begin(115200);
}

void loop() {
  char ch;

  ch = get_c();

  Serial.print(ch);
}

 

 Example output:

 

Brief:

A simple sketch to demostrate SPI protocol by communication with external EEPROM.
 

Source Code:

25lc040.cpp

 /*------------------------------------------------------------------------------------------------- 			   
 *   Author         : Emertxe (https://emertxe.com) 
 *   Date           : Wed 23 Jun 2021 10:00:00 IST
 *   code           : 25lc040.cpp
 *   Title          : 25lc040 driver
 *   Description    : SPI driver code to communicate with EEPROM 25lc040
 *-----------------------------------------------------------------------------------------------*/

#include 
#include 
#include "25lc040.h"

#define SPI_CLK_FREQ 1000000 // 1 MHz

SPIClass *vspi = NULL;

void init_spi(void)
{
  /*
   Created 30/04/2018 by Alistair Symonds
   Adapted for SPI EEPROM 25LC040 by Adil S K
  */
  // Initialise two instances of the SPIClass attached to VSPI and HSPI respectively
  vspi = new SPIClass(VSPI);

  // SCLK = 18, MISO = 19, MOSI = 23, SS = 5
  vspi->begin();

  // Use it as you would the regular arduino SPI API
  vspi->beginTransaction(SPISettings(SPI_CLK_FREQ, MSBFIRST, SPI_MODE0));

  // Set up slave select pins as outputs as the Arduino API
  // Doesn't handle automatically pulling SS low
  pinMode(CS_PIN, OUTPUT); //VSPI Chip Select
  
  chip_select(HIGH); //pull SS high to start with
}

void spi_eeprom_write_byte(unsigned char address, unsigned char data) 
{
  /* Refer Datasheet for the write sequence */
  chip_select(LOW);
  spi_transfer(WREN);
  chip_select(HIGH);
  
  delay(1);
  
  chip_select(LOW);
  spi_transfer(WRITE);
  spi_transfer(address);
  spi_transfer(data);
  chip_select(HIGH);

  delay(5); // Refer datasheet

  chip_select(LOW);
  spi_transfer(WRDI);
  chip_select(HIGH);
  
  delay(1);
}

unsigned char spi_eeprom_read_byte(unsigned char address) 
{
  unsigned char data;

  /* Refer Datasheet for the read sequence */
  chip_select(LOW);
  spi_transfer(READ);
  spi_transfer(address);
  data = spi_transfer(DUMMY);
  chip_select(HIGH);
  
  return data;
}


25lc040.h

#ifndef _25LC040_H_													  
#define _25LC040_H_

#define WREN            6
#define WRDI            4
#define RDSR            5
#define WRSR            1
#define READ            3
#define WRITE           2

#define CS_PIN          5

#define DUMMY           0xFF

#define spi_transfer(x) vspi->transfer(x)
#define chip_select(x)  digitalWrite(CS_PIN, x);

void init_spi(void);
void spi_eeprom_write_byte(unsigned char address, unsigned char data);
unsigned char spi_eeprom_read_byte(unsigned char address);

#endif


SPI_EEPROM.ino

 /*------------------------------------------------------------------------------------------------- 			    
 *   Author         : Emertxe (https://emertxe.com) 
 *   Date           : Wed 23 Jun 2021 10:00:00 IST
 *   Sketch         : SPI-EEPROM.ino
 *   Title          : SPI Demo
 *   Description    : A simple sketch to demostrate SPI protocol by communication with external
 *                    EEPROM
 *-----------------------------------------------------------------------------------------------*/

#include 
#include "25lc040.h"

#define GPIO0               0
#define SWITCH_BUILTIN      GPIO0

bool read_key(void)
{
  static bool key;
  static bool once;

  key = digitalRead(SWITCH_BUILTIN);

  if (key && once)
  {
    once = 0;
    
    return 1;
  }
  else if (key == 0)
  {
    once = 1;
  }
  
  return 0;
}

void spi_eeprom_test() 
{
  char data;
  static char prev_data;
  static char loc = 0;
  int key;

  key = read_key();
  
  if (key)
  {
    if (loc < 3)
    {
      loc++;
    }
    else
    {
      loc = 0;
    }
  }

  data = spi_eeprom_read_byte(loc);

  if (data != prev_data)
  {
    Serial.println(data);
    prev_data = data;
  }
}

void setup() 
{
  Serial.begin(115200);
  Serial.println("SPI EEPROM Test");
  
  init_spi();

  spi_eeprom_write_byte(0, 'A');
  spi_eeprom_write_byte(1, 'B');
  spi_eeprom_write_byte(2, 'C');
  spi_eeprom_write_byte(3, 'D');
}

void loop() 
{
  spi_eeprom_test();
}

 

Schematic

Embedded Systems Course | Emertxe | Bengaluru

Arduino Programming Example output:

 

Brief:

An application to intract with DS1307 RTC using I2C protocol.
 

Source Code:

ds1370.cpp

 /*------------------------------------------------------------------------------------------------- 			   
 *   Author         : Emertxe (https://emertxe.com) 
 *   Date           : Wed 24 Mar 2021 16:0main.c0:04 IST
 *   File           : ds1307.cpp
 *   Title          : DS1307 RTC Driver
 *   Description    : Drive to read and write DS1307
 *-----------------------------------------------------------------------------------------------*/

#include "Arduino.h"
#include "Wire.h"
#include "ds1307.h"

void write_ds1307(unsigned char addr, unsigned char data)
{
  Wire.beginTransmission(SLAVE_ID);
  Wire.write(addr);
  Wire.write(data);
  Wire.endTransmission();
}

unsigned char read_ds1307(unsigned char addr)
{
  unsigned char data;

  Wire.beginTransmission(SLAVE_ID);
  Wire.write(addr);
  Wire.endTransmission();
  Wire.requestFrom(SLAVE_ID, 1);

  data = Wire.read();

  return data;
}

void init_ds1307(void)
{
  unsigned char dummy;

  Wire.begin(21, 22, 100000);

  /* Setting the CH bit of the RTC to Stop the Clock */

  dummy = read_ds1307(SEC_ADDR);
  write_ds1307(SEC_ADDR, dummy | 0x80);

  /*
     Control Register of ds1338
     Bit 7 - OUT
     Bit 6 - 0
     Bit 5 - OSF
     Bit 4 - SQWE
     Bit 3 - 0
     Bit 2 - 0
     Bit 1 - RS1
     Bit 0 - RS0

     Seting RS0 and RS1 as 11 to achive SQW out at 32.768 KHz
  */
  write_ds1307(CNTL_ADDR, 0x93);

  /* Clearing the CH bit of the RTC to Start the Clock */
  dummy = read_ds1307(SEC_ADDR);
  write_ds1307(SEC_ADDR, dummy & 0x7F);
}


ds1307.h

#ifndef DS1338_H												          
#define DS1338_H

#define SLAVE_ID        0x68

#define SEC_ADDR        0x00
#define MIN_ADDR        0x01
#define HOUR_ADDR       0x02
#define DAY_ADDR        0x03
#define DATE_ADDR       0x04
#define MONTH_ADDR      0x05
#define YEAR_ADDR       0x06
#define CNTL_ADDR       0x07

#define SEC_FIELD       buffer[0]
#define MIN_FIELD       buffer[1]
#define HRS_FIELD       buffer[2]
#define DAY_OF_WEEK     buffer[3] - 1
#define DAY_FIELD       buffer[4]
#define MONTH_FIELD     buffer[5]
#define YEAR_FIELD      buffer[6]

#define _12_HRS_        0x40
#define _12_            0x1F
#define _24_            0x3F
#define AM_PM           0x20

void set_rtc(char *buffer);
void get_rtc(char *buffer);
void write_ds1307(unsigned char addr, unsigned char data);
unsigned char read_ds1307(unsigned char addr);
void init_ds1307(void);

#endif


DS1307.ino

 /*------------------------------------------------------------------------------------------------- 			    
 *   Author         : Emertxe (https://emertxe.com) 
 *   Date           : Wed 24 Mar 2021 16:0main.c0:04 IST
 *   Sketch         : DS1307.ino
 *   Title          : DS1307 RTC
 *   Description    : An application to intract with DS1307 RTC using I2C protocol
 *-----------------------------------------------------------------------------------------------*/

#include 
#include "ds1307.h"

unsigned char clock_reg[3];
unsigned char time[9];

void display_time(void)
{
  Serial.println((char *)time);

  if (clock_reg[0] & 0x40)
  {
    if (clock_reg[0] & 0x20)
    {
      Serial.print("PM");
    }
    else
    {
      Serial.print("AM");
    }
  }
}

static void get_time(void)
{
  clock_reg[0] = read_ds1307(HOUR_ADDR);
  clock_reg[1] = read_ds1307(MIN_ADDR);
  clock_reg[2] = read_ds1307(SEC_ADDR);

  if (clock_reg[0] & 0x40)
  {
    time[0] = '0' + ((clock_reg[0] >> 4) & 0x01);
    time[1] = '0' + (clock_reg[0] & 0x0F);
  }
  else
  {
    time[0] = '0' + ((clock_reg[0] >> 4) & 0x03);
    time[1] = '0' + (clock_reg[0] & 0x0F);
  }
  time[2] = ':';
  time[3] = '0' + ((clock_reg[1] >> 4) & 0x0F);
  time[4] = '0' + (clock_reg[1] & 0x0F);
  time[5] = ':';
  time[6] = '0' + ((clock_reg[2] >> 4) & 0x0F);
  time[7] = '0' + (clock_reg[2] & 0x0F);
  time[8] = '\0';
}

void setup()
{
  Serial.begin(115200);

  init_ds1307();
}

void loop()
{
  get_time();
  display_time();

  delay(1000);
}

 

Schematic

Arduino Programming Example output:

 

Arduino Programming Example output:

Brief:

A simple application acting as a web browser to control the and get status of the device.

 

 
Source Code:
/*------------------------------------------------------------------------------------------------- 
 *   Author         : Emertxe (https://emertxe.com) 
 *   Date           : Wed 24 Mar 2021 16:0main.c0:04 IST
 *   Sketch         : SimpleWebBrowser.ino
 *   Title          : Web Browser
 *   Description    : A simple appilcation acting as a web browser to control the and get status
 *                    of the device
 *-----------------------------------------------------------------------------------------------*/

#include 

char ssid[] =     // Your network SSID (name)
char pass[] = // Your network password

WiFiServer server(80);

static bool state;

#define GPIO0 0
#define GPIO2 2

#define SWITCH_BUILTIN GPIO0
#define LED_BUILTIN GPIO2

#define OFF 1

void wifi_info(void)
{
    // print the SSID of the network you're attached to:
    Serial.print("SSID: ");
    Serial.println(WiFi.SSID());

    // print your WiFi shield's IP address:
    String ip = WiFi.localIP().toString();
    Serial.print("IP Address: ");
    Serial.println(ip);

    // print the received signal strength:
    long rssi = WiFi.RSSI();
    Serial.print("Signal strength (RSSI):");
    Serial.print(rssi);
    Serial.println(" dBm");

    Serial.println("\nType " + ip + " on your Web Browser to know more");
}

void setup()
{
    int wifi_state = WL_IDLE_STATUS;

    //Initialize serial and wait for port to open
    Serial.begin(115200);

    digitalWrite(LED_BUILTIN, OFF);

    pinMode(LED_BUILTIN, OUTPUT);
    pinMode(SWITCH_BUILTIN, INPUT);

    // Attempt to connect to Wifi network
    while (wifi_state != WL_CONNECTED)
    {
        Serial.print("Attempting to connect to SSID: ");
        Serial.println(ssid);
        // Connect to WPA/WPA2 network
        wifi_state = WiFi.begin(ssid, pass);

        // wait 2 seconds to retry
        delay(2000);
    }
    Serial.println("Wifi Connected");
    Serial.println("Initializing the server. Please wait for a while");
    server.begin();

    delay(10000);
    Serial.println("Done");

    // Connection establised, Let print the wifi info
    wifi_info();
}

void usage(WiFiClient client)
{
    String ip = WiFi.localIP().toString();

    client.println("
");
    client.print("Usage:");
    client.println("
");
    client.print(ip + "\t - Will show this page");
    client.println("
");
    client.print(ip + "/state - Get the LED status");
    client.println("
");
    client.print(ip + "/led/1 - Switch ON the LED");
    client.println("
");
    client.print(ip + "/led/0 - Switch OFF the LED");
}

void send(int update_state, WiFiClient client)
{
    client.println("HTTP/1.1 200 OK");
    client.println("Content-Type: text/html");
    client.println("Connection: close");
    client.println();
    client.println("");
    client.println("");

    if (update_state == 1)
    {
        client.print("# Welcome to Simple Web Service :-");
        usage(client);
    }
    else if (update_state == 2)
    {
        client.print("LED is ");
        client.print(state ? "ON" : "OFF");
    }
    else
    {
        client.print("Invalid Request");
        client.println("");
        usage(client);
    }

    client.println("");
    client.println("");
}

void service(void)
{
    // listen for incoming clients
    WiFiClient client = server.available();

    if (client)
    {
        Serial.println("New client request");

        int update_state = 0;

        if (client.connected())
        {
            if (client.available())
            {
                String command = "";
                char ch = '0';

                ch = client.read();

                while ((ch != '\n') && (ch != '\r'))
                {
                    command.concat(ch);
                    ch = client.read();
                }
                command.concat('\0');

                Serial.print("Received request: ");
                Serial.println(command);

                command = strtok((char *)&command[0], " ");
                command = strtok(NULL, " ");

                if (!strcmp((char *)&command[0], "/"))
                {
                    update_state = 1;
                }
                else if (!strcmp((char *)&command[0], "/state"))
                {
                    state = digitalRead(LED_BUILTIN);
                    update_state = 2;
                }
                else if (!strcmp((char *)&command[0], "/led/1"))
                {
                    state = 1;
                    digitalWrite(LED_BUILTIN, state);
                    update_state = 2;
                }
                else if (!strcmp((char *)&command[0], "/led/0"))
                {
                    state = 0;
                    digitalWrite(LED_BUILTIN, state);
                    update_state = 2;
                }
                else
                {
                    update_state = 0;
                }

                send(update_state, client);
            }
        }

        // close the connection:
        client.flush();
        client.stop();
        Serial.println("client disonnected");
    }
}

void led_control(void)
{
    static bool key;
    static bool once;

    key = digitalRead(SWITCH_BUILTIN);

    if (key && once)
    {
        once = 0;

        state = !state;
        digitalWrite(LED_BUILTIN, state);
    }
    else if (key == 0)
    {
        once = 1;
    }
}

void loop()
{
    service();
    led_control();
}

 

Arduino Programming Example output: