rreedd
(http://fotos.subefotos.com/268ab19be0d651c02a7177176da31ad6o.png)
rreedd
Descargar Versión PDF.
https://mega.nz/#!rkdU1LbD!wUKSzni5JOpvWMogNZgxE_I-uWDqWk8_96-n9Vulf0E (https://mega.nz/#!rkdU1LbD!wUKSzni5JOpvWMogNZgxE_I-uWDqWk8_96-n9Vulf0E)
Hola !!
Como están compañeros, en este post les haré un tutorial sobre como construir un sistema de medición de humedad con Arduino , el cual se pueda conectar con Android por medio de bluetooth.
Este es el primero de una serie de tutoriales que haré para que se entretengan armando sus propios artilugios y aprendamos entre todos.
El sistema en si es muy simple, pero para hacerlo mas interesante le agregue la interfaz con Android ;D, intentare hacerlo lo mas simple posible pero si por el camino surge alguna duda o sugerencia, por favor no duden en comentarla.
Materiales
- Placa Arduino Nano
(http://files.mvelectronica.com.mx/system_preview_200000007-97e1a99094/Arduino%20Nano-500x500.jpg)
- Sensor de Humedad (Módulo HL-69)
(http://files.ipower-electronics.com/system_preview_200000951-5207d5300f/Higrometro.jpg)
- Módulo Bluetooth HC-06
(http://mlv-s2-p.mlstatic.com/153701-MLV20372115607_082015-N.jpg)
¿Como funciona el medidor de Humedad? :'(
Este sensor Funciona de una forma muy simple, para poder calcular la humedad de la tierra el modulo
hace pasar una corriente por los extremos de una sonda, midiendo la resistencia entre ambos polos
logrando darnos una estimación de la humedad.
Esto se traduce en que mientras mayor sera la cantidad de agua en el suelo (humedad), la electricidad
podrá circular con menos resistencia en cambio si existe un nivel bajo de humedad en el la tierra la
electricidad no podrá circular tan eficazmente y encontrara mas resistencia.
Pines
VCC : 3.3 - 5 V.
GND : Masa (negativo).
DO : (Salida Digital) nos devolverá un prendido o apagado (on - off)
AO : (Salida Analógica) la cual nos traducirá en en una respuesta entre 0 y los 1023, siendo 0 una máxima
sequedad y 1023 un exceso de agua (charco)
Codigo del programa en Arduino
PROYECO_DETECTOR_DE_HUMEDAD.ino
/*
_________________
|d13 D12|
|3v3 D11|
|REF D10|
A0 (SENSOR) |A0 Arduino D9|
|A1 NANO D8|
|A2 D7|
|A3 D6|
|A4 D5|
|A5 D4|
|A6 D3|
|A7 D2|
VCC (Bluetooth, Sensor) |5v GND| GND (Bluetooth, Sensor)
|RST RST|
-9 v (Bateria) |GND TR| TX (Bluetooth)
+9 v (Bateria) |VIN TX| TR (Bluetooth)
|_______________|
*/
int humedad,temp;
void setup() {
Serial.begin(9600); // Establecemos la comunicacion Serial a 9600 baud
humedad =0;
temp=0;
}
void loop() {
temp = analogRead(A0); //leemos el sensor
humedad = (map(temp, 0, 1032, 0, 100));// establecemos los limites del valor recivido
Serial.println(humedad); // mostramos por pantalla
delay(500); //espera de medio segundo para volver a correr el programa
}
Codigo del programa en Android
MainActivity.java
package com.example.rreedd.rreeddarduino01;
import android.app.ListActivity;
import android.bluetooth.*;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.*;
import java.io.*;
import java.util.ArrayList;
import java.util.Set;
import java.util.UUID;
public class MainActivity extends ListActivity {
private TextView humedad, txtlog,txtdata;
private ProgressBar barraHumedad;
Thread hiloA = new HiloCliente();
private ArrayAdapter<String> ListadoDeAdaptadores;
private BluetoothAdapter AdaptadorBluetooth;
private BluetoothSocket BluetoothSocket;
private ArrayList<BluetoothDevice> ListadoDeDispositivos = new ArrayList<BluetoothDevice>();
private ConnectAsyncTask connectAsyncTask;
private String log;
private ImageView img;
private Bitmap on,off;
private Button Botton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// creamos los objetos del tipo correspondientes a la interfaz para poder obtener sus valores
img = (ImageView) findViewById(R.id.imageView2);
off = BitmapFactory.decodeResource(getResources(), R.drawable.off);
on = BitmapFactory.decodeResource(getResources(), R.drawable.on );
humedad = (TextView) findViewById(R.id.txtDatos);
txtlog = (TextView) findViewById(R.id.txtLog);
txtdata = (TextView) findViewById(R.id.txtDatos);
barraHumedad = (ProgressBar) findViewById(R.id.barraHumedad);
Botton = (Button)findViewById(R.id.button);
ListadoDeAdaptadores = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1);
setListAdapter(ListadoDeAdaptadores);
connectAsyncTask = new ConnectAsyncTask();
AdaptadorBluetooth = BluetoothAdapter.getDefaultAdapter();
// se ve si es que el dispositivo acepta bluetooth
if(AdaptadorBluetooth == null){
Toast.makeText(getApplicationContext(), "Not support bluetooth", Toast.LENGTH_LONG).show();
finish();
}
// se ve si es que el bluetooth esta activado
if(!AdaptadorBluetooth.isEnabled()){
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, 1);
}
ActualizarDispositivos();
Botton.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
// se llama a función ActualizarDispositivos()
ActualizarDispositivos();
}
});
}
// funcion encargada de actualizar la lista de dispositivos reconocidos por el teléfono
private void ActualizarDispositivos(){
Set<BluetoothDevice> pariedDevices = AdaptadorBluetooth.getBondedDevices();
if(pariedDevices.size() > 0) {
for (BluetoothDevice device : pariedDevices) {
ListadoDeAdaptadores.add(device.getName() + "\n" + device.getAddress());
ListadoDeDispositivos.add(device);
}
}
}
@Override
// si se presiona un dispositivo en la lista se ejecutara la conexión con este
protected void onListItemClick(ListView l, View v, int position, long id) {
try {
BluetoothDevice device = ListadoDeDispositivos.get(position);
connectAsyncTask.execute(device);
}catch (IllegalStateException a){
}catch (NullPointerException a){}
}
// cierra la conexión con el dispositivo
private void DetenerServidor() throws IOException {
BluetoothSocket.close();
}
//
private void IniciarServidor() {
OutputStream mmOutStream = null;
try {
if(BluetoothSocket.isConnected()){
mmOutStream = BluetoothSocket.getOutputStream();
mmOutStream.write(new String("").getBytes());
}
} catch (IOException e) {
System.out.println(e);
}
}
// se configura la conexión para con el dispositivo bluetooth
private class ConnectAsyncTask extends AsyncTask<BluetoothDevice, Integer, BluetoothSocket> {
private BluetoothSocket SocketConf;
private BluetoothDevice DeviceConf;
@Override
protected BluetoothSocket doInBackground(BluetoothDevice... device) {
DeviceConf = device[0];
try {
String mmUUID = "00001101-0000-1000-8000-00805F9B34FB";
SocketConf = DeviceConf.createInsecureRfcommSocketToServiceRecord(UUID.fromString(mmUUID));
SocketConf.connect();
} catch (Exception e) {
}
return SocketConf;
}
@Override
protected void onPostExecute(BluetoothSocket result) {
BluetoothSocket = result;
BluetoothDevice d = BluetoothSocket.getRemoteDevice();
log = log + "\n" + "log";
log = " Conectado !!!" + "\n" + "\n" +
" Direccion : " + d.getAddress() + "\n" +
" Nombre : " + d.getName() + "\n";
txtlog.setText(log);
hiloA.start();
img.setImageBitmap(on);
Toast.makeText(getApplicationContext(), "CONECTADO", Toast.LENGTH_LONG).show();
}
}
// hilo encargado de recibir los mensajes desde arduino
class HiloCliente extends Thread {
public void run() {
InputStream input;
try {
sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
try {
// si esta conectado sigue
if(BluetoothSocket.isConnected()){
if(BluetoothSocket == null)System.out.println("El Socket no tiene contenido");
//PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(BluetoothSocket.getOutputStream())),true);
// Se toma la entrada desde el socket y se pasa a un BufferedReader donde posteriormente la extraeremos
BufferedReader Entrada = new BufferedReader(new InputStreamReader(BluetoothSocket.getInputStream()));
// ciclo infinito
while(true){
// variable a la que se le dara el valor de cada dato recibido desde el arduino
final String Respuesta = Entrada.readLine();
System.out.println(Respuesta);
runOnUiThread(new Runnable() {
@Override
public void run() {
// se editan los datos vistos por el usuario
txtdata.setText(Respuesta + "%"+"\n"+" De Humedad" );
barraHumedad.setProgress(Integer.parseInt(Respuesta));
}
});
}
}
} catch (IOException e) {
System.out.println("IOException Fallo en el el hilo Cliente");
}
}
}
}
activivity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.rreedd.rreeddarduino01.MainActivity"
android:background="#db020202">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageView3"
android:layout_gravity="center_horizontal|bottom"
android:src="@drawable/logo_underc0de"
android:layout_alignParentBottom="true"
android:layout_alignParentStart="true" />
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Log"
android:id="@+id/txtLog"
android:layout_gravity="bottom"
android:background="@drawable/log"
android:textColor="#40d92e"
android:textSize="15dp"
android:layout_alignParentStart="true"
android:layout_alignEnd="@+id/imageView3"
android:layout_above="@+id/imageView3"
android:textStyle="normal"
android:layout_alignTop="@+id/textView" />
<ScrollView
android:layout_width="wrap_content"
android:layout_height="60dp"
android:id="@+id/scrollView2"
android:background="@drawable/log"
android:layout_alignParentTop="true"
android:layout_alignParentEnd="true"
android:layout_toEndOf="@+id/textView5"
android:layout_alignStart="@+id/imageView4">
<ListView
android:id="@android:id/list"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_above="@+id/imageView"
android:textSize="15dp"
android:layout_below="@+id/btToggle"
android:textAlignment="center">
</ListView>
</ScrollView>
<ImageView
android:layout_width="20dp"
android:layout_height="20dp"
android:id="@+id/imageView2"
android:src="@drawable/off"
android:layout_alignParentTop="true"
android:layout_toStartOf="@+id/scrollView2" />
<ImageView
android:layout_width="70dp"
android:layout_height="100dp"
android:id="@+id/imageView4"
android:src="@drawable/humedad"
android:layout_gravity="center"
android:layout_marginTop="37dp"
android:layout_below="@+id/scrollView2"
android:layout_centerHorizontal="true" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:id="@+id/textView"
android:layout_marginBottom="68dp"
android:layout_above="@+id/imageView3"
android:layout_alignParentEnd="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Sin Datos"
android:id="@+id/txtDatos"
android:textColor="#19aace"
android:textSize="25dp"
android:textAlignment="center"
android:textStyle="bold"
android:gravity="center_horizontal"
android:layout_gravity="center"
android:layout_below="@+id/imageView4"
android:layout_centerHorizontal="true" />
<ProgressBar
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/barraHumedad"
android:background="#404040"
android:layout_above="@+id/txtLog"
android:layout_alignParentEnd="true"
android:layout_marginBottom="34dp"
android:max="100"
android:indeterminate="false" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="Muy Bajo"
android:id="@+id/textView2"
android:textColor="#c8db232f"
android:textSize="18dp"
android:layout_above="@+id/barraHumedad"
android:layout_alignParentStart="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="Medio"
android:id="@+id/textView4"
android:textColor="#c5dbd523"
android:textSize="18dp"
android:layout_alignTop="@+id/textView5"
android:layout_centerHorizontal="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="Alto (Charco)"
android:id="@+id/textView5"
android:textColor="#c100ff11"
android:textSize="18dp"
android:layout_above="@+id/barraHumedad"
android:layout_alignEnd="@+id/barraHumedad" />
<Button
android:layout_width="40dp"
android:layout_height="40dp"
android:id="@+id/button"
android:background="@drawable/recargar"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true" />
</RelativeLayout>
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.rreedd.rreeddarduino01"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="18"
android:targetSdkVersion="23" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_PRIVILEGED" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<application
android:allowBackup="true"
android:icon="@drawable/humedad"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.rreedd.rreeddarduino01.MainActivity"
android:label="@string/app_name"
android:screenOrientation="portrait" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
String.xml
<resources>
<string name="app_name">Arduino-Android</string>
<string name="DesactivarBluetooth">Desactivar el Bluetooth</string>
<string name="ActivarBluetooth">Activar el Bluetooth</string>
<string name="sinConexion">No Conectado</string>
<string name="title_activity_main2">Main2Activity</string>
</resources>
Esquemático
(http://fotos.subefotos.com/6c7d230bc4b4caa07a6556480d389cfeo.png)
Terminado
(http://fotos.subefotos.com/639126160ecced4d75a001e272e5f913o.gif)
(http://fotos.subefotos.com/63df2a7ae5fac524bf9af782b0968a42o.gif)
Descargar Versión PDF
https://mega.nz/#!rkdU1LbD!wUKSzni5JOpvWMogNZgxE_I-uWDqWk8_96-n9Vulf0E (https://mega.nz/#!rkdU1LbD!wUKSzni5JOpvWMogNZgxE_I-uWDqWk8_96-n9Vulf0E)
Enlace al proyecto
https://mega.nz/#F!H8cCRSpC!yKQMMlQDnMd1znnW6xpgfw!n1VWjCJK
Cualquier consulta por favor coméntala
Saludos desde Chile
Hasta el momento todos tus proyectos me han parecido geniales, solo para decirte que sigas asi!, +Coin! C: