關於我自己

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();
        }
}

2012年5月15日 星期二

OPENGL Dev C++

Dev C++本身就有可以下載OpenGL ~然而剛才我卻白爛的去用最複雜的

跑去OpenGL下載dll元件去複製到Dev C++

之後才發現Dev C++本身就有了

介紹Open GL 最主要去讓你去算數學跑公式,藉由圖示跟動畫呈獻出來





2012年5月5日 星期六

用滑鼠座標偵測顏色

目的:
可以用滑鼠的座標取的顏色RGB
可利用在遊戲血條偵測
然後網頁可以利用只有火狐 ~ 因為火狐的CSS顏色是最標準的


程式碼:
Private Declare Function WindowFromPoint Lib "user32" (ByVal xPoint As Long, ByVal yPoint As Long) As Long
    Private Declare Function GetDC Lib "user32" (ByVal hwnd As Long) As Long
    Private Declare Function GetPixel Lib "gdi32" (ByVal hdc As Long, ByVal X As Long, ByVal y As Long) As Long
    Private Declare Function ReleaseDC Lib "user32" (ByVal hwnd As Long, ByVal hdc As Long) As Long
    Private Declare Function GetCursorPos Lib "user32" (lpPoint As POINTAPI) As Long
    Private Type POINTAPI
        X As Long
        y As Long
    End Type
     Private Declare Function SetWindowPos Lib "user32" (ByVal hwnd As Long, ByVal hWndInsertAfter As Long, ByVal X As Long, ByVal y As Long, ByVal cx As Long, ByVal cy As Long, ByVal wFlags As Long) As Long
Private Sub Timer1_Timer()
    Dim lngDC As Long
    Dim lngColor As Long
    Dim PtMouse As POINTAPI
    Dim hwnd As Long
    Dim lngX As Long
    Dim lngY As Long
     Dim r As Integer
     Dim g As Integer
     Dim b As Integer
     Dim IntR As Long
IntR = SetWindowPos(Me.hwnd, -1, 0, 0, 0, 0, 3)
    GetCursorPos PtMouse            '取滑鼠位置
    hwnd = WindowFromPoint(PtMouse.X - 20, PtMouse.y)  '取滑鼠位置元件的Handle 值
    lngX = PtMouse.X
    lngY = PtMouse.y
    lngDC = GetDC(hwnd)         '取該Handle值的DC
    lngColor = GetPixel(lngDC, lngX, lngY)  '取該滑鼠位置的顏色
    Text1 = "位置: x:" & lngX & ", y:" & lngY & " ; 顏色:" & lngColor & " ; hwnd : " & hwnd & vbCrLf
   
      r = lngColor Mod 256
    b = Int(lngColor / 65536)
    g = (lngColor - (b * 65536) - r) / 256
     If r = -1 Then
r = 0
End If
If g = -1 Then
g = 0
End If
If b = -1 Then
b = 0
End If
    Label1.Caption = r
    Label2.Caption = g
    Label3.Caption = b
    Picture1.BackColor = RGB(r, g, b)
    ReleaseDC hwnd, lngDC       '將DC 釋放
      
    End Sub

滑鼠事件

滑鼠事件:
1.滑鼠左右鍵
2.滑鼠移動位置
3.滑鼠拖曳

首先宣告
'Win32 Api
Private Declare Function SetCursorPos Lib "user32" (ByVal x As Long, ByVal y As Long) As Long
Private Declare Sub mouse_event Lib "user32" (ByVal dwFlags As Long, ByVal dx As Long, ByVal dy As Long, ByVal cButtons As Long, ByVal dwExtraInfo As Long)

Const MOUSEEVENTF_ABSOLUTE = &H8000
Const MOUSEEVENTF_MOVE = &H1
Const MOUSEEVENTF_LEFTDOWN = &H2
Const MOUSEEVENTF_LEFTUP = &H4
Const MOUSEEVENTF_MIDDLEDOWN = &H20
Const MOUSEEVENTF_MIDDLEUP = &H40
Const MOUSEEVENTF_RIGHTDOWN = &H8
Const MOUSEEVENTF_RIGHTUP = &H10
Private Const WHEEL_DELTA = 120
Private Const MOUSEEVENTF_WHEEL = &H800
Dim result As Boolean

result = SetCursorPos(40, 55)  '滑鼠會移到作標X =45 Y=55的位置

 mouse_event MOUSEEVENTF_LEFTDOWN Or MOUSEEVENTF_LEFTUP, 0, 0, 0, 0
'啟動滑鼠左鍵 按下去又放開

mouse_event MOUSEEVENTF_RIGHTDOWN Or MOUSEEVENTF_RIGHTUP, 0, 0, 0, 0
'啟動滑鼠右鍵 按下去又放開

 mouse_event MOUSEEVENTF_WHEEL, 0, 0, WHEEL_DELTA, 0
