Hola...
Ando en aprendizaje y me tomo tiempo hacer esto. Asi que les dejo este código de java para programa consola, que recibe por
puerto serial valores numéricos de 1 y 2 byte's y los muestra por consola. Nada Profesional, muy básico.
Hay una parte comentada (la INT16) que recibe dos bytes.
Lo dejo aquí, porque la mayoría de los ejemplos estan para trabajar en modo texto y ascii.
Con este podrías recibir directamente de un Microcontrolador o Equipo medición (Multímetro, Osciloscopio, etc.).
La parte que debe tomar tu atención es donde dice serialPort.setDTR(false); y serialPort.setRTS(true);
Tu equipo podría no necesitarlos o podría cambiar los parámetros (false y true).
Lo tengo configurado con: COM1 a 57600Baud, 8,n,1. Se puede cambiar esos valores. Me ha trabajado bien!!
Recuerda la librería: rxtx-2.1-7-bins-r2 debes tenerla para poder efectuar la comunicación rs232 en java.
import java.io.*;
import java.util.*;
import gnu.io.*;
//Original SimpleRead.java program. I modified it to show int receive values. :)
//I hope you can understand it. :)
////===========================================================================
//Class declaration
public class SimpleRead implements Runnable, SerialPortEventListener {
static CommPortIdentifier portId;
static Enumeration portList;
InputStream inputStream;
SerialPort serialPort;
Thread readThread;
////===========================================================================
public static void main(String[] args) {
boolean portFound = false;
String defaultPort = "COM1"; //Linux usa: /dev/term/a";
if (args.length > 0) {
defaultPort = args[0];
}
portList = CommPortIdentifier.getPortIdentifiers();
while (portList.hasMoreElements()) {
portId = (CommPortIdentifier) portList.nextElement();
if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
if (portId.getName().equals(defaultPort)) {
System.out.println("Found port: " + defaultPort);
portFound = true;
SimpleRead reader = new SimpleRead();
}
}
}
if (!portFound) {
System.out.println("port " + defaultPort + " not found.");
}
}
////===========================================================================
public SimpleRead() {
try {
serialPort = (SerialPort) portId.open("SimpleReadApp", 2000);
} catch (PortInUseException e) {}
try {
inputStream = serialPort.getInputStream();
} catch (IOException e) {}
try {
serialPort.addEventListener(this);
} catch (TooManyListenersException e) {}
serialPort.notifyOnDataAvailable(true);
try {
serialPort.setSerialPortParams(57600, SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
serialPort.setDTR(false);
serialPort.setRTS(true);
} catch (UnsupportedCommOperationException e) {}
readThread = new Thread(this);
readThread.start();
}
////===========================================================================
// Method declaration
public void run() {
try {
Thread.sleep(2000); //(20000);
} catch (InterruptedException e) {}
}
////===========================================================================
//fill buffer with numBytes bytes from is
public void readall(InputStream is, byte[] Buffer1, int numBytes) {
int tempRead=0;
while( tempRead < numBytes ) {
try {
tempRead = tempRead + is.read(Buffer1, tempRead, numBytes - tempRead);
} catch (IOException ex) {
ex.printStackTrace();
}
}
return;
}
////===========================================================================
//Method declaration
public void serialEvent(SerialPortEvent event) {
byte[] Buffer1 = new byte[200];
int int16value = 0;
int int8value = 0;
try {
while (inputStream.available() > 0) {
////===========================================================================
//// INT16 Si usa esta comentar INT8
////===========================================================================
// readall(inputStream, Buffer1, 2); //put two bytes in buffer
// int16value = 256*(int)Buffer1[1] + (int)Buffer1[0];
// System.out.println(int16value);
// }
////===========================================================================
//// INT8 Si usa esta comentar INT16
////===========================================================================
readall(inputStream, Buffer1, 1); //put one bytes in buffer
int8value = 128*(int)Buffer1[1] + (int)Buffer1[0];
//'''Así muestra los números con signo
//System.out.println(int8value);
//'''Así muestra números sin signo
System.out.println(int8value & 0xFF);
}
} catch (IOException e) {}
}
}
Espero le sirva a alguien.
Me costo demasiado tiempo lograr recibir en modo numérico.
Pronto les paso uno en ambiente gráfico que recibe los trés, ascii, int16, int8.
Saludos para todos....