leJOS PC Project – Codice per il PC… (includere la libreria pccomm.jar)
public class Main extends JFrame implements Runnable { private DataInputStream dis; private JPanel contentPane; private JButton btnConnetti; private JTextArea txtrMessaggi; [...] public void attivaComunicazione() { try { NXTComm nxtComm = NXTCommFactory.createNXTComm(NXTCommFactory.BLUETOOTH); NXTInfo[] nxtInfo = nxtComm.search("NXT"); if (nxtInfo.length > 0) if (nxtComm.open(nxtInfo[0])) { btnConnetti.setEnabled(false); btnConnetti.setText("Connesso"); dis = new DataInputStream(nxtComm.getInputStream()); Thread thread = new Thread(this); thread.setDaemon(true); thread.start(); } } catch (Exception e) { JOptionPane.showMessageDialog(this, "Impossibile stabilire la connesisone"); } } @Override public void run() { boolean connected = true; while(connected) { try { txtrMessaggi.append(dis.readLine()+ "\n"); } catch (IOException e) { connected=false; } } }
leJOS NXT Project – Codice per l’NXT…
import java.io.DataOutputStream; import java.io.IOException; import lejos.nxt.comm.Bluetooth; import lejos.nxt.comm.NXTConnection; public class BTHTestNXT { public static void main(String[] args) { System.out.println("Attesa connessione Bluetooth..."); NXTConnection conn = Bluetooth.waitForConnection(); DataOutputStream dos = conn.openDataOutputStream(); System.out.println("Connesso"); boolean connesso = true; while (connesso) { try { dos.writeChars("Ciao sono il tuo NXT"); dos.flush(); try { Thread.sleep(1000); } catch (InterruptedException e) { } } catch (IOException e) { connesso = false; } } } }