به نام خدا : تو این مطلب میخوام پروژه روشن/خاموش کردن یه LED رو به کمک بلوتوث موبایل انجام بدم، به میکروکنترلر هم میتونید ماژول HC05 یا HC06 وصل کنید؛ برای توضیحات بیشتر فیلم ته مطلب رو ببینید؛ برنامه اندروید با Android Studio نوشتم که سورس کدش رو ته مطلب و داخل خود مطلب میزارم ( ارتباط موبایل با میکرو از طریق bluetooth قسمت 1 )
ارتباط موبایل با میکرو از طریق bluetooth قسمت 1
پروژه آردوینو
شماتیک پروژه : برای دیدن در اندازه اصلی، روی عکس کلیک کنید.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
char command1; String string1 = ""; #define LED1 2 void setup() { Serial1.begin(9600); pinMode(LED1, OUTPUT); } void loop() { string1 = ""; while(Serial1.available() > 0) { command1 = Serial1.read(); if( command1 == '\n' ) break; else string1 += command1; delay(10); } if( command1 == '\n' ) { // if my Data Readed !!! if(string1 == "TO") digitalWrite(LED1, 1); else if(string1 == "TF") digitalWrite(LED1, 0); } } |
پروژه اندروید نوشته شده در محیط اندروید استودیو
کدهای پروژه اندروید :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.md3848.Project1" > <uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/> <uses-permission android:name="android.permission.BLUETOOTH"/> <application android:allowBackup="true" android:icon="@mipmap/dmf313_ir" android:theme="@style/AppTheme"> <activity android:name="com.example.md3848.Project1.DeviceList" android:label="DMF313.IR Pro1"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name="com.example.md3848.Project1.ledControl" android:label="LED Control" > </activity> </application> </manifest> |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" tools:context=".DeviceList" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <ToggleButton android:layout_width="match_parent" android:layout_height="wrap_content" android:onClick="onClick_EnableDisable_Bluetooth" android:id="@+id/Tbtn_EnableDisable_Bluetooth" android:textSize="20dp"/> <Button android:id="@+id/Bluetooth_btn_ShowPairedDevices" android:onClick="onClick_Bluetooth_btn_ShowPairedDevices" android:text="Paired Devices" android:layout_width="match_parent" android:layout_height="wrap_content" android:textSize="20dp"/> <TextView android:text="Paired Devices" android:layout_width="wrap_content" android:layout_height="wrap_content" android:paddingLeft="15dp" android:paddingTop="15dp"/> <ListView android:id="@+id/Bluetooth_lv_PairedDevices" android:layout_width="wrap_content" android:layout_height="match_parent"/> </LinearLayout> |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" tools:context="com.example.md3848.Project1.ledControl" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <ToggleButton android:layout_width="match_parent" android:layout_height="wrap_content" android:onClick="onClick_Tbtn_TurnOnOff_LED" android:id="@+id/Tbtn_TurnOnOff_LED" android:textSize="20dp"/> <LinearLayout android:layout_width="match_parent" android:layout_height="0dip" android:layout_weight="1" android:gravity="center|bottom" android:orientation="vertical"> <Button android:id="@+id/Bluetooth_btn_Disconnect" android:onClick="onClick_Bluetooth_btn_Disconnect" android:text="Disconnect" android:layout_width="match_parent" android:layout_height="wrap_content" android:textSize="20dp" /> </LinearLayout> </LinearLayout> |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 |
package com.example.md3848.Project1; import android.app.Activity; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothSocket; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.util.Log; import android.view.View; import android.widget.Toast; import android.widget.ToggleButton; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.lang.ref.WeakReference; import java.util.UUID; public class ledControl extends Activity { static ToggleButton Tbtn_TurnOnOff_LED; String address = null; BluetoothAdapter bAdapter = null; BluetoothDevice bDevice = null; BluetoothSocket bSocket = null; static final UUID myUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); //SPP UUID. Look for it ConnectedThread cThread; private static BluetoothResponseHandler brHandler; private final static int Error = 0; private final static int DataIsReady = 1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_led_control); Tbtn_TurnOnOff_LED = (ToggleButton)findViewById(R.id.Tbtn_TurnOnOff_LED); Tbtn_TurnOnOff_LED.setChecked(false); Tbtn_TurnOnOff_LED.setText("LED ????"); address = getIntent().getStringExtra( "device_address" ); bAdapter = BluetoothAdapter.getDefaultAdapter(); try { Toast.makeText(getApplicationContext(), "Connecting...", Toast.LENGTH_SHORT).show(); if( bSocket == null ) { bDevice = bAdapter.getRemoteDevice(address);//connects to the device's address and checks if it's available bSocket = bDevice.createInsecureRfcommSocketToServiceRecord(myUUID);//create a RFCOMM (SPP) connection bAdapter.cancelDiscovery(); bSocket.connect(); } Toast.makeText(getApplicationContext(), "Connected", Toast.LENGTH_SHORT).show(); } catch (Exception e) { Toast.makeText(getApplicationContext(), "Connection Failed. Is it a SPP Bluetooth? Try again.", Toast.LENGTH_SHORT).show(); finish(); } cThread = new ConnectedThread(bSocket); cThread.start(); if (brHandler == null) brHandler = new BluetoothResponseHandler(this); else brHandler.setTarget(this); } public void onClick_Tbtn_TurnOnOff_LED( View v ) { if( Tbtn_TurnOnOff_LED.isChecked() ) { SendData( "TO\n" ); Tbtn_TurnOnOff_LED.setText("LED Turned OFF"); } else { SendData( "TF\n" ); Tbtn_TurnOnOff_LED.setText("LED Turned ON"); } } public void SendData(String Data) { if( bSocket != null ) { try { bSocket.getOutputStream().write(Data.getBytes()); } catch (Exception e) { Toast.makeText(getApplicationContext(), "Error in Send Data", Toast.LENGTH_LONG).show(); } } else { Toast.makeText(getApplicationContext(), "Bluetooth in Not Connected", Toast.LENGTH_LONG).show(); } } @Override protected void onDestroy() { super.onDestroy(); if( bSocket == null ) return; if( bSocket.isConnected() ) { Disconnect(); } } public void onClick_Bluetooth_btn_Disconnect( View v ) { Disconnect(); } public void Disconnect() { if ( bSocket != null && bSocket.isConnected() ) { try { bSocket.close(); Toast.makeText(getApplicationContext(), "Disconnected", Toast.LENGTH_SHORT).show(); } catch( IOException e ) { Toast.makeText(getApplicationContext(), "Error in Disconnecting ", Toast.LENGTH_SHORT).show(); } } finish(); } public static class ConnectedThread extends Thread { private BluetoothSocket mmSocket; private InputStream mmInStream; private OutputStream mmOutStream; public ConnectedThread(BluetoothSocket socket) { mmSocket = socket; InputStream tmpIn = null; OutputStream tmpOut = null; // Get the input and output streams, using temp objects because member streams are final try { tmpIn = socket.getInputStream(); tmpOut = socket.getOutputStream(); } catch (IOException e) { e.printStackTrace(); } mmInStream = tmpIn; mmOutStream = tmpOut; //Tell other phone that we have connected write("connected".getBytes()); } public void run() { byte[] buffer = new byte[512]; int bytes; StringBuilder readMessage = new StringBuilder(); while( !this.isInterrupted() ) { try { bytes = mmInStream.read(buffer); String readed = new String(buffer, 0, bytes); readMessage.append(readed); if (readed.contains("\n")) { brHandler.obtainMessage(ledControl.DataIsReady, bytes, -1, readMessage.toString()).sendToTarget(); readMessage.setLength(0); } } catch (Exception e) { e.printStackTrace(); Log.i( "ReadData", "22222222222222222222222222"); Message msg = brHandler.obtainMessage( ledControl.Error, "" ); brHandler.sendMessage(msg); break; } } } // Call this from the main activity to send data to the remote device public void write(byte[] bytes) { try { mmOutStream.write(bytes); } catch (IOException e) { e.printStackTrace(); } } // Call this from the main activity to shutdown the connection public void cancel() { if (mmInStream != null) { try {mmInStream.close();} catch (Exception e) {} mmInStream = null; } if (mmOutStream != null) { try {mmOutStream.close();} catch (Exception e) {} mmOutStream = null; } if (mmSocket != null) { try {mmSocket.close();} catch (Exception e) {} mmSocket = null; } this.interrupt(); } } private static class BluetoothResponseHandler extends Handler { private WeakReference<ledControl> mActivity; public BluetoothResponseHandler(ledControl activity) { mActivity = new WeakReference<ledControl>(activity); } public void setTarget(ledControl target) { mActivity.clear(); mActivity = new WeakReference<ledControl>(target); } @Override public void handleMessage(Message msg) { ledControl activity = mActivity.get(); String Data = (String)msg.obj; if (activity != null) { switch (msg.what) { case DataIsReady : if( Data == null ) return; break; } } } } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 |
package com.example.md3848.Project1; import android.app.Activity; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import android.widget.ToggleButton; import java.util.ArrayList; import java.util.Set; public class DeviceList extends Activity { ListView devicelist; ToggleButton Tbtn_EnableDisable_Bluetooth; private BluetoothAdapter myBluetooth = null; private Set<BluetoothDevice> pairedDevices; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_device_list); devicelist = (ListView)findViewById(R.id.Bluetooth_lv_PairedDevices); Tbtn_EnableDisable_Bluetooth = (ToggleButton) findViewById(R.id.Tbtn_EnableDisable_Bluetooth); Tbtn_EnableDisable_Bluetooth.setText( "Enable Bluetooth" ); myBluetooth = BluetoothAdapter.getDefaultAdapter(); if( myBluetooth == null ) { Toast.makeText(getBaseContext(), "Device does not support bluetooth", Toast.LENGTH_LONG).show(); finish(); } if( myBluetooth.isEnabled() ) { Tbtn_EnableDisable_Bluetooth.setChecked(true); Tbtn_EnableDisable_Bluetooth.setText( "Disable Bluetooth" ); } else { Tbtn_EnableDisable_Bluetooth.setChecked(false); Tbtn_EnableDisable_Bluetooth.setText( "Enable Bluetooth" ); } } public void onClick_EnableDisable_Bluetooth( View v ) { if( myBluetooth.isEnabled() ) { myBluetooth.disable(); Tbtn_EnableDisable_Bluetooth.setText( "Enable Bluetooth" ); } else { Intent turnBTon = new Intent( BluetoothAdapter.ACTION_REQUEST_ENABLE ); startActivityForResult( turnBTon, 1 ); Tbtn_EnableDisable_Bluetooth.setText( "Disable Bluetooth" ); } } public void onClick_Bluetooth_btn_ShowPairedDevices( View v ) { pairedDevices = myBluetooth.getBondedDevices(); ArrayList list = new ArrayList(); if( pairedDevices.size() > 0 ) { for(BluetoothDevice bt : pairedDevices) { list.add(bt.getName() + "\n" + bt.getAddress()); } } else { Toast.makeText(getApplicationContext(), "No Paired Bluetooth Devices Found.", Toast.LENGTH_LONG).show(); } final ArrayAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1, list); devicelist.setAdapter(adapter); devicelist.setOnItemClickListener(myListClickListener); //Method called when the device from the list is clicked } private AdapterView.OnItemClickListener myListClickListener = new AdapterView.OnItemClickListener() { public void onItemClick( AdapterView<?> av, View v, int position, long id ) { // Get the device MAC address, the last 17 chars in the View String info = ((TextView) v).getText().toString(); String address = info.substring(info.length() - 17); Intent i = new Intent(DeviceList.this, ledControl.class); i.putExtra("device_address", address); setResult(RESULT_OK,i); startActivity( i ); } }; } |
عکس پروژه در عمل :
فیلم پروژه :
امیدوارم این مطلب براتون مفید بوده باشه، تو این ماه رمضون ما رو هم دعا کنید؛ موفق موید باشید؛ یا علی.
=======================================
=======================================
=======================================
این کلیپو حتما ببینید : http://www.aparat.com/v/3Q0th
مهمان
با سلام جناب مهندس
سوالی داشتم ممنون میشوم راهنمایی بفرمایید.من میخواهم روشن و خاموش شدن یک LED متصل به میکروATMEGA را توسط دستوری که از موبایل به مازول بلووث ارسال میشود، کنترل کنم. یعنی از موبایل on رو بفرستم و ال ای دی روشن شود و of را بفرستم و خاموش شود.اما اتفاقی که می افتد این است که ارسال داده انجام میشود ولی انگار مدار اصلا نمیتواند تشخیص دهد که این داده ایکه آمدهon , of است و اصلل اتفاقی نمیافتد.به نظرتون مشکل از چیه؟لازم به ذکر است من برنامه را در شبیه سازی پیاده سازی کردم و جواب میداد ولی در عمل جواب نمیدهد.هزار بار هم اتصالات و تنظیمات و بادریت و … رو چک کردم.
مهمان
سلام مهندس خسته نباشی فایل اندروید استودAdd Google Maven repository and sync project
Show in Project Structure dialog
Affected Modules: app
ERROR: Failed to resolve: com.android.support:appcompat-v7:25.3.1
Add Google Maven repository and sync project
Show in Project Structure dialog
Affected Modules: app
یو این خطا رو میده دلیلش رو میدونید
مهمان
باسلام دوست عزیز شما که تو الکترونیک وارد هستید لطفا پروژه ها رو با avr بنویسید تابتونیم استفاده کنیم
مهمان
سلام.من کدها رو با blutooth terminal میزنم چرا کار نمیکنه؟ ْۤTF , TN
نکته داره؟
مهمان
با سلام و خسته نباشید
من از سایتتون بازدید کردم.خیلی عالی و بی نقص.کامل.کلا همه چیز تمام.خدا خیرتون بده انشاا…آدمای مثه شما کم پیدا میشن این دوره زمونه رایگان علمو نشر بدن.شما مصداق ذکات علم نشر اون هست هستین.انشاا… به وسیله ی انسانهایی مثه شما هر روز کشورمون رو به محیطی برای ظهور آقامون نزدیکتر کنیم.بازم خدا قوت
مهمان
سلام می تونم بپرسم که منبع شما برای ساخت این نرم افزار چی بوده کجا درباره ی بلوتوث و otg و wifi و.. مطب می گذاره(ما که ندیدیم
)
نویسنده این مطلب
سلام
برا قسمت اندرویدش آموزش عمومیش تو نت فارسی هستش – برا بحث otg تو نت خارجی سرج کردم – برا بحث خود ماژول بلوتوث برا میکرو که کار باهاش سادس و قبلا مطالبی دربارش گزاشته بودم و تو نت قارسی مطلب دربارش زیاده – برا بلوتوث اندروید که یه چیزکی تو نت فارسی هستش به صورت رایگان، بقیشو تو نت خارجی سرج کردم.
مهمان
سلام برای نوشتن این برنامه تا چه حد باید اندروید بلد بود؟…واینکه میشه یه منبع برای یادگیری اندروید معرفی کنید.
نویسنده این مطلب
سلام – بستگی به خودت داره – فیلمای سایت irprogram و اسفوندونه -مقدماتی-
مهمان
قشنگ معلومه با روحانی دعوا داری…
دمت گرم دادا آموزشات حرف نداره
راستی آپارات هم دنبال میشی
نرم افزار های مهم هم مثل : اندروید استودیو – بسکام – کد ویژن و …. رو قرار بده تا انقدر دنبالشون نگردیم
اگه هم آموزش برنامه نویسی بدی عالی میشه
نویسنده این مطلب
اولا روحانی رئیس جمهور کشوره و بقال سر کوچه نیست! باز بقال سر کوچمون رو حرفشو بیام بزارم تو سایت یه حرفی اون وقت حرف “دعوا داری” درسته ولی وقتی حرف رئیس جمهور رو بیای بگی بحث فرق داره – این آقا هسته ای رو که بتون گرفت رفت! تحریم هم که ماشاالله روز به روز داره بیشتر میشه – دیروز یه حرفی میزنه – فرداش یه حرف دیگه – الان هم که میخواد شعار مرگ بر اسرائیل و مرگ بر آمریکا رو حذف کنه – نباید من حرفشو در مقابل حرف امام خمینی ره بزارم تو سایت تا ملت ببینین و آگاه بشن؟
مهمان
دمت گرم داداش…
کارِت درسته..
و خیلی حرکاتیی به جا هستش (لایک)
مهمان
سلام حیف سایت نیست ؟؟