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