Oi pessoal, eu to com um probleminha aqui usando o Javacomm, acontece que “as vezes” eu consigo conectar na serial e ate mesmo receber alguns caracteres que eu envio, mas nao todos e nem sempre consigo receber algo, ja olhei alguns exemplos inclusive os que vem junto a API, mas nao consigo descobrir o porque deste problema, aqui vai o codigo que estou usando:
[code]import javax.comm.*;
import java.io.*;
import java.util.*;
public class Conexao implements SerialPortEventListener, CommPortOwnershipListener {
private InputStream is;
private OutputStream os;
private SerialPort sPort;
private CommPortIdentifier portID;
private Thread tLeitura;
private boolean open;
public Conexao(){
this.open = false;
}
public void abrirConexao(){
try {
portID = CommPortIdentifier.getPortIdentifier(“COM3”);
} catch (Exception e){
System.out.println(“Não encontrei esta porta.”+e);
}
try {
sPort = (SerialPort)portID.open(“Tst”,30000);
} catch (Exception e){
System.out.println(“Erro:”+e);
}
try {
setarParametros();
} catch (Exception e){
sPort.close();
System.out.println(“Erro ao setar os parametros.”);
}
try {
is = sPort.getInputStream();
os = sPort.getOutputStream();
} catch(Exception e){
sPort.close();
System.out.println(“Erro ao pegar os fluxos de IO”);
}
try {
sPort.addEventListener(this);
} catch (Exception e){
sPort.close();
System.out.println(“Erro:”+e);
}
sPort.notifyOnDataAvailable(true);
sPort.notifyOnBreakInterrupt(true);
try {
sPort.enableReceiveTimeout(3000);
} catch (Exception e){
}
portID.addPortOwnershipListener(this);
open = true;
}
public void fecharConexao(){
if (!open){
return;
}
if (sPort != null){
try {
os.close();
is.close();
} catch (Exception e) {
System.out.println("Erro ao fechar os fluxos. "+e);
}
sPort.close();
portID.removePortOwnershipListener(this);
}
open = false;
}
public boolean isOpen(){
return open;
}
public void enviarString(String msg){
try {
os.write(msg.getBytes());
//System.out.println("Enviei: "+msg);
} catch (IOException e) {
System.out.println(“Erro ao escrever no fluxo de saida”+e);
}
}
public void setarParametros(){
try {
sPort.setSerialPortParams(9600,sPort.DATABITS_8,sPort.STOPBITS_2,sPort.PARITY_NONE);
} catch (UnsupportedCommOperationException e) {
System.out.println(“Parametros incorretos”+e);
}
}
public void serialEvent(SerialPortEvent se) {
StringBuffer buff = new StringBuffer();
int novoDado = 0;
switch (se.getEventType()){
case SerialPortEvent.DATA_AVAILABLE:
System.out.println(“Estou dentro do evento.”);
while (novoDado != -1){
try {
novoDado = is.read();
if (novoDado == -1){
break;
}
if (’
’ == (char)novoDado){
buff.append(’
');
} else {
buff.append((char)novoDado);
}
} catch (Exception e) {
System.out.println("ERRO: "+e);
return;
}
}
System.out.println("RECEBI: "+new String(buff));
break;
case SerialPortEvent.BI:
System.out.println("
— BREAK RECEIVED —
");
break;
}
}
public void ownershipChange(int o) {
}
}[/code]
desde já, agradeço a todos por sua atenção e ajuda.
