Olá,
estou com problema em ler dados de sensor de temperatura(já feita a conversão AD) pelo Microcontrolador através da porta serial e setando para jframe, como mostra o código abaixo :
package ComunicaçãoSerial;
//import javax.media.*;
import javax.swing.JDialog;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.plaf.metal.MetalLookAndFeel;
import java.io.*;
import java.util.*;
import gnu.io.*;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
/**
*
* @author est_bpantoja
*/
public class AcenderLed extends javax.swing.JFrame implements Runnable, SerialPortEventListener {
//cadastrar_Usuarios cadastrar;
// private Player p;
static String op;
private String peso;
private InputStream is;
private Scanner scan;
private Object inputPorta;
/** Creates new form Principal */
public AcenderLed() {
initComponents();
}
public String getPeso() {
return peso;
}
public void setPeso(String peso) {
this.peso = peso;
}
//retorna as portas disponíveis
public String[] ObterPortas() {
return portas;
}
//Copia portas para um Array
public void ListarPortas() {
int i = 0;
portas = new String[10];
while (listaDePortas.hasMoreElements()) {
CommPortIdentifier ips = (CommPortIdentifier) listaDePortas.nextElement();
portas[i] = ips.getName();
i++;
}
}
//pesquisa se a Porta existe
public boolean PortaExiste(String COMp) {
String temp;
boolean e = false;
while (listaDePortas.hasMoreElements()) {
CommPortIdentifier ips = (CommPortIdentifier) listaDePortas.nextElement();
temp = ips.getName();
if (temp.equals(COMp) == true) {
e = true;
}
}
return e;
}
//imprime as portas disponíveis
public void ImprimePortas() {
for (int i = 0; i < portas.length; i++) {
if (portas[i] != null) {
System.out.print(portas[i] + " ");
}
}
System.out.println(" ");
}
public void setPorta() {
Porta = "COM1";
baudrate = 19200;
timeout = 1000;
}
public void setPorta(String p, int b, int t) {
this.Porta = p;
this.baudrate = b;
this.timeout = t;
}
//habilita escrita de dados
public void HabilitarEscrita() {
this.Escrita = true;
this.Leitura = false;
}
//habilita leitura de dados
public void HabilitarLeitura() {
this.Escrita = false;
this.Leitura = true;
}
//Obtém o ID da PORTA
public void ObterIdDaPorta() {
try {
cp = CommPortIdentifier.getPortIdentifier(Porta);
if (cp == null) {
System.out.println("A " + Porta + " nao existe!");
System.out.println("ERRO!Abortando...");
IDPortaOK = false;
System.exit(1);
}
IDPortaOK = true;
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Erro durante o procedimento. STATUS" + e);
System.out.println("Erro durante o procedimento. STATUS" + e);
IDPortaOK = false;
System.exit(1);
}
}
//Abre a comunicação da porta
public void AbrirPorta() {
try {
porta = (SerialPort) cp.open("Serial", timeout);
PortaOK = true;
System.out.println("Porta aberta com sucesso!");
//configurar parâmetros
porta.setSerialPortParams(baudrate,
porta.DATABITS_8,
porta.STOPBITS_2,
porta.PARITY_NONE);
} catch (Exception e) {
PortaOK = false;
System.out.println("Erro ao abrir a porta! STATUS: " + e);
System.exit(1);
/*
private void TratarDados(String DadosLidos) {
if (Leitura==true) {
try {
Leitura = porta.etInputStream();
System.out.println("FLUXO OK!");
} catch (Exception e) {
System.out.println("Erro.STATUS: " + e );
}
try {
System.out.println("Enviando um byte para " + Porta );
System.out.println("Enviando : " + DadosLidos );
Leitura.read(DadosLidos.getBytes());
Thread.sleep(100);
Leitura.flush();
} catch (Exception e) {
System.out.println("Houve um erro durante o envio. ");
System.out.println("STATUS: " + e );
System.exit(1);
}
} else {
System.exit(1);
}
}
*/
}
}
//função que envie um bit para a porta serial
public void EnviarUmaString(String msg) {
if (Escrita == true) {
try {
saida = porta.getOutputStream();
System.out.println("FLUXO OK!");
} catch (Exception e) {
System.out.println("Erro.STATUS: " + e);
}
try {
System.out.println("Enviando um byte para " + Porta);
System.out.println("Enviando : " + msg);
saida.write(msg.getBytes());
Thread.sleep(100);
saida.flush();
} catch (Exception e) {
System.out.println("Houve um erro durante o envio. ");
System.out.println("STATUS: " + e);
System.exit(1);
}
} else {
System.exit(1);
}
}
//leitura de dados na serial
public void LerDados() {
// if (Escrita == true) {
if (Escrita == false) {
try {
entrada = porta.getInputStream();
} catch (Exception e) {
System.out.println("Erro de stream: " + e);
System.exit(1);
}
try {
porta.addEventListener(this);
} catch (Exception e) {
System.out.println("Erro de listener: " + e);
System.exit(1);
}
porta.notifyOnDataAvailable(true);
try {
threadLeitura = new Thread(this);
threadLeitura.start();
run();
} catch (Exception e) {
System.out.println("Erro de Thred: " + e);
}
}
}
//método RUN da thread de leitura
public void run() {
/*
*alguns testes
while (Escrita == false) {
scan = new Scanner(is);
String part = scan.nextLine();
// JLabel Temperatura
Temperatura.setText(part);
System.out.println(part);
}
//String[] part = scan.nextLine().split(peso, timeout);
// System.out.println(part[0]);
//tempLabel2.setText(part[0]);
* ?
*/
try {
Thread.sleep(5000);
} catch (Exception e) {
System.out.println("Erro. Status = " + e);
}
}
/
//função que fecha a conexão
public void FecharCom() {
try {
porta.close();
System.out.println("CONEXAO FECHADA>>FIM..");
} catch (Exception e) {
System.out.println("ERRO AO FECHAR. STATUS: " + e);
System.exit(0);
}
}
public void serialEvent(SerialPortEvent ev) {
switch (ev.getEventType()) {
case SerialPortEvent.BI:
case SerialPortEvent.OE:
case SerialPortEvent.FE:
case SerialPortEvent.PE:
case SerialPortEvent.CD:
case SerialPortEvent.CTS:
case SerialPortEvent.DSR:
case SerialPortEvent.RI:
case SerialPortEvent.OUTPUT_BUFFER_EMPTY:
break;
case SerialPortEvent.DATA_AVAILABLE:
byte[] bufferLeitura = new byte[20];
try {
while (entrada.available() > 0) {
nodeBytes = entrada.read(bufferLeitura);
}
String DadosLidos = new String(bufferLeitura);
// this.TratarDados(DadosLidos);
// this.setNivel(DadosLidos);
if (bufferLeitura.length == 0) {
System.out.println("Nada lido!");
} else if (bufferLeitura.length == 1) {
System.out.println("Apenas um byte foi lido!");
} else {
System.out.println(Dadoslidos);
}
} catch (Exception e) {
System.out.println("Erro durante a leitura: " + e);
}
System.out.println("n.o de bytes lidos : " + nodeBytes);
break;
}
/* outros testes
//gerenciador de eventos de leitura na serial
public void serialEvent(SerialPortEvent ev) {
switch (ev.getEventType()) {
case SerialPortEvent.BI:
case SerialPortEvent.OE:
case SerialPortEvent.FE:
case SerialPortEvent.PE:
case SerialPortEvent.CD:
case SerialPortEvent.CTS:
case SerialPortEvent.DSR:
case SerialPortEvent.RI:
case SerialPortEvent.OUTPUT_BUFFER_EMPTY:
break;
case SerialPortEvent.DATA_AVAILABLE:
byte[] bufferLeitura = new byte[20];
try {
while ( entrada.available() > 0 ) {
nodeBytes = entrada.read(bufferLeitura);
}
String DadosLidos = new String(bufferLeitura);
// this.TratarDados(DadosLidos);
// this.setNivel(DadosLidos);
if (bufferLeitura.length == 0)
{
System.out.println("Nada lido!");
} else if (bufferLeitura.length == 1 )
{
System.out.println("Apenas um byte foi lido!");
}
else
{
System.out.println(Dadoslidos);
}
} catch (Exception e) {
System.out.println("Erro durante a leitura: " + e );
}
//System.out.println("n.o de bytes lidos : " + nodeBytes );
break;
}
}
*/
}
private void bt_LigarActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
this.HabilitarEscrita();
this.EnviarUmaString("a");
}
private void bt_DesligarActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
this.HabilitarEscrita();
this.EnviarUmaString("b");
}
private void formWindowOpened(java.awt.event.WindowEvent evt) {
listaDePortas = CommPortIdentifier.getPortIdentifiers();
if (this.PortaExiste("COM1")) {
//this.setPorta("COM1", 9600, 2000);
this.setPorta("COM1", 19200, 2000);
this.HabilitarLeitura();
this.ObterIdDaPorta();
this.AbrirPorta();
this.LerDados();
//serial.FecharCom();
}
// TODO add your handling code here:
}
private void jMenuItem13ActionPerformed(java.awt.event.ActionEvent evt) {
JOptionPane.showMessageDialog(null, "o Software faz comunicação serial seria está configurado para enviar string 'a' e 'b' para micontrolador(ligar a e desligar),colocando um bits( 5V ) para pinagem 33 do PIC");
}
private void bt_TemperaturaActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
// aqui seria onde o botão irá atualizar temperatura do ambientes neste botão
//Temperatura.setText();
// System.out.println(bufferLeitura);
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
JFrame.setDefaultLookAndFeelDecorated(true);
JDialog.setDefaultLookAndFeelDecorated(true);
try {
UIManager.setLookAndFeel(new MetalLookAndFeel());
} catch (UnsupportedLookAndFeelException e) {
e.printStackTrace();
}
//Thread thread = new Thread(new Runnable() {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new AcenderLed().setVisible(true);
}
});
}
Este codigo enviar tb uma string para porta serial “a” e “b”.
Mas como eu disse o foco é pegar a temperatura lido pelo Microcontrolador e setar para layout atualizando com o botão. Se alguém puder me ajudar agradeço.
Abraços.
Breno Pantoja