關於我自己

2012年12月16日 星期日

log4jdbc元件 Java資料庫追蹤

log4jdbc

是記錄資料庫操作與法跟回傳值




官方網站:

 https://code.google.com/p/log4jdbc/

1.首先先下載  jar元件


log4jdbc4-1.2.jar
log4j-1.2.16.jar
slf4j-api-1.6.4.jar
slf4j-log4j12-1.6.4.jar

2.並在web.xml 加入等字串(切記log4j.properties等檔案我是放在WEB-INF\classes\底下)

<servlet>
<init-param>
<param-name>log4j-properties-location</param-name>
<param-value>WEB-INF\classes\log4j.properties</param-value>
</init-param>
</servlet>

3.並在WEB-INF\classes\底下新增兩個檔案log4j.properties跟log4j.xml


如果不知道log4j.properties跟log4j.xml要放哪些內容
可以參考官網5. Set up your loggers. 裡面有 log4j.properties跟log4j.xml可以看~也可以直接複製

4.並放上更改驅動程式

 本來是Class.forName("net.sourceforge.jtds.jdbcx.JtdsDataSource");把它改成log4jdbc驅動
  Class.forName("net.sf.log4jdbc.DriverSpy");
然後
conn = DriverManager.getConnection("jdbc:jtds:sqlserver://localhost:1433/Test01","OO","OOO");
  記得加入log4jdbc等字串會變成
conn = DriverManager.getConnection("jdbc:log4jdbc:jtds:sqlserver://localhost:1433/Test01","OO","OOO");
然後你在Console控制台可以看到資料庫操作印出來的結果    

使用Debug模式也可以到達一樣的效果 ~ 只不過比較麻煩:




2012年10月23日 星期二

砲彈發射

今天遇到有人不太懂物裡的好玩之處
所以引用一下物理學課本公式
物理學好玩不再於他單單只是數學 
而是他可以去模擬推算結果
有如推理小說般的耐人尋味



2012年10月12日 星期五

反三角函數


往往在許多數學題會遇到有關三角函數求角度

例如sin(a)=0.9848

求a 是多少角度呢?

在Matlab跟C++可利用asin涵式 ~ 如上圖反三角函數系列

其他:

2012年7月26日 星期四

碰撞

1.碰撞偵測

利用三角函數,取斜邊邊長

假設兩個圓都半徑都是25

所以碰撞到斜邊必須小於50

 
母球反彈
 

兩球反彈

 


九大行星

2012年7月9日 星期一

2012年7月8日 星期日

週期波

週期波

許多工程上都會用到週期波 ~ 例如訊號跟馬達之類

2012年7月6日 星期五

三角函數公式使用Matlab運算

三角函數公式使用Matlab運算

其實只要了解公式 ~ 並會使用計算機運算

很容易了解其中的道理 ~ 所以選用Matlab


2012年7月3日 星期二

力學-轉動慣量

力學-轉動慣量

公式:

假設有一個圓盤
R    半徑為: 1m
M    質量為: 8kg

套第一個公式(假設是縱放)
  8/4=  2 kgm^2

套第二個公式(假設是橫放)
 8/2= 4 kgm^2


然後有看到一個日本的網站 
(老實說讓我覺得日本工業強盛~不是沒有理由的說 QQ)

KHK STOCK GEARS Website 網站
http://www.khkgears.co.jp/

公式:
KHK STOCK GEARS Website Training Example Reference Guide :
http://www.khkgears.co.jp/tw/gear_technology/
點進去 齒輪技術資料 會看到  齒輪技術資料(PDF版)


2012年6月30日 星期六

伺服馬達跟驅動器之所需脈波

電子齒輪比=CMX/CDV


CMX代入→馬達額定轉速(rpm)×馬達ENCORDER分解能
CDV代入→脈波產生器之最高速率(PULSE/秒)× 60(秒/分)

馬達額定轉速(rpm:1分鐘轉)
馬達ENCORDER分解能(pulse/圈)→馬達轉一圈需給的pulse數
脈波產生器之最高速率(pulse/秒)

因此未化簡前 CMX(分子)就是馬達以額定轉速轉一分鐘所需的pulse數
CDV(分母)就是脈波產生器一分鐘所能產生之最多pulse數


所以假設:
馬達 一分鐘轉 3000 圈

轉一圈需要脈波:131072 Pulse


但是如果我選用驅動器最大輸出200k
200kHz=200000Hz
那麼
(1310702 Pulse * 3000 prm) /(200000Hz * 60 sec)
393216000/12000000=32.768
4096/125  =32.768
驅動器輸入CMX:4096  CDV:125


1310702/32.768 = 4000
馬達轉一圈需要從脈波產生器丟出4000個pulse,額定轉速依然是3000rpm 


而有些伺服馬達是本身跟驅動器已經結合在一起的說

另外可以參考一下:
寶祥電子:PDF檔案
進去之後點 : 資源下載   然後會看到    操作手冊下載
看到最後一項    整合式SLIM5馬達
下載此PDF 到33頁會另外介紹他的脈波輸入的計算
http://www.1111motor.com/

2012年6月29日 星期五

三用電錶

三用電錶
一般來說只要會用三用電錶

在檢測電器產品 ~ 幾乎等於維修

就像電腦知道哪個零件壞了~換掉就好了
(幾乎只要用電壓去測有沒有通電而以~來判斷該零件是否壞掉)




為什麼吃飽 ~ 閒閒沒事發著一篇呢?

因為被媽媽叫去修電風扇 ~結果一開打看到電源線斷了

連測都不用測就直接用焊接把他接好就可以動了
(不過一打開電風扇 ~ 阿鳥威 ~ 小強超多的~嚇的我花容失色)
 正常來說那種長長的插頭
我都用交流電壓來測量他的電源線有沒有通

至於要用直流電壓測量的是著種 ~ 一般外面賣的電源供應器
5V電源 影片:
像著個範例~就是很明顯的馬達的問題:
用交流電壓測量
連接電風扇的四條電源線
期中兩條就是+跟+ 正極跟負極
影片中:電風扇共有3種速度
1速:110~120之間
2速:100~119之間
3速:90~100之間


2012年6月16日 星期六

SolidWork 組合零件

SolidWork 組合零件

組合零件是用觀察自己的設計與架構的驗證
大部分都是在橫介面與縱介面的組合
 當無法拉轉換到適當的選取介面~我則會另用
(預覽之前的瀏覽)
而像懶的在畫一些元件的話~
則SolidWork有內建的元件可提供使用

2012年6月15日 星期五

Lego 小組裝(1)

Lego 小組裝(1)

利用兩個馬達跟顏色感應器:

影片:
 程式碼:

task main()
{

   int actual_position=0;
  SetSensorColorFull(S4);
   ClearScreen( );
      for(int i=0;i<=3;i++)
     {
   RotateMotor(OUT_A, 10,-360);
   Off(OUT_A);

   Wait(3000);
  actual_position = Sensor(S4);
  switch(actual_position)
  {
  case 1:     //Black Color
       TextOut(50,LCD_LINE2,"Black\n");
  break;
   case 2:     //Blue Color
       TextOut(50,LCD_LINE2,"Blue\n");
  break;
   case 3:     //Green Color
       TextOut(50,LCD_LINE2,"Green\n");
  break;
   case 4:     //Yellow Color
       TextOut(50,LCD_LINE2,"Yellow\n");
  break;
   case 5:     //Red Color
       TextOut(50,LCD_LINE2,"Red\n");
  break;
   case 6:     //White Color
       TextOut(50,LCD_LINE2,"White\n");
  break;
  }
   Wait(6000);
    RotateMotor(OUT_B, 10,-360);
   Off(OUT_B);
  Wait(8000);
  }
}

2012年6月12日 星期二

NXT利用藍芽Com RS232技術傳送指令到PC

著個步驟~是我要利用NXT傳送指令到Android手機的先前測試工具

1.寫在NXT寫入程式 (利用SendRemoteString涵數)
2.
因為我的作業系統是Windows 7 所以沒有hyperterminal.exe程式


所以我到此網站下載
(你會在網站內看到zip-package from here等字串,按下去就可以下載)
http://digitizor.com/2009/08/29/install-winxp-hyperterminal-client-on-windows-vista-or-windows-7-free/

3.下載後解壓縮你會看到
4.在此之前先用電腦連結NXT
會在工作管理員產生Port 連結埠~然後再裝置跟印表機的屬性你會看到硬體的連接埠
我的是Com3 ~ 正確來說Com3是傳輸,而Com7接收
就像我在上一遍"Android 藍芽連結NXT 控制馬達"裡面有貼NXT螢幕的連接符號
傳送與接收,因為太懶的解釋,直接寫有連接沒連接


5.連接好之後~請執行hyperterminal.exe 去設置Com   (記得要連之前要開NXT的主機)
連好之後會出現 ~  11€    11€    11€   11  (因為我在NXT 按了4次執行)

做個簡單的應用 ~ 顏色偵測
目的:利用NXT藉由藍芽傳送值到電腦
所以用顏色感測器當做示範
當顏色感測器 ~收到值之後借由NXT將字串傳輸到電腦

影片:


程式碼:
 task main()
{

  int actual_position=0;
  SetSensorColorFull(S2);

  while (true)
  {
   ClearScreen( );
  actual_position = Sensor(S2);
  switch(actual_position)
  {
  case 1:     //Black Color
       TextOut(50,LCD_LINE2,"Black\n");
       SendRemoteString( 0, 0, "Black\n" );
  break;
   case 2:     //Blue Color
       TextOut(50,LCD_LINE2,"Blue\n");
        SendRemoteString( 0, 0, "Blue\n" );
  break;
   case 3:     //Green Color
       TextOut(50,LCD_LINE2,"Green\n");
        SendRemoteString( 0, 0, "Green\n" );
  break;
   case 4:     //Yellow Color
       TextOut(50,LCD_LINE2,"Yellow\n");
        SendRemoteString( 0, 0, "Yellow\n" );
  break;
   case 5:     //Red Color
       TextOut(50,LCD_LINE2,"Red\n");
        SendRemoteString( 0, 0, "Red\n" );
  break;
   case 6:     //White Color
       TextOut(50,LCD_LINE2,"White\n");
        SendRemoteString( 0, 0, "White\n" );
  break;
  }
  Wait(1000);
  }
}



使用Visual Basic 6.0 程式來接收NXT傳來的值

影片:

介面圖:

VB 主程式碼:
被空白字元所煩惱,一直刪之不去,利用過Trim刪除空白涵式跟去查空白的Acsii有查到13跟9
利用replace(字串,Chr(13),"")都沒辦法解決,只好用著種煩人的寫法,有點冗長


Private Sub Command1_Click()

MSComm1.CommPort = 3     '開啟的連接埠
MSComm1.Settings = "9600,n,8,1"
MSComm1.InputMode = comInputModeBinary
If (MSComm1.PortOpen = True) Then MSComm1.PortOpen = False
MSComm1.PortOpen = True
Timer1.Enabled = True
End Sub

Private Sub Command2_Click()
MSComm1.PortOpen = False '關閉
End Sub


Private Sub Timer1_Timer()
Dim ColorValue As Variant
Dim buf() As Byte
Dim v1, v2, v3, v4, v5, v6 As Integer
Dim PictureColor As String

If MSComm1.InBufferSize > 0 Then
   ColorValue = MSComm1.Input
   buf = ColorValue
 
   For i = 0 To UBound(buf)
       If Chr(buf(i)) = " " Then
       Else
       Text1.Text = Text1.Text & Chr(buf(i))
       Text2.Text = Text2.Text & Chr(buf(i))
       End If
   Next i
  
   Text1.Text = Text1.Text & vbCrLf

   v1 = InStr(1, Text2.Text, "Red", 1)
   v2 = InStr(1, Text2.Text, "Black", 1)
   v3 = InStr(1, Text2.Text, "Blue", 1)
   v4 = InStr(1, Text2.Text, "Green", 1)
   v5 = InStr(1, Text2.Text, "Yello", 1)
   v6 = InStr(1, Text2.Text, "White", 1)
   Label1.Caption = Text2.Text
   If v1 > 0 Then
   Picture1.BackColor = RGB(255, 0, 0) '紅色
   End If
   If v2 > 0 Then
   Picture1.BackColor = RGB(0, 0, 0) '黑色
   End If
   If v3 > 0 Then
   Picture1.BackColor = RGB(0, 0, 255) '藍色
   End If
   If v4 > 0 Then
   Picture1.BackColor = RGB(0, 255, 0) '綠色
   End If
   If v5 > 0 Then
   Picture1.BackColor = RGB(255, 255, 0) '黃色
   End If
   If v6 > 0 Then
   Picture1.BackColor = RGB(255, 255, 255) '白色
   End If
   Text2.Text = ""
  
End If

End Sub

======================================
VB 6.0 是使用MSCOMM元件(我比較常用~因為幾乎用拉的省很多時間)
C++ 則是用Createfile涵式Readfile涵式WriteFile涵式
一般打Google打Createfile就會有很多相關資訊

如果要用免費的軟體C++可以考慮Dev-C ++

如果想用有圖形介面又免費的可以考慮
Microsoft Visual Studio 2008 Express 版 SP1
http://www.microsoft.com/zh-tw/download/details.aspx?id=20682

裡面有VB.NET跟C#可以用的說

VB.NET開啟Com Port的方法(VB.NET寫法幾乎跟C#都是大同小異)

VB.NET 開打Com的範例
Imports System.IO.Ports
Imports System.Threading
Imports System.Text
Public Class Form1
    Public myPort As New System.IO.Ports.SerialPort

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
       '設定參數
        With myPort
            .BaudRate = 9600
            .DataBits = 8
            .Parity = Parity.None
            .StopBits = StopBits.One
            .PortName = "COM3"
            '.ReadTimeout = 1000
            .Encoding = System.Text.Encoding.ASCII
            .ReadTimeout = 1000
        End With
        Dim read_word As String
        read_word = ""
        Try
            myPort.Open() '開啟

            '    myPort.DtrEnable = True
            Label1.Text = myPort.IsOpen
            myPort.Write("AT" & vbCrLf)   '寫入 AT等字串


            myPort.RtsEnable = True
            delay(5000)
            read_word = myPort.ReadExisting()
            TextBox2.Text = read_word
            myPort.Close()
            Label1.Text = myPort.IsOpen

            ' TextBox2.Text &= myPort.ReadExisting
            '  TextBox2.Text &= myPort.ReadLine & vbCrLf
            '   Timer1.Enabled = True
        Catch ex As Exception
            ex.Message.ToString()
        End Tr

 '我是習慣用時間來接收 ~ 其實還有其他COM接收方法 DataReceived  ~ 只要有有訊息就觸動

    Private Sub Timer1_Tick(ByVal sender As Object, ByVal e As System.EventArgs) Handles Timer1.Tick
        Dim InStr As String

        InStr = ""
        Try
            myPort.ReadTimeout = 1000
            InStr = myPort.ReadExisting()
            If InStr.Length = 0 Then
                Exit Sub
            Else
                TextBox2.Text += InStr
                TextBox2.Text += "ok"
            End If
        Catch ex As Exception
            MessageBox.Show("讀取錯誤:" + ex.ToString, "錯誤通知", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
        End Try

    End Sub

2012年6月8日 星期五

Android 藍芽連結NXT 控制馬達


The purpose of this thesis to research how to build a bluetooth connection between Android and LEGO-Mindstorm-NXT.

一開始用意不是做這個,是在做玩超音波的時候,

突然想到著不是跟台大研發的倒車雷達一樣嗎?

然後看著超音波偵測器想那跟手機結合那不是很好玩

又讓我想到RGB光源偵測器如果跟手機結合,那麼偵測器偵測到顏色把資料傳到手機,

手機在去呼叫聲音檔案例如:紅色叫聲 聲音檔案或者用手機的無線上網在另外傳送資料

所以才發著一篇 ~
(著一篇的Android 連結跟傳輸我並沒有寫分開有點令人詬病~所以請多多包涵)
==> 連結跟傳輸以分開(主程式碼已修改)



1.NXT 控制器左上角會顯示藍芽是否也連結的符號 (<:未連結       <>:已連結 ) 

 Note the screen in the upper-right corner of the picture ,
 symbol mean ( <:Not To Connect bluetooth   <>:To Connect bluetooth )

程式的介面(program interface):


 影片(Video):
 

開發環境: Windows 7 32Bit
使用:Eclipse + Android SDK + Java SDK

記得到AndroidManifest.xml寫入准許加入藍芽權限: 

you need to add the BLUETOOTH permission to your application

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



封包的格式: 下面的圖片是馬達封包的格式

要看比教詳細的介紹請看
 http://www.mindstorms.rwth-aachen.de/trac/wiki/MotorControl
Message format:開頭你會看到連結埠

然後參考馬達跟超音波的範例:
 http://cellbots.googlecode.com/svn-history/r15/trunk/android/Mindstorms_NXT/src/com/googlecode/cellbots/nxt/NxtConnectionService.java
你會看到
public int setMotor(String srcApp, int motor, int power) {  =>馬達
 public int setUltraSonicSensor(String srcApp, int port) { =>超音波

介面得程式碼:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello" />

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

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="開起藍芽裝置" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="搜尋藍芽裝置" />

    <Button
        android:id="@+id/button4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="連接藍芽裝置" />




    <Button
        android:id="@+id/button3"
        android:layout_width="146dp"
        android:layout_height="wrap_content"
        android:text="更新藍芽搜尋" />

    <Spinner
        android:id="@+id/spinner1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <Spinner
        android:id="@+id/spinner2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <Button
        android:id="@+id/button5"
        android:layout_width="190dp"
        android:layout_height="wrap_content"
        android:text="馬達A" />

</LinearLayout>
然後主程式碼:
package com.test;

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

import android.app.Activity;
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.os.Bundle;
import android.provider.ContactsContract.CommonDataKinds.Im;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;

public class MenuActivityActivity extends Activity {
   
    public static final String TAG = "test";
    private static final int REQUEST_ENABLE_BT = 2;
    public static final String MyUUID = "00001101-0000-1000-8000-00805F9B34FB";
    private ConnectThread mConnectThread;
    private ConnectedThread mConnectedThread;
    private TextView text_View1 ;
   
    BluetoothAdapter mBluetoothAdapter;
    ArrayAdapter<String> bondedDevices;
    ArrayAdapter<String> foundedDevices;
   
    Button turnOnButton, showPairedDevicesButton, scanForDevicesButton,connectButton,RunMotorA;
    TextView text;    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        //=============== main.xml Set up =======================
        text_View1 = (TextView) findViewById(R.id.textView1);
        text = (TextView) findViewById(R.id.textView1);
        turnOnButton = (Button) findViewById(R.id.button1);
        showPairedDevicesButton = (Button) findViewById(R.id.button2);
        scanForDevicesButton = (Button) findViewById(R.id.button3);
        connectButton = (Button) findViewById(R.id.button4);
        RunMotorA = (Button) findViewById(R.id.button5);
       
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (mBluetoothAdapter != null) {text.setText("BlueTooth adapter found");}
       
        turnOnButton.setOnClickListener(new View.OnClickListener()  {
            public void onClick(View v) {
                turnOnBluetooth();
            }
        });

        showPairedDevicesButton.setOnClickListener(new View.OnClickListener()  {
            public void onClick(View v) {
                showPairedDevices();
            }
        });
       
        scanForDevicesButton.setOnClickListener(new View.OnClickListener()  {
            public void onClick(View v) {
                scanForDevices();
            }
        });
       
        connectButton.setOnClickListener(new View.OnClickListener()  {
            public void onClick(View v) {
                connectToDevice();
            }
        });
        RunMotorA.setOnClickListener(new View.OnClickListener()  {
            public void onClick(View v) {
                   int motor=0;    // NXT Port = 0:A Port , 1:B Port ,2:Port .....  
                   int power=50;
                   byte[] setCmd = new byte[13];
                        setCmd[0] = (byte) 0x80;
                        setCmd[1] = (byte) 0x04;
                        setCmd[2] = (byte) motor;
                        setCmd[3] = (byte) power;
                        setCmd[4] = (byte) 0x01;
                        setCmd[5] = (byte) 0x01;
                        setCmd[6] = (byte) 0x00;
                        setCmd[7] = (byte) 0x20;
                        setCmd[8] = (byte) 0x00;
                        setCmd[9] = (byte) 0x00;
                        setCmd[10] = (byte) 0x00;
                        setCmd[11] = (byte) 0x00;
                        setCmd[12] = (byte) 0x00;
                        long t2=0;            
                        while(1000>t2)
                        {
                            mConnectedThread.write(setCmd);
                            t2++;
                        }
            }
        });
        bondedDevices =  new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item);
        foundedDevices =  new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item);
    }
   
    public void turnOnBluetooth(){
        if (!mBluetoothAdapter.isEnabled()) {
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
        }
    }
   
    public void showPairedDevices(){
        Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
        // If there are paired devices
        if (pairedDevices.size() > 0) {
            // Loop through paired devices
            for (BluetoothDevice device : pairedDevices) {
                // Add the name and address to an array adapter to show in a ListView
                bondedDevices.add(device.getName() + "\n" + device.getAddress());
                Log.d("debug",device.getName() + "\n" + device.getAddress() );
            }
        }
        Spinner s1 = (Spinner) findViewById(R.id.spinner1);
        bondedDevices.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        s1.setAdapter(bondedDevices);
        s1.showContextMenu();
    }
   
 // Create a BroadcastReceiver for ACTION_FOUND
    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            // When discovery finds a device
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                // Get the BluetoothDevice object from the Intent
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                // Add the name and address to an array adapter to show in a ListView
                foundedDevices.add(device.getName() + "\n" + device.getAddress());
                refreshNewDevices();
            }
        }
    };

    public void refreshNewDevices(){
        Spinner s2 = (Spinner) findViewById(R.id.spinner2);
        foundedDevices.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        s2.setAdapter(foundedDevices);
        s2.showContextMenu();
    }
   
    public void scanForDevices(){
        // Register the BroadcastReceiver
        IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        registerReceiver(mReceiver, filter); // Don't forget to unregister during onDestroy
        mBluetoothAdapter.startDiscovery();
    }

    public synchronized void connectToDevice(){
        Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
        BluetoothDevice stvorka = null;
        int t=0; // Device Count
        if (pairedDevices.size() > 0) {
            // Loop through paired devices
            for (BluetoothDevice device : pairedDevices) {
              //  if(device.getName().equals("stvorka"))
              //  stvorka = mBluetoothAdapter.getRemoteDevice(device.getAddress());
                  mConnectThread = new ConnectThread(device);
                  mConnectThread.start();
                  text_View1.setText(device.getAddress()+""+ t);
                  t++;     
            }
        }
        //  Start the thread to connect with the given device
        //  mConnectThread = new ConnectThread(stvorka);
        //  mConnectThread.start();
        //  text_View1.setText(stvorka.getName());
    }
   
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(requestCode == REQUEST_ENABLE_BT){
                if(resultCode == Activity.RESULT_OK){
                        text.setText("Bluetooth enabled");
                }else if (resultCode == Activity.RESULT_CANCELED){
                        text.setText("Bluetooth not enabled");
                }
        }
    }
   
    /**
     * Start the ConnectedThread to begin managing a Bluetooth connection
     * @param socket  The BluetoothSocket on which the connection was made
     * @param device  The BluetoothDevice that has been connected
     */
    public synchronized void connected(BluetoothSocket socket, BluetoothDevice device) {
        // Cancel the thread that completed the connection
        if (mConnectThread != null) {mConnectThread.cancel(); mConnectThread = null;}
        // Cancel any thread currently running a connection
        if (mConnectedThread != null) {mConnectedThread.cancel(); mConnectedThread = null;}
        Log.d(TAG,"starting connecting to device");
        mConnectedThread = new ConnectedThread(socket);
        mConnectedThread.start();
    }

    public void move() {
        byte[] data = { 0x0c, 0x00, (byte) 0x80, 0x04, 0x02, 0x32, 0x07, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x00 };
        int motor = 0;
        if (motor == 0) {
            data[4] = 0x02;
        } else {
            data[4] = 0x01;
        }
        data[5] = 0x20;
        if(mConnectedThread != null)
                mConnectedThread.write(data);
        else
                Log.d(TAG,"mConnectedThread is NULL");
    }
   
    /**
     * This thread runs while attempting to make an outgoing connection
     * with a device. It runs straight through; the connection either
     * succeeds or fails.
     */
    private class ConnectThread extends Thread {
        private final BluetoothSocket mmSocket;
        private final BluetoothDevice mmDevice;
       
        public ConnectThread(BluetoothDevice device) {
            mmDevice = device;
            BluetoothSocket tmp = null;
           
            try {
                tmp = device.createRfcommSocketToServiceRecord(UUID.fromString(MyUUID));
            } catch (IOException e) {
                Log.d(TAG,"socket creation failed" ,e);
            }
            mmSocket = tmp;
        }
       
        @Override
        public void run() {
            setName("ConnectThread");
            Log.d(TAG,"running connected thread");
            mBluetoothAdapter.cancelDiscovery();
           
            try {
                mmSocket.connect();
                Log.d(TAG, "connection success");
            } catch (IOException e) {
                connectionFailed();
                Log.d(TAG,"connection failed" ,e);
                try {
                    mmSocket.close();
                } catch (IOException e1) {
                    Log.e(TAG,"connection failed" ,e);
                }
                return;
            }
            synchronized (MenuActivityActivity.this) {
                mConnectThread = null;
            }        
            connected(mmSocket, mmDevice);
        }
       
        public void cancel() {
            try {
                mmSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    /**
     * This thread runs during a connection with a remote device.
     * It handles all incoming and outgoing transmissions.
     */
    private class ConnectedThread extends Thread {
        private final BluetoothSocket mmSocket;
        private final InputStream mmInStream;
        private final OutputStream mmOutStream;
        public ConnectedThread(BluetoothSocket socket) {
            Log.d(TAG, "create ConnectedThread");
            mmSocket = socket;
            InputStream tmpIn = null;
            OutputStream tmpOut = null;
            // Get the BluetoothSocket input and output streams
            try {
                tmpIn = socket.getInputStream();
                tmpOut = socket.getOutputStream();
            } catch (IOException e) {
                Log.d(TAG, "temp sockets not created", e);
            }
            mmInStream = tmpIn;
            mmOutStream = tmpOut;
        }
        public void write(int i) {
            // TODO Auto-generated method stub   
        }
        @Override
        public void run() {
            Log.d(TAG, "run listening");
            byte[] buffer = new byte[1024];
            int bytes;
           
            // Keep listening to the InputStream while connected
            while (true) {
                try {
                    // Read from the InputStream
                    bytes = mmInStream.read(buffer);
                    Log.d(TAG, "listening.."+bytes);
                } catch (Exception e) {
                    Log.d(TAG, "disconnected");
                    connectionLost();
                    break;
                }
            }
        }

        /**
         * Write to the connected OutStream.
         * @param buffer  The bytes to write
         */
        public void write(byte[] buffer) {
            try {
               
                mmOutStream.write(buffer);
                Log.d(TAG, "sending to device"+buffer.toString());
            } catch (IOException e) {
                Log.d(TAG, "Exception during write", e);
            }
        }

        public void cancel() {
            try {
                mmSocket.close();
            } catch (IOException e) {
                Log.d(TAG, "close() of connect socket failed", e);
            }
        }
    }
   
    /**
     * Indicate that the connection was lost and notify the UI Activity.
     */
    private void connectionLost() {
        // Start the service over to restart listening mode
        MenuActivityActivity.this.connectToDevice();
    }
   
    /**
     * Indicate that the connection attempt failed and notify the UI Activity.
     */
    private void connectionFailed() {
        connectionLost();
    }
        @Override
        protected void onStart() {
                super.onStart();
        }
        @Override
        protected void onResume() {
                super.onResume();
        }
        @Override
        protected void onPause() {
                super.onPause();
        }
        @Override
        protected void onStop() {
                super.onStop();
        }
        @Override
        protected void onDestroy() {
                if(mReceiver != null)
                        unregisterReceiver(mReceiver); // Don't forget to unregister during onDestroy
                super.onDestroy();
        }
}