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() '開啟
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
然後參考馬達跟超音波的範例: 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) { =>超音波
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 ;
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 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;
/**
* 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();
}
程式碼: 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 釋放
首先宣告
'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)
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
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表單一直顯示在圖層上面