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:----------------------------------------------------------------------------------------

Saturday 29 November 2014

Android-Arduino Controlled Eight-Relay Board

via Blue Tooth  Part II

  Arduino Code



Here is the Arduino Blue-tooth code to control the eight-relay board. The Android Java code is in the next post. You can control the relays using a smart-phone or tablet. In the meantime you can look at this post to see a basic Android Java Bluetooth project [http://gampageek.blogspot.co.uk/2013/12/set-paireddevices-mbluetoothadapter.html]

 ARDUINO
Start code:---------------------------------------------------------------------------------
 /* Blue tooth transceiver to trigger relays according to commands recieved CT 29/11/2014

// Sketch is provided "As is" with no guarantees, or support from the Author.
// Help with Arduino and shields can be found by joining the forum on the Arduino website: http://arduino.cc/en/

*/

// Includes here
#include <SoftwareSerial.h>

char sendReady = 'r'; // ready to send to Android

int bluetoothTx = 2;
int bluetoothRx = 3;

SoftwareSerial bluetooth(bluetoothTx, bluetoothRx);
const int LED = 10;
char incomingByte = ' ';


const int relay [8] = {
  3, 4, 5, 6, 7, 8, 9, 14};// relay digital control pins 3 to 9 and 14 (A0)
// ie relays 1 to 8. relay 8 = pin14 / A0 is firing power

const int alarm = 15;// alarm pin buzz 15 (A1)
const int powerLED = 16; //RED power led pin 16 (A2)
const int alarmGrnd = 17;// alarm pin buzz grnd 17 (A3)


byte command = ' ';//byte to hold a command char


word counter;           // incremented each second


boolean fired = false;

void setup ()
{
 
   //Setup  serial connection to computer
  Serial.begin(9600);
  pinMode(LED, OUTPUT);
 
  //Setup Bluetooth serial connection to android
  bluetooth.begin(115200);
  bluetooth.print("$$$");
  delay(100);
  bluetooth.println("U,9600,N");
  bluetooth.begin(9600);
  Serial.println("Start");
 

  Serial.print("");//debug

  // alarms and notifications
  pinMode(alarm, OUTPUT);   
  pinMode(powerLED, OUTPUT);
  pinMode(alarmGrnd, OUTPUT);
 
  digitalWrite(alarmGrnd, LOW);// sink buzzer current

  // buzz 2 sec on power up
    buzz(2);
 
  // show power ON
  digitalWrite(powerLED, HIGH);//powerLED (red) on

  //setup relay control pins

  for (int i = 0; i < 8; i++)
  {
    pinMode(relay[i], OUTPUT); // set as outputs relay wired Normally Open (no circuit)
    digitalWrite(relay[i], HIGH);// set high = off (low triggers relay to close = make circuit)
  }
 
 // relay 8 = Firing-power set to ON
 
    digitalWrite(int(relay[7]), LOW); //relay [7](array) => pin 14 => relay-board_8
 
  //BT send ready signal

  //Serial.print(sendNull);// debug
 
  bluetooth.print(sendReady);// ready signal send to Android
  bluetooth.print('#');// delimiter
Serial.println();

 
//  delay (50000);// debug

}

void loop ()
{
  //start of BT code==================================
 
  // recieve code
 
  //Read from bluetooth
  if(bluetooth.available())
  {
    Serial.println("BlueTooth OK");// debug
    char toSend = (char)bluetooth.read();
    Serial.println(toSend);
    incomingByte = toSend;
    command = toSend;
  }
  //end of  of BT code==================================
 

 
  switch  (command) // start of SWITCH CASE ****************************************
  {
 
  case '*': // buzz warning
  buzz(2);
 
  break;
  
  case '1' : // relay 1
    
 
    digitalWrite(int(relay[0]), LOW); //relay [0](array) => pin 3 => relay-board_1 
  
    //Serial.println("Relay: ");// debug

    //Serial.print(int(relay[i]));//debug
    //Serial.print(" Triggered ");//debug
    //Serial.println();//debug
  
    break;

  case '2': // relay 2
 
  
    digitalWrite(int(relay[1]), LOW); //relay [1](array) => pin 4 => relay-board_2 
     
 
    break;

  case '3': // relay 3
 
 
 
    digitalWrite(int(relay[2]), LOW); //relay [2](array) => pin 5 => relay-board_3 
 
  
    break;   

  case '4': // relay 4
 
  
    digitalWrite(int(relay[3]), LOW); //relay [3](array) => pin 6 => relay-board_4
     
     
    break;

  case '5': // relay 5
 
  
    digitalWrite(int(relay[4]), LOW); //relay [4](array) => pin 7 => relay-board_5
      
  
    break;

  case '6': // relay 6
 
 
    digitalWrite(int(relay[5]), LOW); //relay [5](array) => pin 8 => relay-board_6
   
   
    break;

  case '7': // relay 7
 
 
    digitalWrite(int(relay[6]), LOW); //relay [6](array) => pin 9 => relay-board_7
   
  
    break;

 

  case '#': // Trigger all relays together
 
  
    
    for (int i = 0; i < 7; i++)
    {  
    digitalWrite(relay[i], LOW);// set all LOW = ALL ON (low triggers relay to close circuit)
    }
  
  
    break;

  default:// all OFF default HIGH all open (no circuit) eg 'X'
    for (int i = 0; i < 7; i++)
    {  
      digitalWrite(relay[i], HIGH);// set high = off (low triggers relay to close)
    }
 
  
    break;
  
  }// end of switch case********************************************************************

 

}// end of loop

void buzz(int multi){// buzz multi x 1 sec

  digitalWrite(alarm, HIGH);//buzz
 
    for (int i = 1; i < (multi * 50); i++) // wait
    {
      delayMicroseconds(10000);   // multi x 100 x 10000 us
    }
  digitalWrite(alarm, LOW);//buzz off
}

void delaySeconds (int multi){// delay multi x 1 sec

    for (int i = 1; i < (multi * 100); i++) // wait
    {
      delayMicroseconds(10000);   // multi x 100 x 10000 us
    }
}
 
 

End code:---------------------------------------------------------------------------------

Android-Arduino Controlled Eight-Relay Board

via Blue Tooth  Part I


Eight-Relay Module 
control the relays using a smart-phone or tablet.


Introduction
In an earlier series of posts [http://gampageek.blogspot.co.uk/2012/11/remote-controlled-eight-relay-board_16.html] I described a project to design and build a remote controlled relay board, using Jee-lab's Jee-nodes. In this update I am adapting the design to work with Android and Java via a blue-tooth (BT) link to Arduino. NB some of the information from those posts will be repeated if I think it may help for safety or help makes things clearer.

So I am adapting the remote control device I made earlier to work over BT. It allows me to independently switch eight relays and control various  items. When I use buttons on an Android device, instructions will be transmitted via Blue-tooth. At the other end, Arduino switches the relays ON or OFF.

I used a relay module identical to the one in the picture above. It's an optically isolated 8-relay module. That's nice because it makes controlling it easy with an Arduino.  It's worth while reading this link before starting: 

[http://gampageek.blogspot.co.uk/2012/12/normal-0-false-false-false-en-gb-x-none.html]

BE SAFE

I will not be posting how it is possible to link relays to AC mains devices. I will be using low power DC examples. If you go ahead yourself and try mains stuff, remember I told you it can be very dangerous. Playing with mains power can kill you, and the people around you, not just by electrocution but also by starting a fire. 


I didn't need full isolation, so I kept the Vcc and JD-Vcc pins connected using the jumper on the board. I wouldn't use more than 4 relays working at once in my Firework firing RC device. If you intend to use more than four relays at once, then you need to use a separate power supply for the relay coils. This is because the 5v supply can be damaged by the current needed to operate all at once (8 x 80mA = 640 mA ).

You can use a separate 5v supply for the relays, so long as that supply is capable of more than 640 mA. [NB USB should not exceed 500mA].

If you require a separate power supply for the relays follow: Optically isolated 8-relay module instructions with respect to the JD-Vcc jumper and ground connections.

So, relay board tested and working - time to adapt and update my Arduino code!

also see this link:
http://blog.arduino.cc/2012/05/07/bluetooth-communications-between-arduino-and-android-an-introduction/ 

 

Thursday 27 November 2014

Android Java, Arduino Control

Automatically Generate a Button Array Interface 

without XML



Introduction

Under ordinary circumstances you use XML to create layouts for Android, and do the programming in Java. However, there are circumstances when this isn't convenient - you may need to do it on the fly, or it may be just easier to create layouts in Java. Below is some Java code to do just this, and it shows how easy it really is!

 Tricolour LED grid

I wanted to produce an array of buttons which could be used as an interface to control an Arduino over blue-tooth. Maybe it could be for a grid of LED's or an array of relays/ mosfets / switches etc... For Blue-Tooth see this post: http://gampageek.blogspot.co.uk/2013/12/set-paireddevices-mbluetoothadapter.html

The key class here is TableLayout():


//layouts*************************************************
        // Table
       
        myTableLayout = new TableLayout(this);
       
        TableLayout.LayoutParams myParams = new TableLayout.LayoutParams(
                LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);

        myTableLayout.setLayoutParams(myParams);

       
        TableLayout.LayoutParams rowLayout = new TableLayout.LayoutParams(
                LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);


-------------------------------------------------------------------------------------------------------------------

Full code: 
package biz.consett.ArduinoLEDgrid;

/**
 * Create an array of buttons and chose their colours in Android without using an XML layout
 *
 * Could be used in combination with Bluetooth classes
 * eg [http://gampageek.blogspot.co.uk/2013/12/set-paireddevices-mbluetoothadapter.html]
 * to communicate with Arduino over Blue-tooth to control an LED grid / relay / 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.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.EditText;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.ToggleButton;


import android.widget.LinearLayout.LayoutParams;

public class ButtonGrid extends Activity implements OnClickListener
{
    int LedID = 0;
    int LedColor = AColor.WHITE; //null color
    // dimensions of grid
    final static int Xsize = 8;
    final static int Ysize = 8 ;

    static int ButtonID = 0;
    static int LedList [] = new int [Xsize * Ysize];

    static final Button ButtonArray[][] = new Button[Xsize][Ysize];
   
    TableRow rowArray[] = new TableRow[Ysize];
    TableRow rowColorButtons;
    TableLayout myTableLayout;
    TextView myTextViewDebug1;
    TextView myEditTextBT;
   
   
    static Button BlackButton = null; // 0
    static Button GreenButton = null; // 1
    static Button RedButton = null; // 2
    static Button YellowButton = null;  // 3
   
    static ToggleButton BTconnectButton = null;
   
    static int SelectedColor = 0; // black
   
   
   
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        // setContentView(R.layout.activity_main);
       
// get screen size to calc width of buttons
        Display display = getWindowManager().getDefaultDisplay();
        Point size = new Point();
       
        display.getSize(size);
        int width = size.x;
        int height = size.y;
//---------------------------------------------------------------------
   
//layouts*************************************************
        // Table
       
        myTableLayout = new TableLayout(this);
       
        TableLayout.LayoutParams myParams = new TableLayout.LayoutParams(
                LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);

        myTableLayout.setLayoutParams(myParams);

       
        TableLayout.LayoutParams rowLayout = new TableLayout.LayoutParams(
                LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
       
    // debug1 text view   
        myTextViewDebug1 = new TextView(this);
        myTextViewDebug1.setLayoutParams(rowLayout);       
        myTextViewDebug1.setTextColor(AColor.YELLOW);
        myTextViewDebug1.setText("Debug1: " + "null");
       
    // BT connection edit text   
        myEditTextBT = new EditText(this);       
        myEditTextBT.setTextColor(AColor.WHITE);
        myEditTextBT.setTextSize(10);
        myEditTextBT.setHint("BT Connect");
       
    // Color Row   

        rowColorButtons = new TableRow(this);
        rowColorButtons.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(width / Xsize);
                ButtonArray[x][y].setPadding(0, 0, 0, 0);
                ButtonArray[x][y].setHeight(50);
                ButtonArray[x][y].setTextSize(10);

            }

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

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

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

                String LedCoord = ("(" + String.valueOf(x) + ","
                        + String.valueOf(y) + ")");

                ButtonArray[x][y].setText(String.valueOf(LedCoord));
                ButtonArray[x][y].setTextColor(AColor.PURPLE);
                ButtonArray[x][y].setBackgroundColor(AColor.BLACK);

                ButtonArray[x][y].setId(LedID);
                LedID = LedID + 1;

            }

            myTableLayout.addView(rowArray[y]);

        }

       
       
        myTableLayout.addView(myTextViewDebug1);
       
        myTableLayout.setBackgroundColor(AColor.BLACK);
//color buttons       
        // add a Green Button

        GreenButton = new Button(this);
        GreenButton.setWidth(width / Xsize);
        GreenButton.setHeight(50);
        GreenButton.setTextSize(11);
        GreenButton.setText("Green");
        GreenButton.setBackgroundColor(AColor.GREY);
        ///GreenButton.setOnClickListener(this);

        rowColorButtons.addView(GreenButton);

        // add a Red Button

        RedButton = new Button(this);
        RedButton.setWidth(width / Xsize);
        RedButton.setHeight(50);
        RedButton.setTextSize(11);
        RedButton.setText("Red");
        RedButton.setBackgroundColor(AColor.GREY);
       
        rowColorButtons.addView(RedButton);
       

        // add a Yellow Button

        YellowButton = new Button(this);
        YellowButton.setWidth(width / Xsize);
        YellowButton.setHeight(50);
        YellowButton.setTextSize(11);
        YellowButton.setText("Yellow");
        YellowButton.setBackgroundColor(AColor.GREY);
       
        rowColorButtons.addView(YellowButton);

        // add a Black Button (turn off the colour)

        BlackButton = new Button(this);
        BlackButton.setWidth(width / Xsize);
        BlackButton.setHeight(50);
        BlackButton.setTextSize(11);
       
        BlackButton.setText("Black");
        BlackButton.setTextColor(AColor.WHITE);
        BlackButton.setBackgroundColor(AColor.GREY);       

        rowColorButtons.addView(BlackButton);
       
        // add a toggle button to open and close the BT connection
       
        BTconnectButton = new ToggleButton(this);
        BTconnectButton.setWidth(width / Xsize);
        BTconnectButton.setHeight(50);
        BTconnectButton.setTextSize(11);
        BTconnectButton.setPadding(0, 0, 0, 0);
       
        //BTconnectButton.setText("Connect");
        BTconnectButton.setTextColor(AColor.WHITE);
        //BTconnectButton.setBackgroundColor(AColor.GREY);
       
        rowColorButtons.addView(myEditTextBT);
        rowColorButtons.addView(BTconnectButton);
       
//add the rows to the Table       
        myTableLayout.addView(rowColorButtons);

       
    // action onClick for colour buttons
        BlackButton.setOnClickListener(new View.OnClickListener()
                {
                    public void onClick(View v)
                    {
                        try
                        {
                            BlackButton.setBackgroundColor(AColor.BLACK);
                            SelectedColor = 0; // black
                           
                            RedButton.setBackgroundColor(AColor.GREY);
                            YellowButton.setBackgroundColor(AColor.GREY);
                            GreenButton.setBackgroundColor(AColor.GREY);
                           
                        } catch (Exception ex)
                        {
                           
                        }
                    }
                });
       
        RedButton.setOnClickListener(new View.OnClickListener()
        {
            public void onClick(View v)
            {
                try
                {
                    RedButton.setBackgroundColor(AColor.RED);
                    SelectedColor = 2; // red
                   
                    BlackButton.setBackgroundColor(AColor.GREY);
                    YellowButton.setBackgroundColor(AColor.GREY);
                    GreenButton.setBackgroundColor(AColor.GREY);
                } catch (Exception ex)
                {
                   
                   
                }
            }
        });   
       
        YellowButton.setOnClickListener(new View.OnClickListener()
        {
            public void onClick(View v)
            {
                try
                {
                    YellowButton.setBackgroundColor(AColor.YELLOW);
                    SelectedColor = 3; // yellow
                   
                    BlackButton.setBackgroundColor(AColor.GREY);
                    RedButton.setBackgroundColor(AColor.GREY);
                    GreenButton.setBackgroundColor(AColor.GREY);
                } catch (Exception ex)
                {
                   
                   
                }
            }
        });
       
        GreenButton.setOnClickListener(new View.OnClickListener()
        {
            public void onClick(View v)
            {
                try
                {
                    GreenButton.setBackgroundColor(AColor.GREEN);
                    SelectedColor = 1; // green
                   
                    BlackButton.setBackgroundColor(AColor.GREY);
                    YellowButton.setBackgroundColor(AColor.GREY);
                    RedButton.setBackgroundColor(AColor.GREY);
                } catch (Exception ex)
                {
                   
                   
                }
            }
        });
       
    // end of action Onclick for color buttons   
       
       
       
// set content view - Make the view visible on-screen
                setContentView(myTableLayout);
               
               
       
    }

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

    {
        switch (SelectedColor)
        {
        case 0:
            LedColor = AColor.BLACK;    //black
            break;
           
        case 1:
            LedColor = AColor.GREEN;    //green
            break;
        case 2:
            LedColor = AColor.RED;    // red
            break;   
        case 3:
            LedColor = AColor.YELLOW;    // yellow
            break;
           
        default:
            LedColor = AColor.WHITE;    // white
        }
       
        view.setBackgroundColor(LedColor);
        ButtonID = view.getId();
               
        LedList [ButtonID] = LedColor - 0xFF000000; // set color of led] = color; // set color of led
       
        myTextViewDebug1.setText("Debug1: " + Integer.toString(ButtonID) +" = " + Integer.toHexString(LedList[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;
    }

}

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






Wednesday 29 October 2014


  Small Solar Panel (5v)

Arduino Light Sensor

I think this retro-design could be used for a cool visual of a solar array functioning.



 How it works.

The solar panel puts out 5 volts when working well with lots of light. Be aware if the voltage goes above 5v you may damage your Arduino. In that case use a voltage divider. The voltage output (0 to 5v) is measured by the analogue pin on the Arduino. Some code below converts this to a series of pulses on digital pins to light an LED bar.

As light intensity grows (that's me moving the lamp over the panel), the LEDs pulse faster and show that the voltage output from the panel is increasing. If the panel fails, or the light goes out a buzzer sounds or pin 13. You could also use that concept to trigger events if panels are undercharging or overcharging.

I think this retro-design could be used for a cool visual of a solar array functioning. Its reminds me of those old films where the reactor is about to go critical or when they are have to push the power output of warp engines to the limit. In fact, I may add some sound effects code too ! :)

 Code:--------------------------------------------------------
// Initialise Global variables
int startPin = 2; // starting pin don't use 0 or 1 because they are Rx and Tx.
int LEDnum = 12; // highest pin No. 12 -2 = 10 LEDs
int lightPin = A5; //A5 for sensor: 5v max output from the solar panel

// use a 10K resistor as well, in series, to limit the current
int lightLevel = 0;
int myDelay = 0;
int buzzPin = 13; // alarm pin for buzzer

void setup()
{
  pinMode(buzzPin, OUTPUT);

  for (int PINi = startPin; PINi < LEDnum; PINi++)
  {
    pinMode(PINi, OUTPUT);

  }
  Serial.begin(9600);
}

void loop()
{
  lightLevel = analogRead(lightPin); //Read the level


  myDelay = 100 - (lightLevel / 10) ; // set delay according to light level

  Serial.println(myDelay); // debug in terminal window

// if lightlevel is very low ie delay is big, switch off all led and Alarm
  if (myDelay >= 85)
  {
    for (int PINi = startPin; PINi < LEDnum; PINi++)
    {
      digitalWrite(PINi, LOW); 
    }

    digitalWrite(buzzPin, HIGH);
    delay (500);
    digitalWrite(buzzPin, LOW);
    delay (500);
  }
 
// Display charging on LED bar
  else{
    for (int PINi = startPin; PINi < LEDnum; PINi++)
    {
      digitalWrite(PINi, HIGH);
     
      delay(myDelay);
      digitalWrite(PINi, LOW);.
     
    
    }
  }
}

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