Skip to content

Instantly share code, notes, and snippets.

@alexbonhomme
Created November 24, 2013 18:15
Show Gist options
  • Save alexbonhomme/7630361 to your computer and use it in GitHub Desktop.
Save alexbonhomme/7630361 to your computer and use it in GitHub Desktop.
This class implement some simple methods to write datas on a serial bus. This implementation used the RXTXComm library (http://rxtx.qbang.org/wiki/index.php/Download). This example is configured to use this `/dev/ttyACM0` port (may require some tweaks). Typically you could used this code to send/write some datas to an Arduino.
package fr.blckshrk.core.utils.serial;
import gnu.io.CommPortIdentifier;
import gnu.io.NoSuchPortException;
import gnu.io.SerialPort;
import gnu.io.SerialPortEvent;
import gnu.io.SerialPortEventListener;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class SerialArduino implements SerialPortEventListener {
SerialPort serialPort;
/** Buffered input stream from the port */
private InputStream input;
/** The output stream to the port */
private OutputStream output;
/** Milliseconds to block while waiting for port open */
private static final int TIME_OUT = 2000;
/** Default bits per second for COM port. */
private static final int DATA_RATE = 115200;
private String inputBuffer = "";
/**
*
*/
public boolean initialize() {
System.setProperty("gnu.io.rxtx.SerialPorts", "/dev/ttyACM0");
CommPortIdentifier portId = null;
try {
portId = CommPortIdentifier.getPortIdentifier("/dev/ttyACM0");
} catch (NoSuchPortException e1) {
System.err.println(e1.getMessage());
return false;
}
if (portId == null) {
System.err.println("Could not find COM port.");
return false;
}
try {
// open serial port, and use class name for the appName.
serialPort = (SerialPort) portId.open(this.getClass().getName(), TIME_OUT);
// set port parameters
serialPort.setSerialPortParams(DATA_RATE,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
//waiting for opening
Thread.sleep(2000);
// open the streams
input = serialPort.getInputStream();
output = serialPort.getOutputStream();
// add event listeners
serialPort.addEventListener(this);
serialPort.notifyOnDataAvailable(true);
return true;
} catch (Exception e) {
System.err.println(e.getMessage());
}
return false;
}
/**
* This should be called when you stop using the port.
* This will prevent port locking on platforms like Linux.
*/
public synchronized void close() {
if (serialPort != null) {
serialPort.removeEventListener();
serialPort.close();
}
}
/**
* This Method can be called to print a String
* to the serial connection
* @param msg
*/
public synchronized void write(String msg){
try {
output.write(msg.getBytes()); //write it to the serial
output.flush(); //refresh the serial
} catch (Exception e) {
System.err.println(e.getMessage());
}
}
/**
* This Method can be called to print a String
* to the serial connection
* @param msg
*/
public synchronized void writeln(String msg){
write(msg + '\n');
}
/**
* This method is called to read one byte
* @return
*/
public synchronized int read() {
int c = 0;
try {
c = input.read();
} catch (IOException e) {
System.err.println(e.getMessage());
}
return c;
}
/**
* This method is called to read a line terminated by '\n' or '\r\n'
* @return
*/
public synchronized String readln() {
String str = "";
int c = -1;
while ((c = read()) != '\n' && c != -1) {
if (c == '\r') {
continue;
}
str += (char) c;
}
return str;
}
/**
* This Method is called when a command is recieved
* and needs to be encoded
* @param com
*/
private synchronized void encodeCommand(String com){
//checks if the String starts with s for set
if (com.indexOf("s:") == 0) {
String id = com.substring(com.indexOf("s:") + 2, com.indexOf(",")); //remove the s, and store the "p1"
String value = com.substring(com.indexOf(",") + 1, com.length()); //store everything after the ","
if (id.equals("p1") && !value.equals("")) {//if it's my poti1 and it sends a value
String myValue = "s:s1," + value; //set the value to my servo1
writeln(myValue); //and send it via the serial
} else {
System.err.println("Not correct values");
}
}
}
/**
* This Method is called when Serialdata is recieved
*/
@Override
public synchronized void serialEvent (SerialPortEvent oEvent) {
if (oEvent.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
try {
int available = input.available();
for (int i = 0; i < available; i++) { //read all incoming characters
int receivedVal = input.read(); //store it into an int (because of the input.read method
if (receivedVal != 10 && receivedVal != 13) {//if the character is not a new line "\n" and not a carriage return
inputBuffer += (char)receivedVal; //store the new character into a buffer
} else if (receivedVal == 10) { //if it's a new line character
encodeCommand(inputBuffer); //call the method to encode the recieved command
inputBuffer = ""; //clear the buffer
}
}
} catch (Exception e) {
System.err.println(e.getMessage());
}
}
}
/**
* For debugging only
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
SerialArduino serial = new SerialArduino();
if (!serial.initialize()) {
System.err.println("Initialization failed.");
System.exit(-1);
}
System.out.println("Started");
for (int i = 0; i <= 255; i++) {
serial.writeln(i + " " + i + " " + i);
System.out.println("RGB: " + i + " " + i + " " + i);
Thread.sleep(10);
}
for (int i = 255; i >= 0; i--) {
serial.writeln(i + " " + i + " " + i);
System.out.println("RGB: " + i + " " + i + " " + i);
Thread.sleep(10);
}
for (int i = 0; i <= 255; i++) {
serial.writeln(i + " " + (255 - i) + " 0");
System.out.println("RGB: " + i + " " + (255 - i) + " 0");
Thread.sleep(10);
}
serial.close();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment