Skip to content

Instantly share code, notes, and snippets.

@chrishannam
Created June 2, 2020 07:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chrishannam/78c1e5d7e18a114968c691e61e8eb5cd to your computer and use it in GitHub Desktop.
Save chrishannam/78c1e5d7e18a114968c691e61e8eb5cd to your computer and use it in GitHub Desktop.
Read from a serial port and extract JSON.
package uk.co.chrishannam;
import com.fazecast.jSerialComm.SerialPort;
import java.io.InputStream;
public class Main {
public static void main(String[] args) {
System.out.println("Opening serial");
SerialPort[] comPorts = SerialPort.getCommPorts();
SerialPort comPort;
char c = 'a';
for (SerialPort i : comPorts) {
if (i.getDescriptivePortName().equals("USB Serial")) {
System.out.println(i.getDescriptivePortName());
comPort = i;
comPort.openPort();
comPort.setComPortTimeouts(SerialPort.TIMEOUT_READ_SEMI_BLOCKING, 0, 0);
InputStream in = comPort.getInputStream();
try {
String jsonString = "";
boolean start = false;
for (int j = 0; j < 10000; ++j) {
c = (char) in.read();
if (c == '{') {
start = true;
jsonString = "";
jsonString = jsonString + c;
}
else if (start){
jsonString = jsonString + c;
}
if (c == '}') {
System.out.println(jsonString);
in.close();
break;
}
}
} catch (Exception e) {
e.printStackTrace();
}
comPort.closePort();
}
}
System.out.println("Complete!");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment