lubosrusnak
Published © GPL3+

How To Control Arduino From Mobile Phone

Arduino Uno remote control via mobile phone.

IntermediateShowcase (no instructions)28,337
How To Control Arduino From Mobile Phone

Things used in this project

Story

Read more

Schematics

Example circuit

Code

Web server for Arduino

Arduino
When you upload and compile this file to your Arduino board, it will serve as a portable webserver which allows the board to be controlled remotely.
/*
 PROCE55 WiFi Server Example with JSON request parser
 */
 
#include <SPI.h>
#include <WiFi.h>
#include <LiquidCrystal.h>
    
char ssid[] = "P55";      // your network SSID (name)
char pass[] = "PROCE55mobile";  // your network password
//char ssid[] = "EG1";      // your network SSID (name)
//char pass[] = "XML4SDXML4SD1";  // your network password
//char ssid[] = "Tech_D0047758";      // your network SSID (name)
//char pass[] = "WBTJZXJU";  // your network password
// int keyIndex = 0;            // your network key Index number (needed only for WEP)
IPAddress ip(192, 168, 0, 90); // static IP for WiFi shield if needed

int status = WL_IDLE_STATUS;
WiFiServer server(80);          // Listen on tcp port 80
          
// initialize the library with the numbers of the interface pins
// LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
LiquidCrystal lcd(4, 9, 5, 8, 3, 2); // 13 instead of 4 (4,7,10,11 and 12 used by Wifi Shield)

void setup() {
  //Serial.begin(9600);      // initialize serial communication - comment out for better perfomance
  //while (!Serial) {
    // wait serial port initialization
  //}
  
  //pinMode(10, OUTPUT);      // HDG204 WiFi deactivate SD card pin 10, if necessary
  //digitalWrite(10, HIGH);

  // Turn of the LED by default
  pinMode(6, OUTPUT);
  digitalWrite(6, LOW);
  
  //pinMode(LED_BUILTIN, OUTPUT);
  //digitalWrite(LED_BUILTIN, LOW);

  // Init the LCD 16x2
  lcd.begin(16, 2);
  lcd.clear();
 
  // check for the presence of the shield:
  if (WiFi.status() == WL_NO_SHIELD) {
    //Serial.println("WiFi shield not present");
    lcd.clear();
    lcd.setCursor(0, 1);
    lcd.print(F("Error: no wifi!"));
    while (true);       // don't continue
  }

  /*
  if (WiFi.firmwareVersion() != "1.1.0") {
    Serial.println(F("Please upgrade the WiFi Shield firmware!"));
    lcd.clear();
    lcd.setCursor(0, 1);
    lcd.print(F("Firmware old!"));
  }
  */
  
  // attempt to connect to Wifi network:
  lcd.clear();
  lcd.setCursor(0, 0);
  lcd.print(F("Initializing..."));
  lcd.setCursor(0, 1);
  lcd.print(F("SSID:"));
  lcd.setCursor(5, 1);
  lcd.print(ssid);

  // Comment the WiFi.config if static setup not needed, DHCP applies then
  //WiFi.config(ip); // WiFi.config(ip, dns, gateway, subnet);  
   
  while (status != WL_CONNECTED) {
    //Serial.print(F("Attempting to connect to WLAN SSID: "));
    //Serial.println(ssid);                   // print the network name (SSID);  
    status = WiFi.begin(ssid, pass);
    // wait 6 seconds for connection:
    delay(6000);
  }
  server.begin();                           // start the web server on port 80
                         
  lcd.clear();
  lcd.setCursor(0, 0);
  lcd.print("Ready");
  printWifiStatus();
}

void loop() {
  WiFiClient client = server.available();   // listen for incoming clients
  
  if (client) {
    //Serial.print(F("Client connected"));
    String req_str = "";
    String currentLine = "";
    int data_length = 0;
    int data_read_length = 0;
    boolean skip = true; // Skip first CRLF in request header
    int response_length = 0; // HTTP response Content-Length
    int resp_value = -1;  // LED status
    
    lcd.clear(); lcd.setCursor(0, 0); lcd.print(F("Client")); lcd.setCursor(0, 1); lcd.print(F("connected"));
  
    while (client.connected()) 
    {
      if (client.available()) {
        char c = client.read();
        //Serial.write(c);
    
        if (data_length > data_read_length && !skip) {
          // Read remaining request body data
          req_str += c;
          data_read_length++;
          //Serial.println(data_read_length);
        }
        
        if (data_length <= data_read_length && !skip) { // c == '\n' &&
          // Request read completed, send response
               
          // find the request commands manually based on a substring
          if (req_str.lastIndexOf("\"OFF\"") >= 0) {
            digitalWrite(6, LOW);  
            resp_value = 0;
            //Serial.println(F("\r\n===> Setting LED off..."));
          }
          else if (req_str.lastIndexOf("\"ON\"") >= 0) {
            digitalWrite(6, HIGH);  
            resp_value = 1;
            //Serial.println(F("\r\n===> Setting LED on...")); 
          }
          else {
            // GET
            if (digitalRead(6) == 1) {
              resp_value = 1; // HIGH
             }
             else {
              resp_value = 0;  // LOW
             }
          }
          
          // Send the response
          //Serial.println(F("===> Request read completed, sending response..."));

          response_length = 56; // = 51 + 1 + 4;
          
          client.write("HTTP/1.1 200 OK\r\n");
          client.write("Content-Length: ");
          client.print(response_length); // sizeof(resp)
          client.write("\r\n");
          client.write("Connection: close\r\n");
          client.write("Access-Control-Allow-Origin: *\r\n");
          client.write("Content-type: application/json; charset=utf-8\r\n");
          client.write("\r\n");
          client.write("{\"Parameters\":[{\"ParamName\":\"STATUS\",\"ParamValue\":\""); // 51 characters
          client.print(resp_value); // 1 character
          client.write("\"}]}"); // 4 characters
          client.write("\r\n");
          break;
        }
        else if (c == '\n' && currentLine.length() == 0 && skip) {
          // Start of the request body after this line
          //Serial.println(F("===> Start of the request body."));
          skip = false;
        }
        else if (c == '\n' && currentLine.length() > 15 && currentLine.startsWith(F("Content-Length:")) && skip) {
          //skip = false;
          //String temp = currentLine.substring(15);
          //temp.trim();
          //Serial.print(F("===> Content length detected: "));
          //data_length = temp.toInt();
          data_length = currentLine.substring(15).toInt();
          //Serial.println("Content-length: ");
          //Serial.println(data_length);
        }

        if (c == '\n') {
          // new line
          currentLine = "";
        } else if (c != '\r') {
          // add current character to the current line
          currentLine += c;
        }
        
      } // if data available
    } // client still connected
    
    // give the client time to receive the data
    delay(50);
    // close the connection:
    client.stop();
    //Serial.println(F("===> Client disconnected."));
    printWifiStatus();
  }
}

/*
POST / HTTP/1.1
Content-Length: 328
Content-Type: application/json

{"FunctionName":"TEST","Status":"","StatusText":"","TextEncoding":"","SecurityToken":"","Parameters":[{"ParamName":"function_name","ParamValue":"TEST"},{"ParamName":"requestencoding","ParamValue":"UTF-8"},{"ParamName":"responseencoding","ParamValue":"UTF-8"},{"ParamName":"PARAM1","ParamValue":"Test passed!"}],"TableValues":[]}
  
  */
  
void printWifiStatus() {
  // print the SSID of the network you're attached to:
  Serial.print(F("SSID: "));
  Serial.println(WiFi.SSID());

  // print your WiFi shield's IP address:
  IPAddress ip = WiFi.localIP();
  Serial.print(F("IP Address: "));
  Serial.println(ip);
  
  // Status to LCD
  lcd.clear();
  lcd.setCursor(0, 0);
  lcd.print(WiFi.SSID());
  
  lcd.setCursor(0, 1);
  lcd.print(IpAddress2String(ip));
  
  // print the received signal strength:
  Serial.print(F("Signal strength (RSSI):"));
  Serial.print(WiFi.RSSI());
  Serial.println(F(" dBm"));
  // print where to go in a browser:
  Serial.print(F("Send your HTTP requests to http://"));
  Serial.println(ip);
  return;
}

String IpAddress2String(const IPAddress& ipAddress)
{
  return String(ipAddress[0]) + String(".") +\
  String(ipAddress[1]) + String(".") +\
  String(ipAddress[2]) + String(".") +\
  String(ipAddress[3])  ; 
}

Credits

lubosrusnak

lubosrusnak

1 project • 2 followers

Comments