Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
9 views

LED Control Using 8051 Micro-Controller and Android Device Interfacing With Bluetooth

This document summarizes an LED control project using an 8051 microcontroller and an Android device interfaced with Bluetooth. It describes developing an Android app with buttons to control LEDs connected to the microcontroller via on, off, blink, and brightness level. It also describes writing an embedded C program for the microcontroller to receive Bluetooth commands from the Android device and control the LEDs accordingly using timers and interrupts. The goal is to allow wireless LED control via an Android app using an 8051 and Bluetooth module.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

LED Control Using 8051 Micro-Controller and Android Device Interfacing With Bluetooth

This document summarizes an LED control project using an 8051 microcontroller and an Android device interfaced with Bluetooth. It describes developing an Android app with buttons to control LEDs connected to the microcontroller via on, off, blink, and brightness level. It also describes writing an embedded C program for the microcontroller to receive Bluetooth commands from the Android device and control the LEDs accordingly using timers and interrupts. The goal is to allow wireless LED control via an Android app using an 8051 and Bluetooth module.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 28

See discussions, stats, and author profiles for this publication at: https://www.researchgate.

net/publication/309034244

LED Control using 8051 Micro-controller And Android Device Interfacing with
Bluetooth

Code · October 2016


DOI: 10.13140/RG.2.2.13803.54561

CITATIONS READS
0 5,504

1 author:

Deepak Kumbhar
Modern College Of Arts, Science & Commerce Ganeshkhind
17 PUBLICATIONS 19 CITATIONS

SEE PROFILE

All content following this page was uploaded by Deepak Kumbhar on 12 October 2016.

The user has requested enhancement of the downloaded file.


8051 Micro-controller And
Android Device Interfacing

Mr. Deepak S. Kumbhar


Future Chip Technologies
Interfacing Android Based Device with 8051 Micro-controllerfor
LED Control Application
Aim: To develop AndroidUser Interfacefor LED Control application using 8051
Microcontroller and Android Device (Tab/Mobile).

Objectives:
1. To develop and write LEDON-OFF,BLINK and LED Brightness control android user
interfaceapplication (Apps) for Tab/Mobile using Java (Eclipse platform & SDK).
2. To develop and write LED ON-OFF,BLINK and LED Brightness Embedded „C‟
program for 8051 microcontroller using Keil IDE.
3. To interface android based device Tab/ Mobile with 8051 Microcontroller using
Bluetooth module (HC-05).

Block Diagram:

Bluetooth
Mobile/ Tab
8051 Module Wireless Data
HC - 05 Communication
Micro -
between Bluetooth
Android
Controller Module & Android Supported
Device Device with
Bluetooth

LED

Page 1 of 27
Requirement:
Keil Software for 8051 Microcontroller Program development can be done on Microsoft
Windows XP or later versions.

Android application development can be done easily on either of the following operating
systems:

 Microsoft Windows XP or later version.


 Linux including GNU C Library 2.7 or later.

Second point is that all the required tools to develop Android applications are freely available
and can be downloaded from the Web. Following is the list of software's you will need before
you start your Android application programming.

 Java JDK5 or JDK6


 Android SDK
 Eclipse IDE for Java Developers (optional)
 Android Development Tools (ADT) Eclipse Plugin (optional)

Procedure: 8051 Microcontroller


1. Write a program for LEDON-OFF,BLINK and LED Brightnessin “Embedded-C”
with the help of Keil IDE.
2. Buildthe program in Keil IDE.
3. Keil IDE creates a LED_Control.hexfile.
4. With the help of ISP programmer or USB Burner download the LED_Control.hex file in
to the IC 89S52 .
5. Then place the IC 89S52 in the target board or kit.

Program:
A. Embedded „C ‟- program to LED control for 8051 Microcontroller.
#include<reg51.h>
sbit LED=P1^0;
char On=1,Blink=0,i=0,Ton=0,t=0;
void delay(unsigned int n)
{
while(--n);
}
/* Bluetooth Module (HC-05) “Tx pin” is connected to port pin P3^0(Rx) of 8051*/
voidreceiveINTR()interrupt 5 // Serial Interrupt
{ char d;
RI=0;

Page 2 of 27
d=SBUF;
if(d==11) // Command to ON LED using Android User Interface.
{ LED=1;
On=1;
Blink=0;
}
if(d==12) // Command to OFF LED using Android User Interface.
{ LED=0;
On=0;
Blink=0;
}
if(d==13) // Command to Blink LED using Android User Interface.
{ Blink=1;
On=1;
}
if(d<11) // Command to Adjust Brightness of LED using Android
User interface.
Ton=d;
}
/* Function to Generate PWM for LED Brightness.*/
void timer0()interrupt 1 // Timer 0 and Interrupt 1
{ TF0=0;
TR0=0;
TH0=0xff;
TL0=50;

i++;
if(i>10)
i=0;

if(On)
{
if(i>Ton)
LED=0;
else
LED=1;
}
TR0=1;
}

Page 3 of 27
/* Main Program for LED Control */

main()
{
TMOD=0x21; // Configure Timer 0 in Mode 1 for LED Brightness.
// Configure Timer 1 in Mode 2 for Serial Comm.
TH1=0xfd; // Configure Timer1 for Serial Comm. Baud Rate 9600.
TL1=0xff;
TR1=1;
TH0=0xff; // Configure Timer0 To Generate PWM For LED Brightness.
TL0=50;
TR0=1;

SCON=0x50; // ToEnable Serial Communication.


IE=0x92; // To Enable Serial & Timer0 Interrupt.

while(1)
{
if(On && Blink) // Code To Blink LED if Blink option is Selected.
{
LED=1;
delay(40000);
LED=0;
On=0;
delay(40000);
if(Blink!=0)
On=1;
}
}
}

Page 4 of 27
Procedure: Android User Interface Development for Tab/
Smartphone.

1. To create a New Android Application Project


Open Eclipse IDE and go to File → New → Project → Android Application Project.

Specify the name of the application, the project and the package and then click Next.

In the next window, the “Create Activity” option should be checked. The new created
activity will be the main activity of your project. Then press Next button.

Page 5 of 27
In “Configure Launcher Icon” window you should choose the icon you want to have in
your app. We will use the default icon of android, so click Next.

Page 6 of 27
Choose the “Blank Activity” option and press Next.

Page 7 of 27
Specify the name of the new Activity and the name of the layout description of your app.
The .xml file for the layout will automatically be created in the res/layout folder.
Finally, press Finish.

Page 8 of 27
Now that the project is created, you can see the final structure of the project in the image
below.

Page 9 of 27
1

Folder, File & Description of the above project image.


(1) src
This contains the .java source files for your project. By default, it includes anMainActivity.java
source file having an activity class that runs when your app is launched using the app icon.
(2)gen
This contains the .R file, a compiler-generated file that references all the resources found in your
project. You should not modify this file.
(3)bin
This folder contains the Android package files .apk built by the ADT during the build process
and everything else needed to run an Android application.
(4)res/drawable-hdpi
This is a directory for drawable objects that are designed for high-density screens.

Page 10 of 27
(5)res/layout
This is a directory for files that define your app's user interface.
(6)res/values
This is a directory for other various XML files that contain a collection of resources, such as
strings and colors definitions.
(7)AndroidManifest.xml
This is the manifest file which describes the fundamental characteristics of the app and defines
each of its components.

2. Create the layout of the Main Activity


As we mentioned, our app will do three basic functions. We will add two Buttons in order to
enable and disable Bluetooth. Moreover we will put two Buttons, one for the paired and the
other for the enabled Bluetooth devices. Also to show the Bluetooth devices in each situation, we
will add a ListView.

Open res/layout/activity_led_control.xml and go to the respective xml tab. Then paste


the code below.

Activity_led_control.xml:

<RelativeLayoutxmlns:android="http://schemas.android.com/apk/res/andro
id"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".LedControl"
android:background="#FFF8DC" >

