Send Text from a Web Page to Arduino LCD

details

This tutorial shows how to set up an Arduino and Ethernet shield as a web server that hosts an HTML web page on the SD card. The web page allows text to be entered into two text inputs. When the button on the web page is clicked, the text is sent to the LCD that is connected to the Arduino.

An Arduino Uno, Ethernet shield and 2 × 16 LCD display are needed for this tutorial, or similar compatible hardware.

Setting up the Hardware

The following parts are needed for the project:

  • Arduino Uno or similar Arduino, e.g. MEGA
  • Arduino Ethernet shield
  • Micro SD card, e.g. 2GB micro SD card
  • 2 line by 16 character LCD
  • 10k trim. pot (for LCD contrast)
  • Breadboard and wires
  • 39Ω to 47Ω resistor for LCD backlight (optional)
  • Standard USB cable
  • Ethernet patch cable

An Arduino board such as the Arduino Ethernet board can be used in place of a separate Arduino Uno and Ethernet shield.

A card reader or adapter for a micro SD card is needed to copy the HTML file from a PC to the micro SD card.

 

Connecting the LCD to the Arduino

The default pins used in the Arduino LCD example sketches (i.e. found in the Arduino IDE under File → Examples → LiquidCrystal) for connecting the LCD to the Arduino can not be used when an Ethernet shield is plugged into the Arduino. The pins used for the LCD must be changed so that they are not used by both the Ethernet shield and the Arduino.

In the sketch for this project, the following data pins are connected to the LCD:

  • DB7 → 5
  • DB6 → 6
  • DB5 → 7
  • DB4 → 8
  • E → 2
  • RS → 3

 

 

Code

  • /*--------------------------------------------------------------
      Program:      web2lcd
    
      Description:  Arduino web server gets text from HTML text
                    inputs on the hosted web page and displays the
                    text on a 2 line by 16 character LCD.
                    The web page is stored on the micro SD card.
      
      Date:         24 June 2015
     
      Author:       W.A. Smith, http://startingelectronics.org
    --------------------------------------------------------------*/
    
    #include <SPI.h>
    #include <Ethernet.h>
    #include <SD.h>
    #include <LiquidCrystal.h>
    // size of buffer used to capture HTTP requests
    #define REQ_BUF_SZ   90
    // size of buffer that stores a line of text for the LCD + null terminator
    #define LCD_BUF_SZ   17
    
    // MAC address from Ethernet shield sticker under board
    byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
    IPAddress ip(192, 168, 0, 20);   // IP address, may need to change depending on network
    EthernetServer server(80);       // create a server at port 80
    File webFile;                    // the web page file on the SD card
    char HTTP_req[REQ_BUF_SZ] = {0}; // buffered HTTP request stored as null terminated string
    char req_index = 0;              // index into HTTP_req buffer
    char lcd_buf_1[LCD_BUF_SZ] = {0};// buffer to save LCD line 1 text to
    char lcd_buf_2[LCD_BUF_SZ] = {0};// buffer to save LCD line 2 text to
    LiquidCrystal lcd(3, 2, 8, 7, 6, 5);
    
    void setup()
    {
        // disable Ethernet chip
        pinMode(10, OUTPUT);
        digitalWrite(10, HIGH);
        
        Serial.begin(115200);       // for debugging
    
        lcd.begin(16, 2);
        // Message on LCD
        lcd.print(F("Initializing"));
        
        // initialize SD card
        Serial.println("Initializing SD card...");
        if (!SD.begin(4)) {
            Serial.println("ERROR - SD card initialization failed!");
            lcd.print(F("SD init failed"));
            return;    // init failed
        }
        Serial.println("SUCCESS - SD card initialized.");
        // check for index.htm file
        if (!SD.exists("index.htm")) {
            Serial.println("ERROR - Can't find index.htm file!");
            return;  // can't find index file
        }
        Serial.println("SUCCESS - Found index.htm file.");
    
        Ethernet.begin(mac, ip);  // initialize Ethernet device
        server.begin();           // start to listen for clients
    
        // End of initialization message on LCD + print IP address
        lcd.clear();
        lcd.setCursor(0, 0);
        lcd.print(F("Done."));
        lcd.setCursor(0, 1);
        lcd.print(ip);
    }
    
    void loop()
    {
        EthernetClient client = server.available();  // try to get client
    
        if (client) {  // got client?
            boolean currentLineIsBlank = true;
            while (client.connected()) {
                if (client.available()) {   // client data available to read
                    char c = client.read(); // read 1 byte (character) from client
                    // limit the size of the stored received HTTP request
                    // buffer first part of HTTP request in HTTP_req array (string)
                    // leave last element in array as 0 to null terminate string (REQ_BUF_SZ - 1)
                    if (req_index < (REQ_BUF_SZ - 1)) {
                        HTTP_req[req_index] = c;          // save HTTP request character
                        req_index++;
                    }
                    // last line of client request is blank and ends with \n
                    // respond to client only after last line received
                    if (c == '\n' && currentLineIsBlank) {
                        // send a standard http response header
                        client.println("HTTP/1.1 200 OK");
                        // remainder of header follows below, depending on if
                        // web page or XML page is requested
                        // Ajax request - send XML file
                        if (StrContains(HTTP_req, "ajax_inputs")) {
                            // send rest of HTTP header
                            client.println("Content-Type: text/xml");
                            client.println("Connection: keep-alive");
                            client.println();
    
                            // print the received text to the LCD if found
                            if (GetLcdText(lcd_buf_1, lcd_buf_2, LCD_BUF_SZ)) {
                              // lcd_buf_1 and lcd_buf_2 now contain the text from
                              // the web page
                              // write the received text to the LCD
                              lcd.clear();
                              lcd.setCursor(0, 0);
                              lcd.print(lcd_buf_1);
                              lcd.setCursor(0, 1);
                              lcd.print(lcd_buf_2);
                            }
                        }
                        else {  // web page request
                            // send rest of HTTP header
                            client.println("Content-Type: text/html");
                            client.println("Connection: keep-alive");
                            client.println();
                            // send web page
                            webFile = SD.open("index.htm");        // open web page file
                            if (webFile) {
                                while(webFile.available()) {
                                    client.write(webFile.read()); // send web page to client
                                }
                                webFile.close();
                            }
                        }
                        // reset buffer index and all buffer elements to 0
                        req_index = 0;
                        StrClear(HTTP_req, REQ_BUF_SZ);
                        break;
                    }
                    // every line of text received from the client ends with \r\n
                    if (c == '\n') {
                        // last character on line of received text
                        // starting new line with next character read
                        currentLineIsBlank = true;
                    } 
                    else if (c != '\r') {
                        // a text character was received from client
                        currentLineIsBlank = false;
                    }
                } // end if (client.available())
            } // end while (client.connected())
            delay(1);      // give the web browser time to receive the data
            client.stop(); // close the connection
        } // end if (client)
    }
    
    // get the two strings for the LCD from the incoming HTTP GET request
    boolean GetLcdText(char *line1, char *line2, int len)
    {
      boolean got_text = false;    // text received flag
      char *str_begin;             // pointer to start of text
      char *str_end;               // pointer to end of text
      int str_len = 0;
      int txt_index = 0;
      char *current_line;
    
      current_line = line1;
    
      // get pointer to the beginning of the text
      str_begin = strstr(HTTP_req, "&L1=");
    
      for (int j = 0; j < 2; j++) { // do for 2 lines of text
        if (str_begin != NULL) {
          str_begin = strstr(str_begin, "=");  // skip to the =
          str_begin += 1;                      // skip over the =
          str_end = strstr(str_begin, "&");
    
          if (str_end != NULL) {
            str_end[0] = 0;  // terminate the string
            str_len = strlen(str_begin);
    
            // copy the string to the buffer and replace %20 with space ' '
            for (int i = 0; i < str_len; i++) {
              if (str_begin[i] != '%') {
                if (str_begin[i] == 0) {
                  // end of string
                  break;
                }
                else {
                  current_line[txt_index++] = str_begin[i];
                  if (txt_index >= (len - 1)) {
                    // keep the output string within bounds
                    break;
                  }
                }
              }
              else {
                // replace %20 with a space
                if ((str_begin[i + 1] == '2') && (str_begin[i + 2] == '0')) {
                  current_line[txt_index++] = ' ';
                  i += 2;
                  if (txt_index >= (len - 1)) {
                    // keep the output string within bounds
                    break;
                  }
                }
              }
            } // end for i loop
            // terminate the string
            current_line[txt_index] = 0;
            if (j == 0) {
              // got first line of text, now get second line
              str_begin = strstr(&str_end[1], "L2=");
              current_line = line2;
              txt_index = 0;
            }
            got_text = true;
          }
        }
      } // end for j loop
    
      return got_text;
    }
    
    // sets every element of str to 0 (clears array)
    void StrClear(char *str, char length)
    {
        for (int i = 0; i < length; i++) {
            str[i] = 0;
        }
    }
    
    // searches for the string sfind in the string str
    // returns 1 if string found
    // returns 0 if string not found
    char StrContains(char *str, char *sfind)
    {
        char found = 0;
        char index = 0;
        char len;
    
        len = strlen(str);
        
        if (strlen(sfind) > len) {
            return 0;
        }
        while (index < len) {
            if (str[index] == sfind[found]) {
                found++;
                if (strlen(sfind) == found) {
                    return 1;
                }
            }
            else {
                found = 0;
            }
            index++;
        }
    
        return 0;
    }
    
    

 

HTML and JavaScript index.htm File

The HTML and JavaScript code below must be copied to a file called index.htm on the micro SD card.

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <title>Arduino Web Page Text to LCD - web2lcd</title>
        <script>

        strLine1 = "";
        strLine2 = "";
        
        function SendText()
        {
            nocache = "&nocache=" + Math.random() * 1000000;
            var request = new XMLHttpRequest();
            
            strLine1 = "&L1=" + document.getElementById("txt_form").line1LCD.value;
            strLine2 = "&L2=" + document.getElementById("txt_form").line2LCD.value;
            
            request.open("GET", "ajax_inputs" + strLine1 + strLine2 + nocache, true);
            request.send(null);
        }
        </script>
    </head>

    <body onload="GetArduinoIO()">
        <p><b>Enter text to send to Arduino LCD:</b></p>
        <form id="txt_form" name="frmText">
            <label>Line 1: <input type="text" name="line1LCD" size="16" maxlength="16" /></label><br /><br />
            <label>Line 2: <input type="text" name="line2LCD" size="16" maxlength="16" /></label>
        </form>
        <br />
        <input type="submit" value="Send Text" onclick="SendText()" />
    </body>

</html>

Sending Text from the Web Page to the LCD

With the Arduino and Ethernet shield connected to the network, open up a web browser and surf to the IP address set in the Arduino sketch.

If everything is set up correctly, the web page hosted by the Arduino will appear in the web browser. Enter the text in the text fields to send to line 1 and line 2 of the LCD and click the button on the web page.

How the Web to LCD Sketch Works

The sketch is based on the code from the Arduino web server tutorial part 16 that uses Ajax for sending and receiving data between the Arduino web server and web page.

See the above link and also the Arduino web server tutorial for an explanation of the basics of the web server and related technology.

Getting the Text from the Web Page

The GetLcdText() function in the sketch gets the two lines of text for the LCD from the incoming HTTP GET request which is sent from the web browser when the user clicks the button on the web page.

In the GetLcdText() function, the code first looks for line 1 of the LCD text by searching for &L1= which precedes the actual text. The line of the text ends with & which is also the start of the second line of text.

All spaces in the text that are sent are converted to %20 by the browser before sending. While the code is getting the lines of text, it converts the encoded spaces to actual space characters for display on the LCD.

After the first line of text is copied from the HTTP GET request, the code loops to get the second line of text.

The video below shows the final project being tested. Text is entered into the two text inputs – each text input corresponds to one line of the LCD.

For more detail about this tutorial and all source code, visit below link.

http://startingelectronics.org/tutorials/arduino/web-page-to-LCD/

 

This tutorial shows how to set up an Arduino and Ethernet shield as a web server that hosts an HTML web page on the SD card. The web page allows text to be entered into two text inputs. When the button on the web page is clicked, the text is sent to the LCD that is connected to the Arduino.

An Arduino Uno, Ethernet shield and 2 × 16 LCD display are needed for this tutorial, or similar compatible hardware.

Setting up the Hardware

The following parts are needed for the project:

  • Arduino Uno or similar Arduino, e.g. MEGA
  • Arduino Ethernet shield
  • Micro SD card, e.g. 2GB micro SD card
  • 2 line by 16 character LCD
  • 10k trim. pot (for LCD contrast)
  • Breadboard and wires
  • 39Ω to 47Ω resistor for LCD backlight (optional)
  • Standard USB cable
  • Ethernet patch cable

An Arduino board such as the Arduino Ethernet board can be used in place of a separate Arduino Uno and Ethernet shield.

A card reader or adapter for a micro SD card is needed to copy the HTML file from a PC to the micro SD card.

 

Connecting the LCD to the Arduino

The default pins used in the Arduino LCD example sketches (i.e. found in the Arduino IDE under File → Examples → LiquidCrystal) for connecting the LCD to the Arduino can not be used when an Ethernet shield is plugged into the Arduino. The pins used for the LCD must be changed so that they are not used by both the Ethernet shield and the Arduino.

In the sketch for this project, the following data pins are connected to the LCD:

  • DB7 → 5
  • DB6 → 6
  • DB5 → 7
  • DB4 → 8
  • E → 2
  • RS → 3

 

 

Code

  • /*--------------------------------------------------------------
      Program:      web2lcd
    
      Description:  Arduino web server gets text from HTML text
                    inputs on the hosted web page and displays the
                    text on a 2 line by 16 character LCD.
                    The web page is stored on the micro SD card.
      
      Date:         24 June 2015
     
      Author:       W.A. Smith, http://startingelectronics.org
    --------------------------------------------------------------*/
    
    #include <SPI.h>
    #include <Ethernet.h>
    #include <SD.h>
    #include <LiquidCrystal.h>
    // size of buffer used to capture HTTP requests
    #define REQ_BUF_SZ   90
    // size of buffer that stores a line of text for the LCD + null terminator
    #define LCD_BUF_SZ   17
    
    // MAC address from Ethernet shield sticker under board
    byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
    IPAddress ip(192, 168, 0, 20);   // IP address, may need to change depending on network
    EthernetServer server(80);       // create a server at port 80
    File webFile;                    // the web page file on the SD card
    char HTTP_req[REQ_BUF_SZ] = {0}; // buffered HTTP request stored as null terminated string
    char req_index = 0;              // index into HTTP_req buffer
    char lcd_buf_1[LCD_BUF_SZ] = {0};// buffer to save LCD line 1 text to
    char lcd_buf_2[LCD_BUF_SZ] = {0};// buffer to save LCD line 2 text to
    LiquidCrystal lcd(3, 2, 8, 7, 6, 5);
    
    void setup()
    {
        // disable Ethernet chip
        pinMode(10, OUTPUT);
        digitalWrite(10, HIGH);
        
        Serial.begin(115200);       // for debugging
    
        lcd.begin(16, 2);
        // Message on LCD
        lcd.print(F("Initializing"));
        
        // initialize SD card
        Serial.println("Initializing SD card...");
        if (!SD.begin(4)) {
            Serial.println("ERROR - SD card initialization failed!");
            lcd.print(F("SD init failed"));
            return;    // init failed
        }
        Serial.println("SUCCESS - SD card initialized.");
        // check for index.htm file
        if (!SD.exists("index.htm")) {
            Serial.println("ERROR - Can't find index.htm file!");
            return;  // can't find index file
        }
        Serial.println("SUCCESS - Found index.htm file.");
    
        Ethernet.begin(mac, ip);  // initialize Ethernet device
        server.begin();           // start to listen for clients
    
        // End of initialization message on LCD + print IP address
        lcd.clear();
        lcd.setCursor(0, 0);
        lcd.print(F("Done."));
        lcd.setCursor(0, 1);
        lcd.print(ip);
    }
    
    void loop()
    {
        EthernetClient client = server.available();  // try to get client
    
        if (client) {  // got client?
            boolean currentLineIsBlank = true;
            while (client.connected()) {
                if (client.available()) {   // client data available to read
                    char c = client.read(); // read 1 byte (character) from client
                    // limit the size of the stored received HTTP request
                    // buffer first part of HTTP request in HTTP_req array (string)
                    // leave last element in array as 0 to null terminate string (REQ_BUF_SZ - 1)
                    if (req_index < (REQ_BUF_SZ - 1)) {
                        HTTP_req[req_index] = c;          // save HTTP request character
                        req_index++;
                    }
                    // last line of client request is blank and ends with \n
                    // respond to client only after last line received
                    if (c == '\n' && currentLineIsBlank) {
                        // send a standard http response header
                        client.println("HTTP/1.1 200 OK");
                        // remainder of header follows below, depending on if
                        // web page or XML page is requested
                        // Ajax request - send XML file
                        if (StrContains(HTTP_req, "ajax_inputs")) {
                            // send rest of HTTP header
                            client.println("Content-Type: text/xml");
                            client.println("Connection: keep-alive");
                            client.println();
    
                            // print the received text to the LCD if found
                            if (GetLcdText(lcd_buf_1, lcd_buf_2, LCD_BUF_SZ)) {
                              // lcd_buf_1 and lcd_buf_2 now contain the text from
                              // the web page
                              // write the received text to the LCD
                              lcd.clear();
                              lcd.setCursor(0, 0);
                              lcd.print(lcd_buf_1);
                              lcd.setCursor(0, 1);
                              lcd.print(lcd_buf_2);
                            }
                        }
                        else {  // web page request
                            // send rest of HTTP header
                            client.println("Content-Type: text/html");
                            client.println("Connection: keep-alive");
                            client.println();
                            // send web page
                            webFile = SD.open("index.htm");        // open web page file
                            if (webFile) {
                                while(webFile.available()) {
                                    client.write(webFile.read()); // send web page to client
                                }
                                webFile.close();
                            }
                        }
                        // reset buffer index and all buffer elements to 0
                        req_index = 0;
                        StrClear(HTTP_req, REQ_BUF_SZ);
                        break;
                    }
                    // every line of text received from the client ends with \r\n
                    if (c == '\n') {
                        // last character on line of received text
                        // starting new line with next character read
                        currentLineIsBlank = true;
                    } 
                    else if (c != '\r') {
                        // a text character was received from client
                        currentLineIsBlank = false;
                    }
                } // end if (client.available())
            } // end while (client.connected())
            delay(1);      // give the web browser time to receive the data
            client.stop(); // close the connection
        } // end if (client)
    }
    
    // get the two strings for the LCD from the incoming HTTP GET request
    boolean GetLcdText(char *line1, char *line2, int len)
    {
      boolean got_text = false;    // text received flag
      char *str_begin;             // pointer to start of text
      char *str_end;               // pointer to end of text
      int str_len = 0;
      int txt_index = 0;
      char *current_line;
    
      current_line = line1;
    
      // get pointer to the beginning of the text
      str_begin = strstr(HTTP_req, "&L1=");
    
      for (int j = 0; j < 2; j++) { // do for 2 lines of text
        if (str_begin != NULL) {
          str_begin = strstr(str_begin, "=");  // skip to the =
          str_begin += 1;                      // skip over the =
          str_end = strstr(str_begin, "&");
    
          if (str_end != NULL) {
            str_end[0] = 0;  // terminate the string
            str_len = strlen(str_begin);
    
            // copy the string to the buffer and replace %20 with space ' '
            for (int i = 0; i < str_len; i++) {
              if (str_begin[i] != '%') {
                if (str_begin[i] == 0) {
                  // end of string
                  break;
                }
                else {
                  current_line[txt_index++] = str_begin[i];
                  if (txt_index >= (len - 1)) {
                    // keep the output string within bounds
                    break;
                  }
                }
              }
              else {
                // replace %20 with a space
                if ((str_begin[i + 1] == '2') && (str_begin[i + 2] == '0')) {
                  current_line[txt_index++] = ' ';
                  i += 2;
                  if (txt_index >= (len - 1)) {
                    // keep the output string within bounds
                    break;
                  }
                }
              }
            } // end for i loop
            // terminate the string
            current_line[txt_index] = 0;
            if (j == 0) {
              // got first line of text, now get second line
              str_begin = strstr(&str_end[1], "L2=");
              current_line = line2;
              txt_index = 0;
            }
            got_text = true;
          }
        }
      } // end for j loop
    
      return got_text;
    }
    
    // sets every element of str to 0 (clears array)
    void StrClear(char *str, char length)
    {
        for (int i = 0; i < length; i++) {
            str[i] = 0;
        }
    }
    
    // searches for the string sfind in the string str
    // returns 1 if string found
    // returns 0 if string not found
    char StrContains(char *str, char *sfind)
    {
        char found = 0;
        char index = 0;
        char len;
    
        len = strlen(str);
        
        if (strlen(sfind) > len) {
            return 0;
        }
        while (index < len) {
            if (str[index] == sfind[found]) {
                found++;
                if (strlen(sfind) == found) {
                    return 1;
                }
            }
            else {
                found = 0;
            }
            index++;
        }
    
        return 0;
    }
    
    

 

HTML and JavaScript index.htm File

The HTML and JavaScript code below must be copied to a file called index.htm on the micro SD card.

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <title>Arduino Web Page Text to LCD - web2lcd</title>
        <script>

        strLine1 = "";
        strLine2 = "";
        
        function SendText()
        {
            nocache = "&nocache=" + Math.random() * 1000000;
            var request = new XMLHttpRequest();
            
            strLine1 = "&L1=" + document.getElementById("txt_form").line1LCD.value;
            strLine2 = "&L2=" + document.getElementById("txt_form").line2LCD.value;
            
            request.open("GET", "ajax_inputs" + strLine1 + strLine2 + nocache, true);
            request.send(null);
        }
        </script>
    </head>

    <body onload="GetArduinoIO()">
        <p><b>Enter text to send to Arduino LCD:</b></p>
        <form id="txt_form" name="frmText">
            <label>Line 1: <input type="text" name="line1LCD" size="16" maxlength="16" /></label><br /><br />
            <label>Line 2: <input type="text" name="line2LCD" size="16" maxlength="16" /></label>
        </form>
        <br />
        <input type="submit" value="Send Text" onclick="SendText()" />
    </body>

</html>

Sending Text from the Web Page to the LCD

With the Arduino and Ethernet shield connected to the network, open up a web browser and surf to the IP address set in the Arduino sketch.

If everything is set up correctly, the web page hosted by the Arduino will appear in the web browser. Enter the text in the text fields to send to line 1 and line 2 of the LCD and click the button on the web page.

How the Web to LCD Sketch Works

The sketch is based on the code from the Arduino web server tutorial part 16 that uses Ajax for sending and receiving data between the Arduino web server and web page.

See the above link and also the Arduino web server tutorial for an explanation of the basics of the web server and related technology.

Getting the Text from the Web Page

The GetLcdText() function in the sketch gets the two lines of text for the LCD from the incoming HTTP GET request which is sent from the web browser when the user clicks the button on the web page.

In the GetLcdText() function, the code first looks for line 1 of the LCD text by searching for &L1= which precedes the actual text. The line of the text ends with & which is also the start of the second line of text.

All spaces in the text that are sent are converted to %20 by the browser before sending. While the code is getting the lines of text, it converts the encoded spaces to actual space characters for display on the LCD.

After the first line of text is copied from the HTTP GET request, the code loops to get the second line of text.

The video below shows the final project being tested. Text is entered into the two text inputs – each text input corresponds to one line of the LCD.

For more detail about this tutorial and all source code, visit below link.

http://startingelectronics.org/tutorials/arduino/web-page-to-LCD/

 

COMMENTS

Please Login to comment
  Subscribe  
Notify of