Home » Controlling a robot with a smartphone

A tutorial to control a robot with an Android smartphone.

esus_robot_phone

Esus program

Here is the program for the ESP8266 microcontroller:

#include <ESP8266WiFi.h>
#include <esusBoard.h>
 
const char* ssid = "yout_SSID";
const char* password = "your_PASSWORD";

// server
WiFiServer server(80);

// adresse IP
IPAddress ip(192, 168, 1, 13); 
IPAddress gateway(192,168,1,1);
IPAddress subnet(255,255,255,0); 
 
void setup() 
{

  // init board
  initEsusBoard();

  
  Serial.begin(115200);
  delay(10);
 
  
  Serial.println();
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);
 
  WiFi.begin(ssid, password);
  WiFi.config(ip, gateway, subnet);

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

  // la carte Esus est connecter au reseau wifi
  Serial.println("");
  Serial.println("WiFi connected");
 
  
  server.begin();
  Serial.println("Server started");
 
  // Affichage de l'adresse IP sur le port serie
  Serial.print("Use this URL to connect: ");
  Serial.print("http://");
  Serial.print(WiFi.localIP());
  Serial.println("/");
 
}
 
void loop() 
{
  
  // vérification si un client est connecté
  WiFiClient client = server.available();

  // attendre la connexion d'un client
  while(client != true)
  {
    client = server.available();
    Serial.println("Attendre client...");
    delay(100);
  }
 
  // new client connected
  Serial.println("new client");
  while(!client.available()){
    delay(1);
  }

  
  String request = client.readStringUntil('\r');
  
  Serial.println(request);
  client.flush();

  // forward command
  if (request.indexOf("/CMD=FOR") != -1) 
  {
    Serial.println("forward");
    motors1_set(1023,DIR_BACK);
    motors2_set(1023, DIR_BACK);
  }

  // back command
  if (request.indexOf("/CMD=BAK") != -1) 
  {
    Serial.println("back");
    motors1_set(1023,DIR_FORWARD);
    motors2_set(1023, DIR_FORWARD);
  }

  // right command
  if (request.indexOf("/CMD=TR") != -1) 
  {
    Serial.println("turn right");
    motors1_set(1023,DIR_BACK);
    motors2_set(1023, DIR_FORWARD);
  }

  // left command
  if (request.indexOf("/CMD=TL") != -1) 
  {
    Serial.println("turn left");
    motors1_set(1023,DIR_FORWARD);
    motors2_set(1023, DIR_BACK);
  }

  // stop command
  if (request.indexOf("/CMD=STP") != -1) 
  {
    Serial.println("turn stop");
    motors1_set(0,DIR_FORWARD);
    motors2_set(0,DIR_BACK);
  }

  Serial.println("Client disonnected");
  Serial.println("");
 
}