'滑鼠中間滾輪往上移

   SendKeys "^c"  'Ctrl+C  複製 Copy
 
  SendKeys "^v"   'Ctrl+V  貼上  Post

  SendKeys "^s"  'Ctrl+S   儲存 Save

接下來是拖曳部分:很簡單的說因為拖曳的理念是
點滑鼠左鍵不放,然後移動到一定的位置,再放開

例如:(滑鼠拖曳範例)

  Dim result As Boolean

  result = SetCursorPos(2, 55)

   mouse_event MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0

   result = SetCursorPos(3, 198)

   mouse_event MOUSEEVENTF_LEFTUP, 0, 0, 0, 0

滑鼠作標偵測

目的:滑鼠作標偵測,意思是到時候可以設置讓滑鼠自動執行重複的動作

例如:訂火車票,一直按到有車票,但是按鍵的作標幾乎都不變,就可以使用此偵測




程式碼:
Option Explicit
Private Type PointAPI
      X As Long
      y As Long
End Type
Dim MousePos As PointAPI

Private Declare Function GetCursorPos Lib "user32" (lpPoint As PointAPI) As Long
Private Declare Function SetWindowPos Lib "user32" (ByVal hwnd As Long, ByVal hWndInsertAfter As Long, ByVal X As Long, ByVal y As Long, ByVal cx As Long, ByVal cy As Long, ByVal wFlags As Long) As Long

Private Sub Timer1_Timer()

Dim IntR As Long
IntR = SetWindowPos(Me.hwnd, -1, 0, 0, 0, 0, 3)
GetCursorPos MousePos
    Text1 = MousePos.X
    Text2 = MousePos.y

End Sub

VB 6.0 按鍵側錄

程式碼:

Private Declare Function SetWindowPos Lib "user32" (ByVal hwnd As Long, ByVal hWndInsertAfter As Long, ByVal X As Long, ByVal y As Long, ByVal cx As Long, ByVal cy As Long, ByVal wFlags As Long) As Long

Private Declare Function GetAsyncKeyState Lib "user32" (ByVal vKey As Long) As Integer

Private Sub Timer1_Timer()

Dim IntR As Long
IntR = SetWindowPos(Me.hwnd, -1, 0, 0, 0, 0, 3)
For i = 1 To 400
KeyResult = GetAsyncKeyState(i)
If KeyResult = -32767 Then
       If i = 13 Then
       Text1.Text = Text1.Text + "(Enter)"
       Else
       Text1.Text = Text1.Text + Chr(i)
       End If
     End If
Next i

End Sub
以上大約是用
GetAsyncKeyState涵式=>得到按件執 Ascii
SetWindowPos涵式=>把From表單一直顯示在圖層上面

最後我並沒有加下面兩個涵式
Form1.Hide   =>將表單隱藏
App.TaskVisible = False  =>然程式無法在工具管理員看到此EXE

2012年3月31日 星期六

SMS 簡訊編碼說明


 
0791889623077715240C918896333589910008705032015352232E6211661F671F4E94670356DE5B
9C862DFF0C51FA4F865403500B98EF5427FF01FF1F4F6090A3664267097A7AFF1F
==============================================================================

07 91 889623077715 24 0C91 889633358991 00 08 70 50 32 01 53 52 23 2E

07 91 => 07等於SMSC資訊長度  91等於SMSC地址格式
889623077715 => 發送者的電話號碼
24 => 基本參數
0C  91 => 0C等於回復個數  91 回復格式地址
00 08=> 00等於普通GSM 08等於代表示UCS2編碼
889633358991 => 電話
70 50 32 01 53 52 = > 70等於2007年 50等於05月 32等於23日 01等於10點 53等於35分 52等於25秒
                      所以是2007年05月23日10點35分25秒
35 => 正常來說應該是08 時間區域號碼
2E => 編碼的長度 46 不過的長度必須在乘於2 所以等於96
6211 661F 671F 4E94 6703 56DE 5B9C 862D FF0C 51FA 4F86 5403 500B 98EF 5427 FF01FF1F4F6090A3664267097A7AFF1F

6211 = 我
661F = 星
671F = 期
4E94 = 五
6703 = 會
56DE = 回
5B9C = 宜
862D = 蘭
51FA = 出
4F86 = 來
5403 = 吃
500B = 個
98EF = 飯
5427 = 吧

2012年2月26日 星期日

齒輪比跟圓弧長跟RPM跟馬達極數

1.齒輪比:

1圈所謂360度 ~ 假設10個齒鋸 360/10=36

假設A轉一圈 ~ D會轉多少度呢?          由上面齒輪比公式16分之1度

360/16= 22.5度

2.圓弧長

假設我有一臺車 ~ 輪胎半徑為5公分 ~ 我要如何算我的移動距離呢?



