Skip to content

Instantly share code, notes, and snippets.

@OEP
Created June 13, 2012 21:04
Show Gist options
  • Save OEP/2926497 to your computer and use it in GitHub Desktop.
Save OEP/2926497 to your computer and use it in GitHub Desktop.
Example -- Drive iRobot Create for 1 Second and Stop in Java
import java.io.IOException;
import java.io.OutputStream;
import gnu.io.CommPort;
import gnu.io.CommPortIdentifier;
import gnu.io.NoSuchPortException;
import gnu.io.PortInUseException;
import gnu.io.SerialPort;
import gnu.io.UnsupportedCommOperationException;
class DriveCreate {
public static void main(String args[]) {
try {
// Boilerplate stuff from RXTX example code.
CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier("/dev/rfcomm0");
CommPort commPort = portIdentifier.open("RDIS", 2000);
SerialPort serialPort = (SerialPort) commPort;
serialPort.setSerialPortParams(57600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
OutputStream out = serialPort.getOutputStream();
// Create Primitives as byte arrays
byte startup[] = { (byte) 128 };
byte full[] = { (byte) 132 };
byte goForward[] = { (byte) 137, (byte) 0, (byte) 200, (byte) 0x80, (byte) 0x00 };
byte stop[] = { (byte) 137, (byte) 0, (byte) 0, (byte) 0, (byte) 0 };
// Send the bytes.
out.write(startup);
Thread.sleep(1000);
out.write(full);
Thread.sleep(1000);
out.write(goForward);
Thread.sleep(1000);
out.write(stop);
// Cleanup
serialPort.close();
} catch (NoSuchPortException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (PortInUseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnsupportedCommOperationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
@OEP
Copy link
Author

OEP commented Jun 13, 2012

A note: RXTX will "discover" serial ports that look like "/dev/ttyS_", and our "/dev/rfcomm_" does not look like that so it thinks it's not a serial port. Therefore, you have to tell it explicitly that it is a serial port by running it like this:

java -Dgnu.io.rxtx.SerialPorts=/dev/rfcomm0 MyClass

Explained here: http://mailman.qbang.org/pipermail/rxtx/2008-July/9480809.html

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment