segunda-feira, 7 de novembro de 2016

Linux + Bluetooth + Arduino + Mobile



 What you think? Is a very easily project made by myseft and others ClassMates.
The purpose of the code is only made a simple Mobile application that use Bluetooth connection to send and receive command to Arduino.


Remember the Arduino is the Mother Boad and not the Micro Controller.

Use this kind of project only to made prototypes and not professional projects.

Just for fun, to teach my kids to power on/off leds using Arduino ( 7 years old)

 
 
$sudo -i 
$cd /home/lpk/Android/Sdk/platform-tools$./adb kill-server$./adb start-server

$/home/lpk/Downloads/arduino-1.6.12/arduino
 
$~/android-studio/bin$ ./studio.sh 
 
-----------------------AndroidManifest.xml--------------- 
 
xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk
/res/android"    package="com.iot.lpk.projetoiot">
    <uses-permission  
            android:name="android.permission.BLUETOOTH" />
    <uses-permission  
            android:name="android.permission.BLUETOOTH_ADMIN" />

    <application

        android:allowBackup="true"

        android:icon="@mipmap/ic_launcher"

        android:label="@string/app_name"

        android:supportsRtl="true"

        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"
                        />

                <category android:name="android.intent.category.LAUNCHER"
                        />
            </intent-filter>
        </activity>
    </application>

</manifest>

 
---------------activity_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:id="@+id/activity_main"

    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.iot.lpk.projetoiot.MainActivity">
    <TextView

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:text="Iniciando..."

        android:id="@+id/lblTexto" />


    <TextView        android:text="Lampada 1"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:id="@+id/txtLamp01"

        android:layout_below="@+id/textView"

        android:layout_alignParentLeft="true"

        android:layout_alignParentStart="true"

        android:layout_marginTop="29dp" />
    <SeekBar        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:id="@+id/bar1"

        android:layout_below="@+id/txtLamp01"

        android:layout_alignParentLeft="true"

        android:layout_alignParentStart="true"

        android:layout_marginTop="20dp"

        android:layout_alignRight="@+id/textView9"

        android:layout_alignEnd="@+id/textView9"
 />

    <TextView        android:text="Lampada 2"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:layout_below="@+id/bar1"

        android:layout_alignParentLeft="true"

        android:layout_alignParentStart="true"

        android:layout_marginTop="21dp"

        android:id="@+id/textView4"
 />
    <SeekBar        android:layout_width="wrap_content"

        android:layout_height="wrap_content"
        android:id="@+id/bar2"

        android:layout_below="@+id/textView4"

        android:layout_alignParentLeft="true"

        android:layout_alignParentStart="true"

        android:layout_marginTop="13dp"

        android:layout_alignRight="@+id/bar1"

        android:layout_alignEnd="@+id/bar1" />
    <TextView        android:text="Lampada 3"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:layout_below="@+id/bar2"

        android:layout_alignParentLeft="true"

        android:layout_alignParentStart="true"

        android:layout_marginTop="11dp"

        android:id="@+id/textView6" />
    <SeekBar        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:layout_below="@+id/textView6"

        android:layout_alignParentLeft="true"

        android:layout_alignParentStart="true"

        android:layout_marginTop="18dp"

        android:id="@+id/bar3"        android:layout_alignRight="@+id/bar2"

        android:layout_alignEnd="@+id/bar2" />
    <Button        android:text="OK"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content" 
 android:id="@+id/btnOK"

        android:layout_alignParentBottom="true" 
 android:layout_alignParentRight="true" 
 android:layout_alignParentEnd="true" 
 android:layout_marginRight="17dp" 
 android:layout_marginEnd="17dp" />

    <TextView        android:text="Temperatura" 
 android:layout_width="wrap_content" 
 android:layout_height="wrap_content" 
 android:layout_centerVertical="true" 
 android:layout_alignRight="@+id/textView" 
 android:layout_alignEnd="@+id/textView" 
 android:id="@+id/textView7" />

    <TextView        android:text="30" 
 android:layout_width="wrap_content" 
 android:layout_height="wrap_content" 
 android:layout_below="@+id/textView7" 
 android:layout_alignParentLeft="true" 
 android:layout_alignParentStart="true" 
 android:layout_marginTop="18dp" 
 android:id="@+id/txtTemperatura" 
 tools:textSize="30sp" />

    <TextView 
 android:text="Sensor de Luminosidade" 
 android:layout_width="wrap_content" 
 android:layout_height="wrap_content" 
 android:id="@+id/textView9" 
 android:layout_below="@+id/txtTemperatura" 
 android:layout_alignParentLeft="true" 
 android:layout_alignParentStart="true"         
android:layout_marginTop="11dp" />
    <ProgressBar         
style="?android:attr/progressBarStyleHorizontal" 
 android:layout_width="wrap_content" 
 android:layout_height="wrap_content" 
 android:layout_below="@+id/textView9" 
 android:layout_alignParentLeft="true" 
 android:layout_alignParentStart="true" 
 android:layout_marginTop="12dp" 
 android:id="@+id/progressBar1" 
 android:layout_alignParentRight="true" 
 android:layout_alignParentEnd="true" />
</RelativeLayout>
 


--------------------MainActivity.java------------------- 
package com.iot.lpk.projetoiot;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity implements SeekBar.OnSeekBarChangeListener{

    private TextView lblTexto, txtTemperatura;
    private Button btnOK;
    private SeekBar bar1, bar2, bar3;
    private ProgressBar progress;
    private BluetoothConnection bluetoothConnection;

    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        bar1 = (SeekBar) findViewById(R.id.bar1);
        bar2 = (SeekBar) findViewById(R.id.bar2);
        bar3 = (SeekBar) findViewById(R.id.bar3);
        progress = (ProgressBar) findViewById(R.id.progressBar1);

        bar1.setMax(255);
        bar2.setMax(255);
        bar3.setMax(255);
        progress.setMax(1023);

        bar1.setOnSeekBarChangeListener(this);
        bar2.setOnSeekBarChangeListener(this);
        bar3.setOnSeekBarChangeListener(this);

        //1:255
        bluetoothConnection = new BluetoothConnection(this, new BluetoothConnection.BluetoothConnectionListener() {
            @Override            public void onConnect() {

                Toast.makeText(getApplicationContext(),"Conectado " , Toast.LENGTH_SHORT).show();
            }

            @Override            public void onMessageReceive(String message) {
                Toast.makeText(getApplicationContext(),"onMessageReceive " + message, Toast.LENGTH_SHORT).show();

                if(message.contains("ldr:")){
                    int luminosidade = Integer.parseInt(message.replace("ldr:",""));
                    progress.setProgress(luminosidade);
                }
               else if(message.contains("temp:")){
                    int temp = Integer.parseInt(message.replace("temp:",""));
                    txtTemperatura.setText("" + temp);
                }
            }

            @Override            public void onConnectionError() {
                Toast.makeText(getApplicationContext(),"Error " , Toast.LENGTH_SHORT).show();
            }

            @Override            public void onPermissionError() {
                Toast.makeText(getApplicationContext(),"onPermissionError " , Toast.LENGTH_SHORT).show();
            }

            @Override            public void onAdapterDisable() {
                Toast.makeText(getApplicationContext(),"onAdapterDisable " , Toast.LENGTH_SHORT).show();
            }
        });



        txtTemperatura = (TextView) findViewById(R.id.txtTemperatura);

        lblTexto = (TextView) findViewById(R.id.lblTexto);

        btnOK = (Button) findViewById(R.id.btnOK);

        btnOK.setOnClickListener(new View.OnClickListener() {
            @Override            public void onClick(View view) {
                lblTexto.setText("Oficina de Prototipacao de Iot");
                bluetoothConnection.connect();

               //BluetoothConnection.            }
        });


    }

    @Override    public void onProgressChanged(SeekBar seekBar, int i, boolean b) {

        //progress.setProgress();
        if(seekBar.getId() == R.id.bar1) {

            txtTemperatura.setText("Lam1 " + i);
            progress.setProgress(i);
            bluetoothConnection.sendData("1:" + seekBar.getProgress());
            //BluetoothConnection
        }
        else if(seekBar.getId() == R.id.bar2) {
            txtTemperatura.setText("Lam2" + i);
            progress.setProgress(i);
            bluetoothConnection.sendData("2:" + seekBar.getProgress());
        }
        else if(seekBar.getId() == R.id.bar3) {
            txtTemperatura.setText("Lam3" + i);
            progress.setProgress(i);
            bluetoothConnection.sendData("3:" + seekBar.getProgress());
        }

    }

    @Override    public void onStartTrackingTouch(SeekBar seekBar) {

    }

    @Override    public void onStopTrackingTouch(SeekBar seekBar) {
        if(seekBar.getId() == R.id.bar1) {
           int value = seekBar.getProgress();
          Toast.makeText(getApplicationContext(),"Lampada 1 Valor " + value, Toast.LENGTH_SHORT).show();
        }
        else if(seekBar.getId() == R.id.bar2) {
            int value = seekBar.getProgress();
            Toast.makeText(getApplicationContext(),"Lampada 2 Valor " + value, Toast.LENGTH_SHORT).show();
        }
        else if(seekBar.getId() == R.id.bar3) {
            int value = seekBar.getProgress();
            Toast.makeText(getApplicationContext(),"Lampada 3 Valor " + value, Toast.LENGTH_SHORT).show();
        }

    }
}

----------------------BluetoohConnection.java--------------
package com.iot.lpk.projetoiot;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.telephony.TelephonyManager;
import android.widget.ArrayAdapter;
import android.widget.ProgressBar;

import java.io.InputStream;
import java.io.OutputStream;
import java.util.Set;
import java.util.UUID;

/** * Created by diegopnavarro on 27/10/16. */
public class BluetoothConnection {


    /*     * Interface de Comunicação     * */
    public interface BluetoothConnectionListener{
        void onConnect();
        void onMessageReceive(String message);
        void onConnectionError();
        void onPermissionError();
        void onAdapterDisable();
    }

    public final static int requestBluetoothPermission = 1000;


    private final static int errorConnection = 1001;
    private final static int successConnection = 1002;
    private final static int sendMessage = 1003;

    private BluetoothConnectionListener listener;
    private Activity context;

    private BluetoothAdapter mBluetoothAdapter;
    private BluetoothSocket socket;
    private OutputStream outputStream;
    private InputStream inputStream;


    private boolean connected;
    private ConnectionDevice connectionDevice;
    private ProgressDialog progressDialog;

    private String receivedMessage;



    /*    *  Handler de sincronia    * */
    private Handler handler = new Handler(Looper.getMainLooper()){

        @Override        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            if(progressDialog != null){
                progressDialog.dismiss();
            }

            switch (msg.what){

                case errorConnection:
                    listener.onConnectionError();
                    break;

                case successConnection:
                    listener.onConnect();
                    break;

                case sendMessage:
                    listener.onMessageReceive((String) msg.obj);
                    break;

            }

        }
    };

    private static final UUID mUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");

    public BluetoothConnection(Activity context, BluetoothConnectionListener listener){

        this.context = context;
        this.listener = listener;

    }


    public void connect(){

        /*        *  Listener Nulo, realiza o retorno do método        * */
        if(listener == null){

            return;
        }


        /*        *  Verifica a permissão do bluetooth        * */
        if (ContextCompat.checkSelfPermission(context,
                Manifest.permission.BLUETOOTH)
                != PackageManager.PERMISSION_GRANTED) {

            ActivityCompat.requestPermissions(context,
                    new String[]{Manifest.permission.BLUETOOTH, Manifest.permission.BLUETOOTH_ADMIN},
                    requestBluetoothPermission);

            listener.onPermissionError();

            return;
        }


        /*        * Verifica se o adaptador Bluetooth está ativo        * */
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

        if(mBluetoothAdapter == null || !mBluetoothAdapter.isEnabled()){

            listener.onAdapterDisable();;

            return;

        }



        /*        * Identifica todos os devices pareados        * */
        Set devices = mBluetoothAdapter.getBondedDevices();

        final ArrayAdapter arrayAdapter = new ArrayAdapter(
                context,android.R.layout.select_dialog_item);

        for(BluetoothDevice device : devices) {
            arrayAdapter.add(device.getName() + "\n" + device.getAddress());
        }

        AlertDialog.Builder builderDialog = new AlertDialog.Builder(context);
        builderDialog.setTitle("Selecione o dispositivo para conectar");
        builderDialog.setCancelable(false);
        builderDialog.setAdapter(arrayAdapter, new DialogInterface.OnClickListener() {
            @Override            public void onClick(DialogInterface dialog, int which) {
                connectWithDevice((BluetoothDevice) mBluetoothAdapter.getBondedDevices().toArray()[which]);
                dialog.dismiss();
            }
        });

        builderDialog.create().show();
    }


    private void connectWithDevice(BluetoothDevice device){
        progressDialog = ProgressDialog.show(context,"IoT","Fazendo a conexão com o dispositivo " + device.getName());
        connectionDevice = new ConnectionDevice(device);
        connectionDevice.start();
    }


    private class ConnectionDevice extends Thread{

        private BluetoothDevice device;

        public ConnectionDevice(BluetoothDevice device){
            this.device = device;
        }


        @Override        public void run() {
            super.run();

            receivedMessage = "";

            try {
                socket = device.createRfcommSocketToServiceRecord(mUUID);
                socket.connect();
                handler.sendEmptyMessage(successConnection);
                connected = true;

                outputStream = socket.getOutputStream();
                inputStream = socket.getInputStream();

                while (connected){


                    int availableData = inputStream.available();

                    if(availableData > 0){
                        byte[] availableBytes = new byte[availableData];
                        inputStream.read(availableBytes);

                        String message = new String(availableBytes);
                        receivedMessage = receivedMessage + message;

                        if(receivedMessage.contains("\n")){

                            String[] messageItems = receivedMessage.split("\n");

                            String lastItem = messageItems[messageItems.length - 1];
                            int offSet = 1;

                            receivedMessage = lastItem;

                            if(lastItem.contains("\r")){
                                offSet = 0;
                                receivedMessage = "";
                            }

                            for(int count = 0 ; count < messageItems.length - offSet ; count++){
                                Message msg = new Message();
                                msg.what = sendMessage;
                                msg.obj = messageItems[count].trim();
                                handler.sendMessage(msg);
                            }
                        }
                    }
                }

            }catch (Exception e){
                connected = false;
                handler.sendEmptyMessage(errorConnection);
            }
        }
    }



    /*    *  Envio de informação    * */

    public boolean sendData(String message){

        try{
            message = message + "\n";
            outputStream.write(message.getBytes());
            return true;
        }
        catch (Exception e){
            connected = false;
            handler.sendEmptyMessage(errorConnection);
            return false;
        }
    }



    /*    *    * Desconectar    * */
    public void disconnect(){
        connected = false;
    }


}
-----------------------Sensores--------
/*
  Fabio Leandro Lapuinka
*/

int valor = 0;


int ledPin1 = 6;     //pulso - maior
int ledPingGrid1 = 7;

int ledPin2 = 5;    //pulso - maior
int ledPingGrid2 = 4;

int ledPin3 = 3;   //pulso - maior
int ledPingGrid3 = 2;

//int ledPin =

int sensorValue = 0;
int tmp = A0;
int ledValorLum = 0;
int ldr = A0;
int ledTemp = A1;
int iteracao = 0;

// the setup function runs once when you press reset or power the board
void setup() {
  // initialize digital pin LED_BUILTIN as an output.


  pinMode(ldr , INPUT);
  pinMode(ledTemp , INPUT);

  pinMode(ledPin1, OUTPUT);
  pinMode(ledPingGrid1, OUTPUT);



  pinMode(ledPin2, OUTPUT);
  pinMode(ledPingGrid2, OUTPUT);
 


  pinMode(ledPin3, OUTPUT);
  pinMode(ledPingGrid3, OUTPUT);


  //nao posso por causa do RX TX Serial.begin(9600);

  digitalWrite(ledPingGrid1, LOW);
  digitalWrite(ledPingGrid2, LOW);
  digitalWrite(ledPingGrid3, LOW);

  Serial.begin(9600);
}

void checkLed(int led, int valor) {

  switch (led) {

    case 1:
      analogWrite(ledPin1, valor);
      break;
    case 2:
      analogWrite(ledPin2, valor);
      break;
    case 3:
      analogWrite(ledPin3, valor);
      break;
    default:
      break;
  }
}

void serialEvent() {
  //1:200\n
  int led = Serial.readStringUntil(':').toInt();
  int valor = Serial.readStringUntil('\n').toInt();
  valor = map(valor , 0, 255, 1, 100 );

  checkLed(led, valor);
}



// the loop function runs over and over again forever
void loop() {

  iteracao++;

  if (iteracao == 100) {
    int valorLdr = analogRead(ldr);
    int valorTemp = analogRead(ledTemp);
    valorTemp = (valorTemp * 500) / 1023;
    Serial.print("ldr:");
    Serial.println(valorLdr);
    Serial.print("temp:");
    Serial.println(valorTemp);
    iteracao = 0;
  }


  //int valTmp = analogRead(tmp);
  //int val = map(sensorValue , 0, 1023, 1, 100 ); //Map area analog ara nao dar 255

  //digitalWrite(ledPingGrid, LOW);
  //analogWrite(ledPin, val);



  //Serial.print(valTmp);
  //analogWrite
  delay(10);                       // wait for a second
}


Postar um comentário