所以輪胎移動90度代表車子移動了7.85公分

180度 = 15.7公分

1圈 = 360度 =  31.4公分

3.RPM                                                                                                      

RPM = 每分鐘轉速,英文RPM,全寫是Revolution(s) Per Minute

假設 RPM = 3600

意味1分鐘轉3600圈

1圈代表360度

如果我要算1秒呢?

1分鐘=60秒

所以3600/60=60圈

1秒轉60圈

套上面的弧長移動距離

那麼60*31.4=1884公分

1公尺=100公分

所以1884/100=18.84公尺

(PS:Lego轉速沒那個快 ~ 看之前篇就知道了)

馬達極數
每分鐘轉速(rpm)=頻率(Hz) X 60 (sec/min) X 2  / 極數

1Hz * 60S *2 /極數
1*60*2/2=60
1*60*2/4=30
1*60*2/6=20
1*60*2/8=15
1*60*2/12=10

2P=1HZ為60 RPM  
4P=1HZ為30 RPM  
6P=1HZ為20 RPM
8P=1HZ為15 RPM  
12P=1HZ為10 RPM 

假設用6P ~ 在程式下指令80Hz
80*60*2/6=1600
所以一分鐘轉1600圈

2012年2月25日 星期六

LEGO NXT Motor Bricx

 task main()
{
   ClearScreen( );    //要先清空螢幕
   int t1 = CurrentTick( );   //取時間點t1
   OnFwd(OUT_A, 100);
   Wait(60000);        //讓馬達轉1秒=1000
   Off(OUT_A);     //停止馬達
   int angle = MotorRotationCount(OUT_A); //讀取馬達角度
   int t2 = CurrentTick( );   //讀取時間點t2
   while(1){
         TextOut(0,LCD_LINE1,"angle="); //LCD第一行顯示文字「angle=」
         NumOut(50,LCD_LINE1,angle);    //LCD第一行中間顯示馬達轉角
         TextOut(0,LCD_LINE2,"time=");  //LCD第二行輸出文字
         NumOut(50,LCD_LINE2,t2-t1);    //LCD第二行中間顯示經過時間
     

  }
}

解說:
 OnFwd(OUT_A, 100);  以100%電力輸出
  Wait(60000);       60000等於1分鐘
 所呈現的結果 ~ 讓我有點小小的吃驚 ~ 因為代表還會有一些少許的誤差
 angle = -12009
 time = -5536
一分種轉12009度  12009/360=33.3583   一分鐘轉33圈
看看上面圖片第一行的 33 rpm 的數值
(PS:更正 發現到MotorRotationCount讀的數值 ~ 只能讀到12000多數值就掛了
為什麼會發現呢? 因為看實際去轉並沒有那麼慢 ~ 然後用一秒去測為816度
816/360= 2.2666圈 ~ 等於1秒至少會轉2圈 ~ 意味      60*2=120 一分鐘至少要120圈左右  真正2.666*60=136圈
所以實際等於一分鐘360圈 ~ 有可能跟電壓跟電源有關 ~ 要實際用三用電表去測才知道)

另外可以參考

轉動的數值比較不會那麼吃驚
吃驚是時間 竟然有5536 換算下來有5秒
究竟5秒是怎麼來的 ~ 是因為要停馬達A所以花了5秒嗎?  Off(OUT_A);     //停止馬達

著點要再看看為什麼原因導致誤差5秒 ~ 自己在看轉動的時候要到1分鐘的時候
馬達好像在前5秒就開始轉慢了 ~ 給我的感覺像下面圖片的01
我本來期待是02的圖式 ~可以瞬間停下來的說

2011年12月13日 星期二

線性代數Elementary Linear Algebra 第二章矩陣(共有七章)

再第二章講解矩陣

解反矩陣

應用: 密碼學

C++程式 有點懶得打 ~ 引用別的網站所以只提供網址:
http://hi.baidu.com/xxwl04108/blog/item/fddcd06ea59057dd81cb4a01.html

2011年12月10日 星期六

線性代數Elementary Linear Algebra 高斯消去法 C++ 第一章(共有七章)

首先先講解看到高斯消去法讓我想到國中的解聯立方程式

不過應該說廢話,幾乎根本一模一樣,最後管他的能用就好了
為什麼我會寫此文章呢? 因為以前學生時代看到數學老實說連看都不想看,覺得數學很難

但是程式越寫越多,用到演算法也越來越多,到後面也就想自然去了解數學
而寫著篇如果是以前我,看到著篇應該會欣喜若狂就覺得很有幫助

所以怕有很多像以前的我

大概會引用比較簡單,並會用程式去引用,還有為什麼學著個有什麼用途呢?

線性代數一共有七章 所以等我有空的時候會一個個章結慢慢補上

Code
應用: