Monday 1 December 2014

Android-Arduino Controlled Eight-Relay Board

 via Blue Tooth Part III

  Android Java Code


The corresponding Arduino code is in the previous post: [http://gampageek.blogspot.co.uk/2014/11/android-arduino-controlled-eight-relay.html]

 Also Arduino help can be found here: http://forum.arduino.cc/ 

and here is my membership at forum.arduino.cc:  http://forum.arduino.cc/index.php?action=profile;u=48270

Programming esp. JAVA, ANDROID help here: http://stackoverflow.com/

    Facebook:  Craig Turner

JAVA
Start code:---------------------------------------------------------------
 package biz.consett.btrelayboard;

/**
 * Buttons to control an mulitple-item-interface over Blue-tooth
 * eg eight relay board and Arduino

 * BT adapter code from:
 *https://bellcode.wordpress.com/2012/01/02/android-and-arduino-bluetooth-communication/
 *
 * LED grid / relay board / mosfet switch grid
 * ETC
 *
 ***Disclaimer***
 * Please note this code is provided for free and AS IS. There is no support and no guarantee
 * from the Author.
 *****************
 *
 * @author Craig Turner
 *
 * Please use it, modify it, and enjoy it.
 * If you find it useful please link to my website:
 * http://gampageek.blogspot.co.uk, where you can also find
 * the project write up and Arduino code, and other hacks.
 *
 *
 */

import android.os.Bundle;
import android.app.Activity;
import android.content.pm.ActivityInfo;
import android.graphics.Point;

import android.view.Display;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;

import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.ToggleButton;


import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;

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

import android.widget.LinearLayout.LayoutParams;

public class BTRelayBoard extends Activity implements OnClickListener
{
    int relayID = 0;
  
    // dimensions of grid
    final static int Xsize = 4; // grid is 4
    final static int Ysize = 2;// x 2 = 12 for eight-relay
    // board [1-8], plus all on [#] all off [0] and a spare [=]

    static int buttonID = 0;
    static int relayList[] = new int[Xsize * Ysize];

    static final Button ButtonArray[][] = new Button[Xsize][Ysize];

    TableRow rowArray[] = new TableRow[Ysize];
    TableRow rowBlueTooth;
    TableLayout RelayTableLayout;
    TextView textDebug1;
    TextView textBT;

  
    static ToggleButton BTconnectButton = null;
  
    // BlueTooth
    BluetoothAdapter bluetoothAdapter;
    BluetoothSocket socket;
    BluetoothDevice myDevice;
    OutputStream outputStream;
  
  
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        // setContentView(R.layout.activity_main);
      
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); // fix orientation to portrait
      
// get screen size to calc width of buttons
        Display display = getWindowManager().getDefaultDisplay();
        Point size = new Point();
      
        display.getSize(size);
        int screenWidth = size.x;
        //int screenHeight = size.y;//not used
//---------------------------------------------------------------------
  
//layouts*************************************************
        // Table
      
        RelayTableLayout = new TableLayout(this);
      
        TableLayout.LayoutParams myParams = new TableLayout.LayoutParams(
                LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);

        RelayTableLayout.setLayoutParams(myParams);

      
        TableLayout.LayoutParams rowLayout = new TableLayout.LayoutParams(
                LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
      
    // debug1 text view  
        textDebug1 = new TextView(this);
        textDebug1.setLayoutParams(rowLayout);      
        textDebug1.setTextColor(AColor.YELLOW);
        textDebug1.setText("Debug1: " + "null");
      
    // BT connection edit text  
        textBT = new TextView(this);      
        textBT.setTextColor(AColor.WHITE);
        textBT.setTextSize(12);
        textBT.setHint("BT Waiting");
      
    // Color Row  

        rowBlueTooth = new TableRow(this);
        rowBlueTooth.setLayoutParams(rowLayout);
      
  
      
//**************************************************************************      

        // Create an array of buttons, Create row views and add buttons to
        // views

        for (int y = 0; y < Ysize; y++)
        {
            rowArray[y] = new TableRow(this);
            rowArray[y].setLayoutParams(rowLayout);

        }

        for ( int x = 0; x < Xsize; x++)
        {

            for (int y = 0; y < Ysize; y++)
            {
                ButtonArray[x][y] = new Button(this);
                ButtonArray[x][y].setOnClickListener(this);
              
                ButtonArray[x][y].setWidth(screenWidth / Xsize); //scale button width
                ButtonArray[x][y].setPadding(0, 0, 0, 0);
                ButtonArray[x][y].setHeight(screenWidth / Xsize); // scale button height to width
                //ButtonArray[x][y].setHeight(((screenHeight / Ysize)/ 1) - 100); // scale button height alternative
              
                ButtonArray[x][y].setTextSize(10);
                          
            }

        }
// array rows
        int n = 0;
        for (int y = 0; y < Ysize; y++)
        {
            //columns
            for (int x = 0; x < Xsize; x++)
            {

                rowArray[y].setBackgroundColor(AColor.BLACK);

                rowArray[y].addView(ButtonArray[x][y]);
              
              

                String relayNum = ("[ " + (n+1) + " ]");

                ButtonArray[x][y].setTextSize(16);
              
                ButtonArray[x][y].setTextColor(AColor.PURPLE);
                ButtonArray[x][y].setBackgroundColor(AColor.GREEN);
              
                if (n == 12)
                {
                    ButtonArray[0][2].setText(("OFF"));
                    ButtonArray[1][2].setText(("ON"));
                    ButtonArray[2][2].setText((" "));
                    ButtonArray[3][2].setText((" "));
                }
                else
                {
                    ButtonArray[x][y].setText(relayNum);
                    }
              
              
                ButtonArray[x][y].setId(relayID);
                relayID = relayID + 1;
                n = n + 1; // label for relay button

            }

            RelayTableLayout.addView(rowArray[y]);

        }

      
      
        RelayTableLayout.addView(textDebug1);
      
        RelayTableLayout.setBackgroundColor(AColor.BLACK);

      
      
        // add a toggle button to open and close the BT connection
      
        BTconnectButton = new ToggleButton(this);
        BTconnectButton.setText("BT Connect");
        BTconnectButton.setWidth(screenWidth / Xsize);
        BTconnectButton.setHeight(50);
        BTconnectButton.setTextSize(11);
        BTconnectButton.setPadding(0, 0, 0, 0);
      
        BTconnectButton.setTextOff("BT Connect");
        BTconnectButton.setTextOn("BT Disconnect");
        BTconnectButton.setTextColor(AColor.WHITE);
      
      
      
    // toggle button actions   
        BTconnectButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked)
                {
                    findBT("linvor");//myBTstring // change for yours
                  
                } else
              
                {
                    textBT.setText("BT Waiting" );
                  
                }
            }
        });
      
        rowBlueTooth.addView(textBT);
        rowBlueTooth.addView(BTconnectButton);
      
      
//add the rows to the Table      
        RelayTableLayout.addView(rowBlueTooth);
      
// set content view - Make the view visible on-screen
                setContentView(RelayTableLayout);  
      
    }

  
  
  
    // add onClick function to button array view
    public void onClick(View view)

    {
        view.setBackgroundColor(AColor.RED); // change color to red when Relay clicked ON
      
      
      
        buttonID = view.getId();
      
      

        relayList[buttonID] =  0xFFff000; //

        textDebug1.setText("Debug1: " + Integer.toString(buttonID) + " = " + Integer.toHexString(relayList[buttonID])); // for
                                                                                                                            // debug

        // so now we can send ButtonID and it's color over BT to arduino */

    }// end of add onClick function to button array view

    @Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }

  
    //look for a bluetooth adapter
    void findBT(String myBTstring)
    {
        bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (bluetoothAdapter == null)
        {
            textBT.setText("No BT available");
        }
      
        if (!bluetoothAdapter.isEnabled())
        {
            Intent enableBluetooth = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBluetooth, 0);
        }

        Set<BluetoothDevice> pairedDevices = bluetoothAdapter.getBondedDevices();
        if (pairedDevices.size() > 0)
        {
            for (BluetoothDevice device : pairedDevices)
            {
                if (device.getName().equals(myBTstring))//
                {
                    myDevice = device;
                    textBT.setText("Looking for: " + myBTstring);
                  
                    break;
                }
            }
        }
      
        else
        {
            textBT.setText("BT Error"); // probably no BT adapter or a paired device
        }
        
    }
  
//end of look for a bluetooth adapter

void openBT() throws IOException
{
    UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb"); // Standard
                                                                            // SerialPortService
                                                                            // ID
    if (myDevice != null) // only open a device if device set by string
                            // input from user
    {// as in findBT() method
        socket = myDevice.createRfcommSocketToServiceRecord(uuid);
        socket.connect();
        outputStream = socket.getOutputStream();

        textBT.setText("BT Connected");
      
    }
  
    else
    {
        textBT.setText("BT Error");
      
    }
}


// send data over BT
void sendData() throws IOException
{
    try
    {
        relayID = buttonID + 1 ; // buttons are 0-7, relays are 1-8
        relayID = buttonID;
      
        String message = Integer.toString(relayID);
  
    message += "\n";
    outputStream.write(message.getBytes());
    textDebug1.setText("Data Sent: " + message);
}
catch (Exception e)
{
    textDebug1.setText("No Data Sent");
}
}//end of send data over BT

void closeBT() throws IOException
{

    outputStream.close();
    socket.close();
    textBT.setText("BT closed");
     }// end of close BT

}// end of class
XML
Manifest --------------------------------------------------------------------
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="biz.consett.btrelayboard"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="13"
        android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.BLUETOOTH" />
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="biz.consett.btrelayboard.BTRelayBoard"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

end code:----------------------------------------------------------------------------------------