ratnaddeepjoshi
Published © LGPL

Phone Call Indicator cum Panic Switch

Bluetooth and Android-based call indicator with panic switch for calling a preset number.

IntermediateShowcase (no instructions)1,358
Phone Call Indicator cum Panic Switch

Things used in this project

Hardware components

HC-05 Bluetooth Module
HC-05 Bluetooth Module
×1
Buzzer Module
×1
Tactile Switch, Top Actuated
Tactile Switch, Top Actuated
×1
5 mm LED: Red
5 mm LED: Red
×1
5 mm LED: Yellow
5 mm LED: Yellow
×1
Resistor 220 ohm
Resistor 220 ohm
×2
ATmega 328 P-PU
×1
Arduino Pro Mini 328 - 5V/16MHz
SparkFun Arduino Pro Mini 328 - 5V/16MHz
×1

Software apps and online services

Arduino IDE
Arduino IDE
Android Studio
Android Studio
Autodesk EAGLE

Story

Read more

Schematics

Basic Sketch

Code

MainActivity.java

Java
This is the main activity for the android app (called myapplication)
package com.ratnadeep.myapplication;

import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;

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


public class MainActivity extends AppCompatActivity {
    Button btnSend, BtnArm, BtnReset;
    ToggleButton tglBtnConnect, tglBtnTest;
    TextView tvStatus, ETReceivedTxt;
    EditText etMsgBox;
    BluetoothAdapter btAdapter;
    BluetoothDevice btDevice;
    public BluetoothSocket socket;
    Set<BluetoothDevice> mPairedDevices;
    OutputStream outputStream;
    InputStream inputStream;
    SendRecieve sendRecieve;
    private final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb");
    private final int MESSAGE_SENT = 10;
    private final int BLUE_TOOTH_OFF = 11;
    private final int MESSAGE_RECEIVED = 12;
    private final int SOCKET_NOT_CONNECTED = 13;
    private final int SOCKET_OPENED = 1;
    public static boolean cont = false;
    int MY_APP_PERMISSION_CALL_PHONE;
    Boolean canCall = false; // cannot call without permissions
    SharedPreferences sharedPreferences ;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        findViewbyIDs();
        RequestPermission();



        if (ContextCompat.checkSelfPermission(MainActivity.this,
                Manifest.permission.READ_PHONE_STATE)!= PackageManager.PERMISSION_GRANTED){
            ActivityCompat.requestPermissions(this,
                    new String[] {Manifest.permission.READ_PHONE_STATE},1);
        }

        tglBtnConnect.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if(isChecked){
                    tvStatus.setText("Connecting...");
                    btAdapter = BluetoothAdapter.getDefaultAdapter();
                    if (btAdapter != null) {
                        Connect myconnect = new Connect();
                        if (cont) {
                            myconnect.start();
                        }
                    } else {
                        Toast.makeText(MainActivity.this, "Check if Bluetooth is on",
                                Toast.LENGTH_SHORT).show();
                        //tglBtnConnect.setChecked(false);
                    }

                }
                else {
                    btAdapter = null;
                    socket = null;
                    cont = false;
                    tvStatus.setText("Remote Device Disconnected");
                    ETReceivedTxt.setText("");
                    BtnArm.setBackgroundResource(android.R.drawable.btn_default);
                }

            }
        });
        tglBtnTest.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if(isChecked){
                    if(cont){
                        sendRecieve.SendMessage("P");
                    }
                    else{
                        tvStatus.setText("Caannot Continue, Check status");
                        tglBtnTest.setChecked(false);

                    }
                }
                else {
                    if(cont) {
                        sendRecieve.SendMessage("R");

                    }
                }
            }
        });





        BtnArm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                TelephonyManager tmgr =
                        (TelephonyManager) MainActivity.this.getSystemService(Context.TELEPHONY_SERVICE);
                if (socket != null) {

                    //Create new Receiver and register it
                    myReceiver myNewReceiver = new myReceiver();
                    IntentFilter filter = new IntentFilter();
                    filter.addAction(TelephonyManager.ACTION_PHONE_STATE_CHANGED);
                    registerReceiver(myNewReceiver,filter);

                    BtnArm.setBackgroundColor(Color.RED);
                } else {
                    Toast.makeText(MainActivity.this, "No Socket",
                            Toast.LENGTH_SHORT).show();
                }
            }
        });

        BtnReset.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String strMsg = "R" + "\n";
                //SendRecieve sendRecieve = new SendRecieve(socket);
                sendRecieve.SendMessage(strMsg);


            }
        });


        sharedPreferences = this.getSharedPreferences(getString(R.string.file_name),MODE_PRIVATE);
    }



    private void findViewbyIDs() {
        tglBtnConnect = (ToggleButton) findViewById(R.id.btnCnnct);
        btnSend = (Button) findViewById(R.id.btnSend);
        tvStatus = (TextView) findViewById(R.id.tvStatus);
       // etMsgBox = (EditText) findViewById(R.id.MsgBox);
        BtnArm = (Button) findViewById(R.id.btnArm);
        tglBtnTest = (ToggleButton)findViewById(R.id.tglTestReset);
        BtnReset = (Button) findViewById(R.id.btnReset);
        ETReceivedTxt = (TextView) findViewById(R.id.etReceivedText);

    }

    private class Connect extends Thread {
        private BluetoothSocket mmSocket;

        public Connect() {
            btAdapter = BluetoothAdapter.getDefaultAdapter();
            if (btAdapter.isEnabled()) {
                btDevice = (BluetoothDevice) (btAdapter.getBondedDevices().toArray())[0];
                btAdapter.getRemoteDevice(String.valueOf(btDevice));
                cont = true;
            } else {
                Message message = Message.obtain();
                message.what = BLUE_TOOTH_OFF;
                handler.sendMessage(message);

            }

        }

        public void run() {
            try {
                mmSocket = btDevice.createInsecureRfcommSocketToServiceRecord(MY_UUID);
                mmSocket.connect();
            } catch (IOException e) {
                cont = false;
                Message message = Message.obtain();
                message.what = SOCKET_NOT_CONNECTED;
                handler.sendMessage(message);
                e.printStackTrace();
            }
            if ((mmSocket != null) && (cont)) {
                Message message = Message.obtain();
                message.what = SOCKET_OPENED;
                handler.sendMessage(message);
                socket = mmSocket;
            }
        }
    }

    public class SendRecieve extends Thread {

        private OutputStream outputStream;
        private InputStream inputStream;
        int inByte;
        byte[] buffer = new byte[512];
        byte[] newBuffer = new byte[1024];
        int bytes, availableBytes;
        String bufferMessage = "";
        char Ascii;

        public SendRecieve(BluetoothSocket mySocket) {
            try {
                outputStream = mySocket.getOutputStream();
                inputStream = mySocket.getInputStream();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }

        public void run() {
            bytes = 0;

            while (true) {
                try {

                    //bytes = inputStream.read(buffer,0,buffer.length);
                    inByte = inputStream.read();
                    if (inByte != -1) Ascii = (char) inByte;
                    if ((inByte != 42) && (inByte != -1)) {
                        bufferMessage += (char) inByte;

                        Log.e("Char REceived", String.valueOf((char) inByte));
                    } else {
                        handler.obtainMessage(MESSAGE_RECEIVED, bufferMessage.length(), -1, bufferMessage).sendToTarget();
                        bufferMessage = "";

                    }

                    //Log.e("REceived Buffer Length",String.valueOf(bytes));

                } catch (IOException e) {
                    e.printStackTrace();
                }

            }


        }

        public void SendMessage(String msg) {
            try {
                outputStream.write(msg.getBytes());
                Message message = Message.obtain();
                message.what = MESSAGE_SENT;
                handler.sendMessage(message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }



    public class myReceiver extends BroadcastReceiver{


        public myReceiver(){


        }

        @Override
        public void onReceive(Context context, Intent intent) {

        try {
            String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
            if (state.equals("RINGING")) {
                Toast.makeText(context, state, Toast.LENGTH_SHORT).show();
                sendRecieve.SendMessage("P" + "\n");
            }
        } catch (Exception e) {
            Log.e("Error", e.toString());
        }
    }



        }




    Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what) {
                case (SOCKET_OPENED):
                    tvStatus.setText("Socket is open");
                    sendRecieve = new SendRecieve(socket);
                    sendRecieve.start();
                    break;
                case (MESSAGE_SENT):
                    Toast.makeText(MainActivity.this, "Message Sent",
                            Toast.LENGTH_SHORT).show();
//                    etMsgBox.setText("");
                    break;
                case (BLUE_TOOTH_OFF):
                    Toast.makeText(MainActivity.this, "No Bluetooth",
                            Toast.LENGTH_SHORT).show();
                    tglBtnConnect.setChecked(false);
                    tvStatus.setText("Bluetooth not connected");
                    break;
                case (MESSAGE_RECEIVED):
                    //byte[] readBuff = (byte[])msg.obj;
                    String readBuff = (String) msg.obj;
                    if (readBuff.equals("Call")) {

                        CallNumber(sharedPreferences.getString("myNumber",""));
                    }
                    if (readBuff.equals("Reset")){
                        tglBtnTest.setChecked(false);
                        tvStatus.setText("Reset from Device");
                    }
                    ETReceivedTxt.setText(readBuff);

                    break;
                case (SOCKET_NOT_CONNECTED):
                    tvStatus.setText("Socket not Connected. Check Remote Device");
                    tglBtnConnect.setChecked(false);


            }
            return false;
        }
    });

    public void CallNumber(String varNumber) {
       //
        // Toast.makeText(this,varNumber,Toast.LENGTH_SHORT).show();

        if (canCall) {
            Intent callIntent = new Intent(Intent.ACTION_CALL);
            callIntent.setData(Uri.parse("tel:"+ varNumber));
            try {
                this.startActivity(callIntent);
            } catch (SecurityException e) {
                Toast.makeText(MainActivity.this,
                       "Check Permissions", Toast.LENGTH_SHORT).show();
            }
            catch (Exception e){
                Log.d ("CallNumber",e.toString());
            }

        }

    }

    public void RequestPermission() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE) !=
                PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.CALL_PHONE},
                    MY_APP_PERMISSION_CALL_PHONE);
        } else { // if permission already exists

            canCall = true;
        }


    }
    @Override
    public boolean onCreateOptionsMenu (Menu menu){

        MenuInflater menuInflater = getMenuInflater();
        menuInflater.inflate(R.menu.main_menu,menu);


        return true;

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem menuItem){
        Intent intent;

        switch(menuItem.getItemId()){

            case(R.id.AddPhone):
                intent = new Intent(this,AddPhone.class);
                startActivity(intent);
                break;
            case(R.id.About):
                intent = new Intent(this,About.class);
                startActivity(intent);
                break;
            case(R.id.CloseApp):
                ///this.finish();
                System.exit(0);
                break;

        }

        return true;
    }
}

App Manifest

XML
This is the manifest file for the application
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.ratnadeep.myapplication">

    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
    <uses-permission android:name="android.permission.BLUETOOTH" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />
    <uses-permission android:name="android.permission.READ_CALL_LOG" />
    <uses-permission android:name="android.permission.CALL_PHONE" />
    <uses-permission android:name="android.permission.READ_PHONE_NUMBERS" />



    <application
        android:allowBackup="true"
        android:icon="@mipmap/rjoshi_ic_launcher1"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/rjoshi_ic_launcher1"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".About"></activity>
        <activity
            android:name=".AddPhone"
            android:label="@string/title_activity_add_phone"
            android:theme="@style/AppTheme.NoActionBar" />
        <activity android:name=".MainActivity"
            android:launchMode="singleTop" android:configChanges="orientation|screenSize">

            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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


    </application>

</manifest>

AddPhone.java

Java
This is an activity called by MainActivity to add a phone number
package com.ratnadeep.myapplication;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class AddPhone extends AppCompatActivity {
    EditText PhoneNo;
    //PreferenceEditor preferenceEditor = new PreferenceEditor(this);
    Button SaveBtn,CancelBtn;
    SharedPreferences sharedPreferences;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_phone);
        PhoneNo = (EditText)findViewById(R.id.etPhoneNo);
        SaveBtn = (Button)findViewById(R.id.btnSave);
        CancelBtn = (Button)findViewById(R.id.btnCancel);
        sharedPreferences = this.getSharedPreferences(getString(R.string.file_name),MODE_PRIVATE);

        PhoneNo.setText(sharedPreferences.getString("myNumber",""));
        SaveBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SharedPreferences.Editor editor = sharedPreferences.edit();
                editor.putString("myNumber",PhoneNo.getText().toString());
                editor.commit();
                finish();
            }
        });
        CancelBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }


}

activity_main.xml

XML
layout for the MainActivity
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/tvStatus"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Not Connected"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <ToggleButton
        android:id="@+id/btnCnnct"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginTop="8dp"
        android:textOff="Connect"
        android:textOn="Disconnect"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/btnSend"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginTop="32dp"
        android:text="Test"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/btnCnnct" />

    <!--<EditText
        android:id="@+id/MsgBox"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginTop="8dp"
        android:ems="10"
        android:inputType="textPersonName"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/btnCnnct" />-->

    <Button
        android:id="@+id/btnArm"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginRight="8dp"
        android:text="Arm"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/btnReset"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginLeft="16dp"
        android:layout_marginTop="32dp"
        android:text="Reset"
        app:layout_constraintStart_toEndOf="@+id/btnSend"
        app:layout_constraintTop_toBottomOf="@+id/btnArm" />

    <TextView
        android:id="@+id/etReceivedText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginRight="8dp"
        android:ems="10"
        android:inputType="textPersonName"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/tvStatus" />

    <ToggleButton
        android:id="@+id/tglTestReset"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginTop="8dp"
        android:textOff="Test"
        android:textOn="Reset"
        app:layout_constraintStart_toEndOf="@+id/btnCnnct"
        app:layout_constraintTop_toTopOf="parent" />

    <!--<ToggleButton
        android:id="@+id/toggleButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="104dp"
        android:layout_marginLeft="104dp"
        android:layout_marginTop="8dp"
        android:text="ToggleButton"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/btnCnnct" />-->

</android.support.constraint.ConstraintLayout>

HC05_04_withBuzzer_OneSwitch.ino

Arduino
Arduino Code for the project
#include <SoftwareSerial.h>
const int RX_PIN = 2;
const int TX_PIN = 3;
const int BuzzerPin = 8;
const int ManualReset = 11;
const int CallPin = 10;
SoftwareSerial mySerial(RX_PIN,TX_PIN);
char CommandChar;
String message;
int Lock;

void setup() {
  // put your setup code here, to run once:

  mySerial.begin(9600);
  Serial.begin(9600);
  pinMode(13,OUTPUT); //Red LED incoming Call
  pinMode(12,OUTPUT); //Yellow LED Normal
  pinMode(BuzzerPin,OUTPUT);
  digitalWrite(BuzzerPin,LOW);
  pinMode(ManualReset,INPUT);
  pinMode(CallPin,INPUT);
  //                                                                            noTone(BuzzerPin);
  Lock = 0;

}

void loop() {
  // put your main code here, to run repeatedly:

if(mySerial.available())
{
 //delay(10);
   CommandChar = (char)mySerial.read();
   if(CommandChar != "\n")
   {
    Serial.print(CommandChar);
    if ((String)CommandChar == "P")
    {
      Lock = 1;
       pinMode(BuzzerPin,OUTPUT);
      digitalWrite(12,LOW);
      digitalWrite(13,HIGH);
      digitalWrite(BuzzerPin,HIGH);
      //Serial.println("Received P");
    }
    if (((String)CommandChar =="R") )
    {
      Lock = 0;
      digitalWrite(13, LOW);
      digitalWrite(12,HIGH);
      digitalWrite(BuzzerPin,LOW);
         }
     if ((String)CommandChar == "C")
     {
      mySerial.print("Call*");
     }
    }
  else
    {
    Serial.println(CommandChar);
     }
}//End of mySerial loop

if ((digitalRead(ManualReset) == 1) && (digitalRead(12)==HIGH))
{
//      Lock = 0;
//      digitalWrite(13, LOW);
//      digitalWrite(12,HIGH);
//      pinMode(BuzzerPin,INPUT);
        mySerial.print("Call*");
        Serial.println("called from box");
}

if ((digitalRead(ManualReset) == 1) && (digitalRead(12)==LOW))
{
      Lock = 0;
      digitalWrite(13, LOW);
      digitalWrite(12,HIGH);
      pinMode(BuzzerPin,INPUT);
        mySerial.print("Reset*");
        Serial.println("Reset from box");
}

if (digitalRead(CallPin) ==1)
{
  mySerial.print("Call*");
}

if (Lock == 1)
  {
    digitalWrite(13,HIGH);
    digitalWrite(BuzzerPin,HIGH);
    delay(300);
    digitalWrite(13,LOW);
    digitalWrite(BuzzerPin,LOW);
   // noTone(BuzzerPin);
    delay(300);
  }
  

if (Lock == 0)
{
  digitalWrite(13,LOW);
  digitalWrite(12,HIGH);
  pinMode(BuzzerPin,INPUT);
}
Serial.println(digitalRead(ManualReset));
mySerial.print("Hello*");
//mySerial.println();

delay(2000);

}

      


 

Credits

ratnaddeepjoshi

ratnaddeepjoshi

0 projects • 0 followers

Comments