<Button
android:id="@+id/button2"
style="?android:attr/buttonStyleSmall"
android:layout_width="70dp"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/button1"
android:layout_alignBottom="@+id/button1"
android:layout_centerHorizontal="true"
android:text="OFF"
android:onClick="off" />

<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"

Page 11 of 27
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignTop="@+id/seekBar1"
android:text="Brightness : 0"
android:textAppearance="?android:attr/textAppearanceMedium" />

<SeekBar
android:id="@+id/seekBar1"
android:layout_width="110dp"
android:layout_height="wrap_content"
android:layout_alignRight="@+id/textView2"
android:layout_below="@+id/button2"
android:layout_marginTop="35dp"
android:max="10" />

<Button
android:id="@+id/button3"
style="?android:attr/buttonStyleSmall"
android:layout_width="70dp"
android:layout_height="wrap_content"
android:layout_above="@+id/seekBar1"
android:layout_toRightOf="@+id/textView5"
android:onClick="blink"
android:text="Blink" />

<Button
android:id="@+id/button1"
style="?android:attr/buttonStyleSmall"
android:layout_width="70dp"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/textView1"
android:layout_below="@+id/textView5"
android:layout_marginTop="58dp"
android:onClick="on"
android:text="ON" />

<ToggleButton
android:id="@+id/toggleButton1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/textView2"
android:layout_marginBottom="30dp"
android:layout_toRightOf="@+id/textView5"
android:onClick="connectDisconnect" />

<Spinner
android:id="@+id/spinner1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/toggleButton1"
android:layout_alignRight="@+id/button2" />

Page 12 of 27
<TextView
android:id="@+id/textView5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignRight="@+id/textView4"
android:layout_marginTop="40dp"
android:text="LED Control"
android:textAppearance="?android:attr/textAppearanceLarge" />

<TextView
android:id="@+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/textView3"
android:layout_centerHorizontal="true"
android:text="www.futurechiptech.com"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textColor="#0020f0"
android:textSize="12sp" />

<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/toggleButton1"
android:layout_centerHorizontal="true"
android:text="Cell: 9890141705/9665999705"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textColor="#0020f0" />

<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/textView3"
android:layout_alignParentBottom="true"
android:layout_marginBottom="59dp"
android:text="Future Chip Technologies, Pune."
android:textAppearance="?android:attr/textAppearanceSmall"
android:textColor="#0020f0" />

</RelativeLayout>

Also, we have to specify the texts in the stings.xml file, so go to res/values/strings.xml


and specifically to the xml tab. Then paste the following.

strings.xml:

Page 13 of 27
<?xml version="1.0" encoding="utf-8"?>
<resources>

<string name="app_name">LED_Control</string>
<string name="action_settings">Settings</string>
</resources>

3. Code the Main Activity

To interact with Bluetooth, BluetoothAdapter class should be used, so getDefaultAdapter()


is called to take an instance of this object class. To turn on Bluetooth, firstly we should check if
BluetoothAdapter is already enabled. If not, startActivityForResult() method with
the ACTION_REQUEST_ENABLE action Intent is called. Notice that the second parameter of
startActivityForResult() method, is an integer and is set greater than 0, so the system goes
back to our implementation of onActivityResult() method of the Activity. In contrast, we
call disable() method in order to turn off Bluetooth.

A very important functionality in Bluetooth, is to scan and search for devices that are
discoverable and can be accessed in a local area. When we say discoverable, we mean that a
device is enabled and its information is shared and visible. Before the discovering procedure it is
good to query the set of paired devices, because the desirable device may be already known.
Paired devices are previously connected devices, where the information is stored and reused by
the Bluetooth APIs. To set the paired devices, getBondedDevices() is called, so we can find
out all the BluetoothDevices.

For the performance of device discovery, we call startDiscovery() method. To receive all the
information of the BluetoothDevices that are discovered, we should register a
BroadcastReceiver for the Intent with ACTION_FOUND. It is recommended to cancel the
discovery procedure because BluetoothAdapter consumes many resources, so
cancelDiscovery() is used for this reason. Also in our example, we unregister the previously
registered BroadcastReceiver and remove all its filters, by calling unregisterReceiver() in
the onDestroy() method of our Activity.

Open src/com/example/led_control/LedControl.java file and paste the following code.

packagecom.example.led_control;

importjava.io.IOException;
importjava.io.InputStream;
importjava.io.OutputStream;
importjava.util.ArrayList;
importjava.util.Set;
importjava.util.UUID;

importandroid.os.Bundle;

Page 14 of 27
importandroid.os.Handler;
importandroid.os.Message;
importandroid.app.Activity;
importandroid.bluetooth.BluetoothAdapter;
importandroid.bluetooth.BluetoothClass;
importandroid.bluetooth.BluetoothDevice;
importandroid.bluetooth.BluetoothSocket;
importandroid.content.BroadcastReceiver;
importandroid.content.Context;
importandroid.content.Intent;
importandroid.view.Menu;
importandroid.view.View;
importandroid.widget.AdapterView.OnItemSelectedListener;
importandroid.widget.*;
importandroid.widget.SeekBar.OnSeekBarChangeListener;

public class LedControl extends Activity {

public static TextViewledBrightness;


public static SeekBarsb;

private static BluetoothAdapter BA;


private static BluetoothSocketbtSocket = null;
private static OutputStreamoutStream = null;
private static InputStreaminStream = null;
private static final UUID MY_UUID =UUID.fromString("00001101-
0000-1000-8000-00805F9B34FB");
private static ToggleButtontb;
private static booleanisConnected=false;
private Set<BluetoothDevice>pairedDevices;
private Spinner spinner;
private static String add;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_led_control);
ledBrightness=(TextView)findViewById(R.id.textView1);
tb=(ToggleButton)findViewById(R.id.toggleButton1);
tb.setTextOn("Disconnect");
tb.setTextOff("Connect");
tb.isChecked();
tb.setChecked(false);
sb =(SeekBar)findViewById(R.id.seekBar1);
sb.setOnSeekBarChangeListener(new
SeekBar.OnSeekBarChangeListener(){
intval=0;
@Override
public void onProgressChanged(SeekBar arg0,
intchangedValue, booleanfromUser) {
// TODO Auto-generated method stub

Page 15 of 27
val=changedValue;
ledBrightness.setText("Brightness : "+val);
}
@Override
public void onStartTrackingTouch(SeekBar arg0) {
// TODO Auto-generated method stub

}
@Override
public void onStopTrackingTouch(SeekBar arg0) {
// TODO Auto-generated method stub
send(val);
}

});

enableBT();

public void on(View v)


{ send(11);
}
public void off(View v)
{ send(12);
}
public void blink(View v)
{ send(13);
}
public void exit(View v)
{ if (outStream != null) {
try {
outStream.flush();
} catch (IOException e) {
tost_short("Failed To Flush Output Stream.");
}
}
try {
btSocket.close();
tost_short("Disconnecting....");
} catch (IOException e2) {
tost_short("Failed To Close Connection.Please Turn Off
Bluetooth.");
}
finish();
}

public void connectDisconnect(View v)


{
boolean on=((ToggleButton) v).isChecked();
if(on)
connect();

Page 16 of 27
else
disconnect();
}

@Override
public void onStop()
{
super.onStop();
if (outStream != null) {
try {
outStream.flush();
} catch (IOException e) {
tost_short("Failed To Flush Output Stream.");
}
}
try {
btSocket.close();
tost_short("Disconnecting....");
} catch (IOException e2) {
tost_short("Failed To Close Connection.Please
Turn Off Bluetooth.");
}
finish();

}
@Override
public void onPause()
{
super.onPause();

@Override
publicbooleanonCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if
it is present.
getMenuInflater().inflate(R.menu.led_control, menu);
return true;
}
public void enableBT(){
BA = BluetoothAdapter.getDefaultAdapter();

if (!BA.isEnabled()) //Prompt user to turn on Bluetooth


{
tost_short("Bluetooth is OFF");
Intent turnOn = new
Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
super.startActivityForResult(turnOn, 0);
while(!BA.isEnabled());
}

Page 17 of 27
pairedDevices = BA.getBondedDevices();

ArrayList list = new ArrayList();


for(BluetoothDevicebt : pairedDevices)
list.add(bt.getName());

spinner = (Spinner)findViewById(R.id.spinner1);
ArrayAdapter<String>scrollAdp=new
ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,list);

scrollAdp.setDropDownViewResource(android.R.layout.simple_spinner
_dropdown_item);
spinner.setAdapter(scrollAdp);

}
public void connect() // Code to Make Connection With Bluetooth
HC-05
{
if(!isConnected)
{
for(BluetoothDevicebt : pairedDevices)
{
if(bt.getName().equals(spinner.getSelectedItem().toString()))
add=bt.getAddress();
}
BluetoothDevice device = BA.getRemoteDevice(add); // Give
Correct MAC Address of Your Device
try {
btSocket =
device.createRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) {
tost_short("ERROR: Unable to Find Device Please
Check Bluetooth Connection.");
finish(); return;
}
BA.cancelDiscovery();
try {
btSocket.connect();
} catch (IOException e) {
tost_short("ERROR: Unable to Make Bluetooth
connection.");
finish(); return;
}
try {
outStream = btSocket.getOutputStream();
inStream = btSocket.getInputStream();
tost_short("You are Connected With Gadget.Now You
Can Communicate With Gadget.");
} catch (IOException e) {
tost_short("ERROR: Unable to Get Output
Stream.");
finish(); return;

Page 18 of 27
}
isConnected=true;
}
}

void disconnect()
{
if(isConnected)
{
if (outStream != null) {
try {
outStream.flush();
} catch (IOException e) {
tost_short("Failed To Flush Output Stream.");
}
}
try {
btSocket.close();
tost_short("Disconnecting....");
} catch (IOException e2) {
tost_short("Failed To Close Connection.Please
Turn Off Bluetooth.");
}
isConnected=false;
}
}

public void tost_short(String s)


{

Toast.makeText(getApplicationContext(),s,Toast.LENGTH_SHORT).show
();
}

private void send(int c) //Cmd function starts here.


{
if(!isConnected)
return;
byte b=(byte)c;
try {
outStream.write(b);
} catch (IOException e) {
tost_short("ERROR: Unable to Send. Please Check Bluetooth
Connections.");
}
}
}

Page 19 of 27
4. Set the permissions
We have to declare the permissions in the AndroidManifest.xml file of our project. For this
reason we add BLUETOOTH permission if we want to use any of the Bluetooth features. Also we
should add BLUETOOTH_ADMIN permission, in order to discover other devices.

Open AndroidManifest.xml file and go to the respective xml tab. Then paste the following.

AndroidManifest.xml:

<?xml version="1.0" encoding="utf-8"?>


<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.led_control"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="18" />

<uses-permissionandroid:name="android.permission.BLUETOOTH"/>
<uses-permissionandroid:name="android.permission.BLUETOOTH_ADMIN"/>

<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.led_control.LedControl"
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>

We should mention that if we have to add BLUETOOTH_ADMIN permission, the declaration of


BLUETOOTH permission is obligatory.

Page 20 of 27
5. Run the application
To run the application we can‟t use the Android emulator, so we have to run the app from our
Android device via Eclipse.

Connect your Android device with your pc through USB. Go to Settings → Applications →
Development path and enable USB debugging option.

Back to Eclipse, right click on our project → Run as → Run Configurations.

In the popup window choose the current project, go to the Target tab and choose “Always
prompt to pick device” option, as you can see below. Then click Run.

Finally choose the running Android device and press OK.

Page 21 of 27
The app will be loaded in your Android device, as you can see in the image below.

Page 22 of 27
Page 23 of 27
Page 24 of 27
Page 25 of 27
Page 26 of 27

View publication stats

You might also like