Como dije en la entrada anterior. En el mundo en que vivimos no podemos dejar de utilizar Android para tomar datos y controlar equipos.
Resulta que el móvil es una herramienta omnipresente.
Version 1
En este ejemplo he utilizado realizado una aplicación para el móvil mediante un socket, para enviar la posición deseada mediante comandos "pos ...".
En este ejemplo el deslizador lo utilizaré para enviar comandos de posición de 0 a 180, mientras que los botones se usan para enviar posiciones absolutas (0,90,180).
Version 2
En este segundo vídeo he cambiado el programa del arduino para que los botones funcionen con comandos de manera que se realicen posicionamientos del servo, y comandos de ejecución combinados, tales como movimientos derecha izquierda, secuencias de oscilación y vibración del servo.
Aquí dejo los códigos de las dos pruebas.
Version 1- Programa Android
Corre sobre el programa Arduino de la entrada anterior
package com.example.joseangel.telemando;
import android.support.v7.app.ActionBarActivity;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.Menu;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import android.graphics.Color;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.SeekBar;
import android.widget.TextView;
import android.view.View;
import android.widget.ImageView;
public class MainActivity extends ActionBarActivity {
private Button btconect, btdisconect, btsndtxt, btnizq, btnder, bt1, bt2,
bt3, bt4;
private SeekBar pos;
private TextView txtstatus;
private EditText ipinput, portinput, input_txt;
private ImageView leds;
private boolean connected = false;
private Socket socket;
private String serverIpAddress = "192.168.4.1";
private static final int REDIRECTED_SERVERPORT = 23;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
leds = (ImageView) findViewById(R.id.leds);
btconect = (Button) findViewById(R.id.btcnt);
btdisconect = (Button) findViewById(R.id.btdisc);
bt1 = (Button) findViewById(R.id.bt1);
bt2 = (Button) findViewById(R.id.bt2);
bt3 = (Button) findViewById(R.id.bt3);
bt4 = (Button) findViewById(R.id.bt4);
txtstatus = (TextView) findViewById(R.id.txtstatus);
pos = (SeekBar) findViewById(R.id.Posicion);
pos.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener(){
@Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
// TODO Auto-generated method stub
String msg;
msg=String.valueOf(progress); // o Integer.toString(pos_bar):
boolean val_acc = Snd_Msg("pos "+msg);
//error al enviar
if (!val_acc) {
Set_txtstatus(" Error ", 0);
Change_leds(false);
Log.e("Snd_Action() -> ", "!ERROR!");
}
if (!socket.isConnected())
Change_leds(false);
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
});
//Botones de Accion
bt1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Snd_Action(1);
}
});
bt2.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Snd_Action(2);
}
});
bt3.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Snd_Action(3);
}
});
bt4.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Snd_Action(4);
}
});
//Al clickear en conectar
btconect.setOnClickListener(new OnClickListener() {
@Override
// conectar
public void onClick(View v) {
//Nos conectamos y obtenemos el estado de la conexion
boolean conectstatus = Connect();
//si nos pudimos conectar
if (conectstatus) {//mostramos mensaje
Set_txtstatus("Conexion OK ", 1);
Change_leds(true);//camiamos img a verde
} else {//error al conectarse
Change_leds(false);//camiamos img a rojo
//mostramos msg de error
Set_txtstatus("Error.. ", 0);
}
}
});
//Al clickear en desconectar
btdisconect.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
boolean conectstatus=Disconnect();
if (conectstatus) {//mostramos mensaje
Set_txtstatus(".. En espera ..", 1);
Change_leds(false);//camiamos img a verde
}
else {//error al conectarse
Change_leds(false);//camiamos img a rojo
//mostramos msg de error
Set_txtstatus("Error.. ", 0);
}
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
//Enviamos mensaje de accion segun el boton q presionamos
public void Snd_Action(int bt) {
String msg="";
//no hay texto
//seteo en el valor action el numero de accion
switch (bt) {
case 1:
msg = "pos 0";
break;
case 2:
msg = "pos 90";
break;
case 3:
msg = "pos 160";
break;
case 4:
msg = "comand 1";
break;
}
//mando msg
boolean val_acc = Snd_Msg(msg);
//error al enviar
if (!val_acc) {
Set_txtstatus(" Error ", 0);
Change_leds(false);
Log.e("Snd_Action() -> ", "!ERROR!");
}
if (!socket.isConnected())
Change_leds(false);
}
public boolean Snd_Msg(String msg) {
try {
//Accedo a flujo de salida
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())),true);
if (socket.isConnected())// si la conexion continua
{
//Envio mensaje por flujo
out.println(msg);
//envio ok
return true;
} else {//en caso de que no halla conexion al enviar el msg
Set_txtstatus("Error...", 0);//error
return false;
}
} catch (IOException e) {// hubo algun error
Log.e("Snd_Msg() ERROR -> ", "" + e);
return false;
}
}
//cambia el imageview segun status
public void Change_leds(boolean status) {
if (status)
leds.setImageResource(R.drawable.on);
else
leds.setImageResource(R.drawable.off);
}
/*Cambiamos texto de txtstatus segun parametro flag_status
* flag_status 0 error, 1 ok*/
public void Set_txtstatus(String txt, int flag_status) {
// cambiel color
switch (flag_status){
case 0:
txtstatus.setTextColor(Color.RED);
break;
case 1:
txtstatus.setTextColor(Color.GREEN);
break;
case 2:
txtstatus.setTextColor(Color.BLACK);
break;
}
txtstatus.setText(txt);
}
//Conectamos
public boolean Connect() {
//Obtengo datos ingresados en campos
try {
InetAddress serverAddr = InetAddress.getByName(serverIpAddress);
socket = new Socket(serverAddr, REDIRECTED_SERVERPORT);
//si nos conectamos
if (socket.isConnected() == true) {
return true;
} else {
return false;
}
} catch (UnknownHostException e1) {
e1.printStackTrace();
//Si hubo algun error mostrmos error
txtstatus.setTextColor(Color.RED);
txtstatus.setText(" !!! ERROR !!!");
Log.e("Error connect()","");
return false;
} catch (IOException e1) {
e1.printStackTrace();
//Si hubo algun error mostrmos error
txtstatus.setTextColor(Color.RED);
txtstatus.setText(" !!! ERROR !!!");
Log.e("Error connect()","");
return false;
}
}
//Metodo de desconexion
public boolean Disconnect() {
//Prepramos mensaje de desconexion
//avisamos al server que cierre el canal
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}
if (socket.isConnected())
return false;
return true;
}
Version 1- Programa Arduino
#include <SoftwareSerial.h>
#include "ESP8266.h"
#include <Servo.h>
Servo myservo;
SoftwareSerial esp8266Serial = SoftwareSerial(10, 11);
ESP8266 wifi = ESP8266(esp8266Serial);
int pos = 0;
int ESP_on = 12;
int Pin_servo=4;
void setup()
{
Serial.begin(9600);
// ESP8266
esp8266Serial.begin(9600);
pinMode(ESP_on, OUTPUT);
digitalWrite(ESP_on, HIGH);
wifi.begin();
wifi.setTimeout(2000);
// getVersion
char version[16] = {};
Serial.print("getVersion: ");
Serial.print(getStatus(wifi.getVersion(version, 16)));
Serial.print(" : ");
Serial.println(version);
/****************************************/
/****** WiFi commands ******/
/****************************************/
// setWifiMode
Serial.print("setWifiMode: ");
//Serial.println(getStatus(wifi.setMode(ESP8266_WIFI_STATION)));
Serial.println(getStatus(wifi.setMode(ESP8266_WIFI_ACCESSPOINT)));
// setAPConfiguration
Serial.print("setAPConfiguration: ");
Serial.println(getStatus(wifi.setAPConfiguration("ESP8266", "awesomelib", 10, ESP8266_ENCRYPTION_WPA_WPA2_PSK)));
wifi.restart();
// setMultipleConnections
Serial.print("setMultipleConnections: ");
Serial.println(getStatus(wifi.setMultipleConnections(true)));
// createServer
Serial.print("createServer: ");
Serial.println(getStatus(wifi.createServer(23)));
myservo.attach(Pin_servo);
}
void loop()
{
// read data
unsigned int id;
int comando,i;
int length,pos,old_pos;
int totalRead;
char buffer[128] = {};
if ((length = wifi.available()) > 0) {
id = wifi.getId();
totalRead = wifi.read(buffer, 127);
if (length > 0) {
String entrada(buffer);
// Serial.println(buffer);
if (entrada.startsWith("pos "))
{ pos=entrada.substring(4).toInt();
myservo.write(pos);
}
if(entrada.startsWith("CICLO "))
{ comando=entrada.substring(6).toInt();
switch(comando){
case 1: // hacer pasos de 10 de 0 a 180
myservo.write(0);
delay(500);
for(i=0; i<180; i+=10) {
myservo.write(i);
delay(50);}
break;
case 2:// hacer pasos de 10 de 180 a 0
myservo.write(180);
delay(500);
for(i=0; i<180; i+=10){
myservo.write(180-i);
delay(50);}
break;
case 3: // realizar 5 saludos
myservo.write(90);
delay(500);
for (i=0; i<5; i++) {
myservo.write(60);
delay(500);
myservo.write(120);
delay(500);
}
break;
case 4: //Realiza un tembleque
myservo.write(90);
delay(500);
for (i=0; i<10; i++) {
myservo.write(85);
delay(100);
myservo.write(95);
delay(100); }
break;
}
}
}
}
}
String getStatus(bool status)
{
if (status)
return "OK";
return "KO";
}
String getStatus(ESP8266CommandStatus status)
{
switch (status) {
case ESP8266_COMMAND_INVALID:
return "INVALID";
break;
case ESP8266_COMMAND_TIMEOUT:
return "TIMEOUT";
break;
case ESP8266_COMMAND_OK:
return "OK";
break;
case ESP8266_COMMAND_NO_CHANGE:
return "NO CHANGE";
break;
case ESP8266_COMMAND_ERROR:
return "ERROR";
break;
case ESP8266_COMMAND_NO_LINK:
return "NO LINK";
break;
case ESP8266_COMMAND_TOO_LONG:
return "TOO LONG";
break;
case ESP8266_COMMAND_FAIL:
return "FAIL";
break;
default:
return "UNKNOWN COMMAND STATUS";
break;
}
}
String getRole(ESP8266Role role)
{
switch (role) {
case ESP8266_ROLE_CLIENT:
return "CLIENT";
break;
case ESP8266_ROLE_SERVER:
return "SERVER";
break;
default:
return "UNKNOWN ROLE";
break;
}
}
String getProtocol(ESP8266Protocol protocol)
{
switch (protocol) {
case ESP8266_PROTOCOL_TCP:
return "TCP";
break;
case ESP8266_PROTOCOL_UDP:
return "UDP";
break;
default:
return "UNKNOWN PROTOCOL";
break;
}
}
Version 2- Programa Android
//Programa ejemplo control remoto servocontrol por wifi ESP8266
//By Jose Angel Moneo
package com.example.joseangel.telemando;
import android.support.v7.app.ActionBarActivity;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.Menu;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import android.graphics.Color;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.SeekBar;
import android.widget.TextView;
import android.view.View;
import android.widget.ImageView;
public class MainActivity extends ActionBarActivity {
private Button btconect, btdisconect, btsndtxt, btnizq, btnder, bt1, bt2,
bt3, bt4;
private SeekBar pos;
private TextView txtstatus;
private EditText ipinput, portinput, input_txt;
private ImageView leds;
private boolean connected = false;
private Socket socket;
private String serverIpAddress = "192.168.4.1";
private static final int REDIRECTED_SERVERPORT = 23;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
leds = (ImageView) findViewById(R.id.leds);
btconect = (Button) findViewById(R.id.btcnt);
btdisconect = (Button) findViewById(R.id.btdisc);
bt1 = (Button) findViewById(R.id.bt1);
bt2 = (Button) findViewById(R.id.bt2);
bt3 = (Button) findViewById(R.id.bt3);
bt4 = (Button) findViewById(R.id.bt4);
txtstatus = (TextView) findViewById(R.id.txtstatus);
pos = (SeekBar) findViewById(R.id.Posicion);
pos.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener(){
@Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
// TODO Auto-generated method stub
String msg;
msg=String.valueOf(progress); // o Integer.toString(pos_bar):
boolean val_acc = Snd_Msg("pos "+msg);
//error al enviar
if (!val_acc) {
Set_txtstatus(" Error ", 0);
Change_leds(false);
Log.e("Snd_Action() -> ", "!ERROR!");
}
if (!socket.isConnected())
Change_leds(false);
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
});
//Botones de Accion
bt1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Snd_Action(1);
}
});
bt2.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Snd_Action(2);
}
});
bt3.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Snd_Action(3);
}
});
bt4.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Snd_Action(4);
}
});
//Al clickear en conectar
btconect.setOnClickListener(new OnClickListener() {
@Override
// conectar
public void onClick(View v) {
//Nos conectamos y obtenemos el estado de la conexion
boolean conectstatus = Connect();
//si nos pudimos conectar
if (conectstatus) {//mostramos mensaje
Set_txtstatus("Conexion OK ", 1);
Change_leds(true);//camiamos img a verde
} else {//error al conectarse
Change_leds(false);//camiamos img a rojo
//mostramos msg de error
Set_txtstatus("Error.. ", 0);
}
}
});
//Al clickear en desconectar
btdisconect.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
boolean conectstatus=Disconnect();
if (conectstatus) {//mostramos mensaje
Set_txtstatus(".. En espera ..", 1);
Change_leds(false);//camiamos img a verde
}
else {//error al conectarse
Change_leds(false);//camiamos img a rojo
//mostramos msg de error
Set_txtstatus("Error.. ", 0);
}
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
//Enviamos mensaje de accion segun el boton q presionamos
public void Snd_Action(int bt) {
String msg="";
//no hay texto
//seteo en el valor action el numero de accion
switch (bt) {
case 1:
msg = "CICLO 1";
break;
case 2:
msg = "CICLO 2";
break;
case 3:
msg = "CICLO 3";
break;
case 4:
msg = "CICLO 4";
break;
}
//mando msg
boolean val_acc = Snd_Msg(msg);
//error al enviar
if (!val_acc) {
Set_txtstatus(" Error ", 0);
Change_leds(false);
Log.e("Snd_Action() -> ", "!ERROR!");
}
if (!socket.isConnected())
Change_leds(false);
}
/*Metodo para enviar mensaje por socket
*/
public boolean Snd_Msg(String msg) {
try {
//Accedo a flujo de salida
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())),true);
if (socket.isConnected())// si la conexion continua
{
//Envio mensaje por flujo
out.println(msg);
//envio ok
return true;
} else {//en caso de que no halla conexion al enviar el msg
Set_txtstatus("Error...", 0);//error
return false;
}
} catch (IOException e) {// hubo algun error
Log.e("Snd_Msg() ERROR -> ", "" + e);
return false;
}
}
//cambia el imageview segun status
public void Change_leds(boolean status) {
if (status)
leds.setImageResource(R.drawable.on);
else
leds.setImageResource(R.drawable.off);
}
/*Cambiamos texto de txtstatus segun parametro flag_status
* flag_status 0 error, 1 ok*/
public void Set_txtstatus(String txt, int flag_status) {
// cambiel color
switch (flag_status){
case 0:
txtstatus.setTextColor(Color.RED);
break;
case 1:
txtstatus.setTextColor(Color.GREEN);
break;
case 2:
txtstatus.setTextColor(Color.BLACK);
break;
}
txtstatus.setText(txt);
}
//Conectamos
public boolean Connect() {
//Obtengo datos ingresados en campos
try {
InetAddress serverAddr = InetAddress.getByName(serverIpAddress);
socket = new Socket(serverAddr, REDIRECTED_SERVERPORT);
//si nos conectamos
if (socket.isConnected() == true) {
return true;
} else {
return false;
}
} catch (UnknownHostException e1) {
e1.printStackTrace();
//Si hubo algun error mostramos error
txtstatus.setTextColor(Color.RED);
txtstatus.setText(" !!! ERROR !!!");
Log.e("Error connect()","");
return false;
} catch (IOException e1) {
e1.printStackTrace();
//Si hubo algun error mostramos error
txtstatus.setTextColor(Color.RED);
txtstatus.setText(" !!! ERROR !!!");
Log.e("Error connect()","");
return false;
}
}
//Metodo de desconexion
public boolean Disconnect() {
//Prepramos mensaje de desconexion
//avisamos al server que cierre el canal
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}
if (socket.isConnected())
return false;
return true;
}
}
//By Jose Angel Moneo
package com.example.joseangel.telemando;
import android.support.v7.app.ActionBarActivity;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.Menu;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import android.graphics.Color;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.SeekBar;
import android.widget.TextView;
import android.view.View;
import android.widget.ImageView;
public class MainActivity extends ActionBarActivity {
private Button btconect, btdisconect, btsndtxt, btnizq, btnder, bt1, bt2,
bt3, bt4;
private SeekBar pos;
private TextView txtstatus;
private EditText ipinput, portinput, input_txt;
private ImageView leds;
private boolean connected = false;
private Socket socket;
private String serverIpAddress = "192.168.4.1";
private static final int REDIRECTED_SERVERPORT = 23;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
leds = (ImageView) findViewById(R.id.leds);
btconect = (Button) findViewById(R.id.btcnt);
btdisconect = (Button) findViewById(R.id.btdisc);
bt1 = (Button) findViewById(R.id.bt1);
bt2 = (Button) findViewById(R.id.bt2);
bt3 = (Button) findViewById(R.id.bt3);
bt4 = (Button) findViewById(R.id.bt4);
txtstatus = (TextView) findViewById(R.id.txtstatus);
pos = (SeekBar) findViewById(R.id.Posicion);
pos.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener(){
@Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
// TODO Auto-generated method stub
String msg;
msg=String.valueOf(progress); // o Integer.toString(pos_bar):
boolean val_acc = Snd_Msg("pos "+msg);
//error al enviar
if (!val_acc) {
Set_txtstatus(" Error ", 0);
Change_leds(false);
Log.e("Snd_Action() -> ", "!ERROR!");
}
if (!socket.isConnected())
Change_leds(false);
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
});
//Botones de Accion
bt1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Snd_Action(1);
}
});
bt2.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Snd_Action(2);
}
});
bt3.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Snd_Action(3);
}
});
bt4.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Snd_Action(4);
}
});
//Al clickear en conectar
btconect.setOnClickListener(new OnClickListener() {
@Override
// conectar
public void onClick(View v) {
//Nos conectamos y obtenemos el estado de la conexion
boolean conectstatus = Connect();
//si nos pudimos conectar
if (conectstatus) {//mostramos mensaje
Set_txtstatus("Conexion OK ", 1);
Change_leds(true);//camiamos img a verde
} else {//error al conectarse
Change_leds(false);//camiamos img a rojo
//mostramos msg de error
Set_txtstatus("Error.. ", 0);
}
}
});
//Al clickear en desconectar
btdisconect.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
boolean conectstatus=Disconnect();
if (conectstatus) {//mostramos mensaje
Set_txtstatus(".. En espera ..", 1);
Change_leds(false);//camiamos img a verde
}
else {//error al conectarse
Change_leds(false);//camiamos img a rojo
//mostramos msg de error
Set_txtstatus("Error.. ", 0);
}
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
//Enviamos mensaje de accion segun el boton q presionamos
public void Snd_Action(int bt) {
String msg="";
//no hay texto
//seteo en el valor action el numero de accion
switch (bt) {
case 1:
msg = "CICLO 1";
break;
case 2:
msg = "CICLO 2";
break;
case 3:
msg = "CICLO 3";
break;
case 4:
msg = "CICLO 4";
break;
}
//mando msg
boolean val_acc = Snd_Msg(msg);
//error al enviar
if (!val_acc) {
Set_txtstatus(" Error ", 0);
Change_leds(false);
Log.e("Snd_Action() -> ", "!ERROR!");
}
if (!socket.isConnected())
Change_leds(false);
}
/*Metodo para enviar mensaje por socket
*/
public boolean Snd_Msg(String msg) {
try {
//Accedo a flujo de salida
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())),true);
if (socket.isConnected())// si la conexion continua
{
//Envio mensaje por flujo
out.println(msg);
//envio ok
return true;
} else {//en caso de que no halla conexion al enviar el msg
Set_txtstatus("Error...", 0);//error
return false;
}
} catch (IOException e) {// hubo algun error
Log.e("Snd_Msg() ERROR -> ", "" + e);
return false;
}
}
//cambia el imageview segun status
public void Change_leds(boolean status) {
if (status)
leds.setImageResource(R.drawable.on);
else
leds.setImageResource(R.drawable.off);
}
/*Cambiamos texto de txtstatus segun parametro flag_status
* flag_status 0 error, 1 ok*/
public void Set_txtstatus(String txt, int flag_status) {
// cambiel color
switch (flag_status){
case 0:
txtstatus.setTextColor(Color.RED);
break;
case 1:
txtstatus.setTextColor(Color.GREEN);
break;
case 2:
txtstatus.setTextColor(Color.BLACK);
break;
}
txtstatus.setText(txt);
}
//Conectamos
public boolean Connect() {
//Obtengo datos ingresados en campos
try {
InetAddress serverAddr = InetAddress.getByName(serverIpAddress);
socket = new Socket(serverAddr, REDIRECTED_SERVERPORT);
//si nos conectamos
if (socket.isConnected() == true) {
return true;
} else {
return false;
}
} catch (UnknownHostException e1) {
e1.printStackTrace();
//Si hubo algun error mostramos error
txtstatus.setTextColor(Color.RED);
txtstatus.setText(" !!! ERROR !!!");
Log.e("Error connect()","");
return false;
} catch (IOException e1) {
e1.printStackTrace();
//Si hubo algun error mostramos error
txtstatus.setTextColor(Color.RED);
txtstatus.setText(" !!! ERROR !!!");
Log.e("Error connect()","");
return false;
}
}
//Metodo de desconexion
public boolean Disconnect() {
//Prepramos mensaje de desconexion
//avisamos al server que cierre el canal
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}
if (socket.isConnected())
return false;
return true;
}
}
Version 2- Programa Arduino
//Programa ejemplo control remoto servocontrol por wifi ESP8266
//By Jose Angel Moneo
#include <SoftwareSerial.h>
#include "ESP8266.h"
#include <Servo.h>
Servo myservo;
SoftwareSerial esp8266Serial = SoftwareSerial(10, 11);
ESP8266 wifi = ESP8266(esp8266Serial);
int pos = 0;
int ESP_on = 12;
int Pin_servo=4;
void setup()
{
Serial.begin(9600);
// ESP8266
esp8266Serial.begin(9600);
pinMode(ESP_on, OUTPUT);
digitalWrite(ESP_on, HIGH);
wifi.begin();
wifi.setTimeout(2000);
// getVersion
char version[16] = {};
Serial.print("getVersion: ");
Serial.print(getStatus(wifi.getVersion(version, 16)));
Serial.print(" : ");
Serial.println(version);
/****************************************/
/****** WiFi commands ******/
/****************************************/
// setWifiMode
Serial.print("setWifiMode: ");
//Serial.println(getStatus(wifi.setMode(ESP8266_WIFI_STATION)));
Serial.println(getStatus(wifi.setMode(ESP8266_WIFI_ACCESSPOINT)));
// setAPConfiguration
Serial.print("setAPConfiguration: ");
Serial.println(getStatus(wifi.setAPConfiguration("ESP8266", "awesomelib", 10, ESP8266_ENCRYPTION_WPA_WPA2_PSK)));
wifi.restart();
// setMultipleConnections
Serial.print("setMultipleConnections: ");
Serial.println(getStatus(wifi.setMultipleConnections(true)));
// createServer
Serial.print("createServer: ");
Serial.println(getStatus(wifi.createServer(23)));
myservo.attach(Pin_servo);
}
void loop()
{
// read data
unsigned int id;
int comando,i;
int length,pos,old_pos;
int totalRead;
char buffer[128] = {};
if ((length = wifi.available()) > 0) {
id = wifi.getId();
totalRead = wifi.read(buffer, 127);
if (length > 0) {
String entrada(buffer);
// Serial.println(buffer);
if (entrada.startsWith("pos "))
{ pos=entrada.substring(4).toInt();
myservo.write(pos);
}
if(entrada.startsWith("CICLO "))
{ comando=entrada.substring(6).toInt();
switch(comando){
case 1: // hacer pasos de 10 de 0 a 180
myservo.write(0);
delay(500);
for(i=0; i<180; i+=10) {
myservo.write(i);
delay(50);}
break;
case 2:// hacer pasos de 10 de 180 a 0
myservo.write(180);
delay(500);
for(i=0; i<180; i+=10){
myservo.write(180-i);
delay(50);}
break;
case 3: // realizar 5 saludos
myservo.write(90);
delay(500);
for (i=0; i<5; i++) {
myservo.write(60);
delay(500);
myservo.write(120);
delay(500);
}
break;
case 4: //Realiza un tembleque
myservo.write(90);
delay(500);
for (i=0; i<10; i++) {
myservo.write(85);
delay(100);
myservo.write(95);
delay(100); }
break;
}
}
}
}
}
String getStatus(bool status)
{
if (status)
return "OK";
return "KO";
}
String getStatus(ESP8266CommandStatus status)
{
switch (status) {
case ESP8266_COMMAND_INVALID:
return "INVALID";
break;
case ESP8266_COMMAND_TIMEOUT:
return "TIMEOUT";
break;
case ESP8266_COMMAND_OK:
return "OK";
break;
case ESP8266_COMMAND_NO_CHANGE:
return "NO CHANGE";
break;
case ESP8266_COMMAND_ERROR:
return "ERROR";
break;
case ESP8266_COMMAND_NO_LINK:
return "NO LINK";
break;
case ESP8266_COMMAND_TOO_LONG:
return "TOO LONG";
break;
case ESP8266_COMMAND_FAIL:
return "FAIL";
break;
default:
return "UNKNOWN COMMAND STATUS";
break;
}
}
String getRole(ESP8266Role role)
{
switch (role) {
case ESP8266_ROLE_CLIENT:
return "CLIENT";
break;
case ESP8266_ROLE_SERVER:
return "SERVER";
break;
default:
return "UNKNOWN ROLE";
break;
}
}
String getProtocol(ESP8266Protocol protocol)
{
switch (protocol) {
case ESP8266_PROTOCOL_TCP:
return "TCP";
break;
case ESP8266_PROTOCOL_UDP:
return "UDP";
break;
default:
return "UNKNOWN PROTOCOL";
break;
}
}