Skip to content

Instantly share code, notes, and snippets.

@tgoossens
Created February 14, 2013 11:19
Show Gist options
  • Save tgoossens/4952182 to your computer and use it in GitHub Desktop.
Save tgoossens/4952182 to your computer and use it in GitHub Desktop.
TestClasses for BTProtocol of p&o project 2013. BTInitiator runs on the PC and initiaties the bluetoothconnection. And opens a DataInputStream CommTest (receiver) runs on NXT and waits for incoming connection. USAGE: 1) startup NXT with CommTest 2) Press Right arrow to let CommTest wait for bluetooth connection 3) Startup BTInitiator
import java.io.IOException;
import java.io.OutputStream;
import lejos.pc.comm.NXTComm;
import lejos.pc.comm.NXTCommException;
import lejos.pc.comm.NXTCommFactory;
import lejos.pc.comm.NXTInfo;
/*
* RUNS ON PC
*/
public class BTInitiator {
public static void main(String[] args) {
NXTComm nxtComm = null;
try {
nxtComm = NXTCommFactory.createNXTComm(NXTCommFactory.BLUETOOTH);
NXTInfo nxtInfo = new NXTInfo(NXTCommFactory.BLUETOOTH, "NXT",
"00:16:53:0A:09:D6");
if (canConnect(nxtComm, nxtInfo, NXTComm.PACKET)) { // 2 is RAW MODE
OutputStream out = nxtComm.getOutputStream();
out.write(new byte[] { 10, 11, 12, 13, 7, 18, 19, 20 });
out.flush();
Thread.sleep(20000);
out.write(new byte[] { 10, 20, 30, 40, 050, 60, 70, 80});
out.flush();
out.close();
} else {
System.err.println("No connection");
}
} catch (NXTCommException | IOException | InterruptedException e) {
e.printStackTrace();
} finally {
try {
nxtComm.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static boolean canConnect(NXTComm comm, NXTInfo nxtInfo, int mode) {
try {
return comm.open(nxtInfo, mode);
} catch (NXTCommException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}
}
}
import java.io.*;
import lejos.nxt.*;
import lejos.nxt.comm.*;
/**
* sample of selecting channel at run time
* RUNS ON NXT
* */
public class CommTest {
public static void main(String[] args) {
LCD.drawString("right BT", 0, 0);
NXTConnection connection = null;
if (Button.waitForAnyPress() == Button.ID_RIGHT) {
LCD.drawString("waiting for BT", 0, 1);
connection = Bluetooth.waitForConnection();
} else {
LCD.drawString("waiting for USB", 0, 1);
connection = USB.waitForConnection();
}
DataInputStream in = connection.openDataInputStream();
LCD.clear();
int i = 0;
while (true) {
try {
int input = in.readByte();
LCD.drawInt(input, 0, i % 6);
i++;
Button.waitForAnyPress();
} catch (IOException e) {
System.out.println(" write error " + e);
Button.waitForAnyPress();
}
}
}
public static int byteArrayToInt(byte[] b) {
return b[3] & 0xFF | (b[2] & 0xFF) << 8 | (b[1] & 0xFF) << 16
| (b[0] & 0xFF) << 24;
}
public static byte[] intToByteArray(int a) {
return new byte[] { (byte) ((a >> 24) & 0xFF),
(byte) ((a >> 16) & 0xFF), (byte) ((a >> 8) & 0xFF),
(byte) (a & 0xFF) };
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment