atuaz
基本會員
積分 10
發文 2
註冊 2010-1-27
狀態 離線
|
#1 〔求助〕NB藍芽操控2台機器人(lego)同時動作..
各位資深前輩們好
小弟的專題報告將近
題目是用筆電連結藍芽操控2台機器人同時動作(前進後退)
由於時間緊迫 依小弟及朋友的能力只有辦法藉由書籍的範例程式碼來操作一台
我想詢問的是能否以修改程式碼的方式
來使筆電藍芽操控"兩台"機器人同時動作
(機器人為LEGO)
因為下面的程式碼是已經成功能連結操作一台機器人
希望資深前輩能不吝指教!!小弟非常感激!!
範例程式碼如下(已實作成功操控一台)
import lejos.pc.comm.*;
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
class MouseAction implements MouseListener //滑鼠事件
{
DataOutputStream dataOut;
int cmd;
public MouseAction(DataOutputStream _dataOut, int _cmd)
{
dataOut = _dataOut;
cmd = _cmd;
}//建構子
public void mousePressed(MouseEvent e) //滑鼠壓下事件
{
try{
dataOut.writeInt(cmd); //送出命令
dataOut.flush();
} catch(IOException i) {
JOptionPane.showMessageDialog(null, "Communication disconnected",
"Error", JOptionPane.ERROR_MESSAGE); //斷線錯誤警告
System.exit(1);
}
}//mousePressed
public void mouseReleased(MouseEvent e) //滑鼠放開事件
{
try{
dataOut.writeInt(0); //送出停止命令
dataOut.flush();
} catch(IOException i) {
JOptionPane.showMessageDialog(null, "Communication disconnected",
"Error", JOptionPane.ERROR_MESSAGE); //斷線錯誤警告
System.exit(1);
}
}//mouseReleased
public void mouseClicked(MouseEvent e) {}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
}//MouseAction
class Sample14_2 extends JFrame
{
int STOP = 0, FWD = 1, BACK = 2, LEFT = 3, RIGHT = 4; //宣告命令碼
JButton btForward;
JButton btBackward;
JButton btLeft;
JButton btRight;
NXTConnector conn;
DataOutputStream dataOut;
public Sample14_2()
{
conn = new NXTConnector();
if(!conn.connectTo("", "", NXTCommFactory.BLUETOOTH)) //連線到NXT
{
JOptionPane.showMessageDialog(null, "Cannot connect to NXT",
"Error", JOptionPane.ERROR_MESSAGE); //連線失敗訊息
System.exit(1);
}//if
dataOut = conn.getDataOut(); //取得輸出串流
//設定視窗
this.setTitle("COM"); //視窗標題為「COM」
this.setSize(320, 240); //視窗大小為320×240
this.setResizable(false); //固定視窗大小
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //視窗關閉時結束程式
this.getContentPane().setLayout(null); //視窗的Layout Manager為null
this.setLocationRelativeTo(null); //視窗在螢幕置中
//前進按鈕
btForward = new JButton("↑"); //宣告JButton
btForward.setBounds(100, 0, 100, 100); //設定大小位置
btForward.addMouseListener(new MouseAction(dataOut, FWD));//加入滑鼠事件
this.getContentPane().add(btForward); //將按鈕加入視窗
//後退按鈕
btBackward = new JButton("↓");
btBackward.setBounds(100, 100, 100, 100);
btBackward.addMouseListener(new MouseAction(dataOut, BACK));
this.getContentPane().add(btBackward);
//左轉按鈕
btLeft = new JButton("←");
btLeft.setBounds(0, 100, 100, 100);
btLeft.addMouseListener(new MouseAction(dataOut, LEFT));
this.getContentPane().add(btLeft);
//右轉按鈕
btRight = new JButton("→");
btRight.setBounds(200, 100, 100, 100);
btRight.addMouseListener(new MouseAction(dataOut, RIGHT));
this.getContentPane().add(btRight);
this.setVisible(true); //顯示視窗
}//建構子
public static void main(String args[])
{
Sample14_2 com = new Sample14_2();
}//main
}//Sample14_2
|
|