Ola galera do fórum sou novo nesse fórum, e se puder queria contar com ajuda de vvs para um pequeno problema q esta nas minhas mãos
O problema é o seguinte estou usando o java para desenvolver uma aplicação no modelo de um termômetro, ate aí tudo bem estava pesquisando na internet e encontrei algumas coisa sobre o assunto criei uma tela gráfica e com uma pesquisa consegui a classe q interliga ambos usando uma biblioteca rxtx, primeiro exemplo tudo bem, mais quando foi para eu pegar esse dado e jogar dentro do textarea encontrei um problema por mais q eu jogue esse dado dentro deuma variavle ele vai aparecer nulo em outra classe que eu chamar, eu quero pegar esse valor em uma outra classe, vou posta o código para q vcs possa ver como é que está,obrigado a todos ate a próxima.
:?:
Aruino+Java
R
2 Respostas
R
Classe que mostra o resultado dado pelo o Arduino
package ArduinoJava;
import gnu.io.CommPortIdentifier;
import gnu.io.PortInUseException;
import gnu.io.SerialPort;
import gnu.io.SerialPortEvent;
import gnu.io.SerialPortEventListener;
import gnu.io.UnsupportedCommOperationException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.TooManyListenersException;
/**
*
* @author Rodrigues
*/
public class JAvaduino_03 implements SerialPortEventListener {
String total = new String();
InputStream inputStream;
public void execute() {
String portName = getPortNameByOS();
CommPortIdentifier portId = getPortIdentifier(portName);
if(portId != null) {
try {
SerialPort serialPort = (SerialPort) portId.open(this.getClass().getName(), 2000);
inputStream = serialPort.getInputStream();
serialPort.addEventListener(this);
serialPort.notifyOnDataAvailable(true);
serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
}
catch (PortInUseException e) {}
catch (IOException e) {}
catch (UnsupportedCommOperationException e) {
e.printStackTrace();
}
catch (TooManyListenersException e) {}
} else {
System.out.println("Porta Serial não disponível");
}
}
/**
* Get The port name
**/
private String getPortNameByOS() {
String osname = System.getProperty("os.name","").toLowerCase();
if ( osname.startsWith("windows") ) {
// windows
return "COM4";
} else if (osname.startsWith("linux")) {
// linux
return "/dev/ttyS0";
} else if ( osname.startsWith("mac") ) {
// mac
return "???";
} else {
System.out.println("Sorry, your operating system is not supported");
System.exit(1);
return null;
}
}
/**
*Get the Port Identifier
**/
private CommPortIdentifier getPortIdentifier(String portName) {
Enumeration portList = CommPortIdentifier.getPortIdentifiers();
Boolean portFound = false;
while (portList.hasMoreElements()) {
CommPortIdentifier portId = (CommPortIdentifier) portList.nextElement();
if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
System.out.println("Available port: " + portId.getName());
if (portId.getName().equals(portName)) {
System.out.println("Found port: "+portName);
portFound = true;
return portId;
}
}
}
return null;
}
public void serialEvent(SerialPortEvent event) {
switch (event.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:
total ="";
readSerial();
System.out.println(total);
break;
}
}
/**
* Buffer to hold the reading
*/
private byte[] readBuffer = new byte[400];
private void readSerial() {
try {
int availableBytes = inputStream.available();
if (availableBytes > 0) {
// Read the serial port
inputStream.read(readBuffer, 0, availableBytes);
// Print it out
//System.out.println(
//new String(readBuffer, 0, availableBytes));
total = total+new String(readBuffer, 0, availableBytes);
}
} catch (IOException e) {
}
}
public static void main(String []args)throws Exception{
JAvaduino_03 main = new JAvaduino_03();
main.execute();
}
}
R
Classe da Aplicação gráfica
quero jogar o valor mostrado la dentro textarea e consequentemente alterar o porcentagem da barra, progressBar
package ArduinoJava;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.event.*;
public class PROG {
public static void main(String[] args){
JFrame frame = new ProgressBarFrame();
frame.show();
}
}
class ProgressBarFrame extends JFrame
{ public ProgressBarFrame()
{ setTitle("Terminal de Tempetaura Arduino");
setSize(350, 200);
addWindowListener(new WindowAdapter()
{ public void windowClosing(WindowEvent e)
{ System.exit(0);
}
} );
Container contentPane = getContentPane();
textArea = new JTextArea();
JPanel panel = new JPanel();
startButton = new JButton("VER");
progressBar = new JProgressBar();
progressBar.setBackground(Color.yellow);
progressBar.setStringPainted(true);
panel.add(startButton);
panel.add(progressBar);
contentPane.add(new JScrollPane(textArea), "Center");
contentPane.add(panel, "South");
startButton.addActionListener(
new ActionListener()
{ public void actionPerformed(ActionEvent event)
{ JAvaduino_03 main = new JAvaduino_03();
progressBar.setMaximum(100);
activity = new SimulatedActivity(Integer.parseInt(main.total));
activity.start();
activityMonitor.start();
startButton.setEnabled(false);
}
});
activityMonitor = new javax.swing.Timer(1000,new ActionListener()
{ public void actionPerformed(ActionEvent event)
{ int current = activity.getCurrent();
textArea.append(current + "\n");
progressBar.setValue(current);
if (current == activity.getTarget())
{ //activityMonitor.stop();
startButton.setEnabled(false);
}
}
});
}
private javax.swing.Timer activityMonitor;
private JButton startButton;
private JProgressBar progressBar;
private JTextArea textArea;
private SimulatedActivity activity;
}
class SimulatedActivity extends Thread
{ public SimulatedActivity(int t)
{
current = 0;
target = t;
}
public int getTarget()
{ return target;
}
public int getCurrent()
{ return current;
}
public void run()
{ while (current < target && !interrupted())
{ try
{ sleep(100);
}
catch(InterruptedException e)
{ return;
}
current++;
}
}
private int current;
private int target;
}
Criado 27 de setembro de 2011
Ultima resposta 27 de set. de 2011
Respostas 2
Participantes 1