Last active
January 28, 2016 14:51
-
-
Save 456789123/e079f59100d1a298de59 to your computer and use it in GitHub Desktop.
Using a GUI control with java, I have the temperature reading with the LM35 and control of a fan that can be used in a cooling system or greenhouse.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const int ventilador = 11; /* Pino para o LED */ | |
const int sensor = 0; /* Sensor para leitura de temperatura LM35 */ | |
int numero = 0; | |
static float leitura_temp( ) | |
{ | |
float temp = 0; | |
int i = 0; | |
for( i = 0; i < 1000; i++ ) | |
{ | |
temp = temp + analogRead(sensor); | |
} | |
temp = temp / 1000; /* Media de cem leituras */ | |
temp = temp * ( 1.1 / 1024 ); /* Converte valor lido para tensão */ | |
temp = temp * 100; /* Converte para Graus = temperatura/(1/10mv) */ | |
return temp; | |
} | |
void formar_numero( int *cont, char *caracter ) | |
{ | |
switch( *cont ) | |
{ | |
case 0 : numero = ((*caracter - '0') * 100); | |
break; | |
case 1 : numero = ((*caracter - '0') * 10) + numero; | |
break; | |
case 2 : numero = (*caracter - '0') + numero; | |
break; | |
} | |
if( numero >= 255 ) | |
{ | |
numero = 255; | |
} | |
} | |
void setup( ) | |
{ | |
Serial.begin( 9600 ); /* Taxa de comunicacao de BaudRate em 9600 Bauds */ | |
pinMode( ventilador, OUTPUT ); /* Configura pino como saída */ | |
analogReference( INTERNAL ); /* Referencia de 1.1V UNO (1.1/1024=0,913mv) | |
0,913mv de precisão ou seja 0,09ºC( INTERNAL | |
1V1 Arduino Duemilanove) | |
*/ | |
} | |
void loop( ) | |
{ | |
float temp = leitura_temp( ); | |
if(Serial.available( )) /* Recebeu algum dado do computador */ | |
{ | |
char caracter = Serial.read( ); /* Armazena caractere lido */ | |
/* | |
Verificacao de seguranca para entrada no loop infinito | |
*/ | |
if( caracter == 'c' ) | |
{ | |
int cont = 0; | |
while(true) | |
{ | |
if(Serial.available( )) | |
{ | |
caracter = Serial.read( ); | |
/* | |
Verificar se o caractere ASCII e um digito entre 0 e 9 | |
*/ | |
if( caracter >= 48 && caracter <= 57 ) | |
{ | |
formar_numero( &cont, &caracter ); | |
cont++; | |
if( cont >= 3 ) | |
{ | |
break; | |
} | |
} else { break; } | |
} | |
} | |
} | |
} | |
Serial.print(" "); | |
Serial.print( temp ); | |
analogWrite( ventilador, numero ); | |
delay(10); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package janela; | |
import java.io.IOException; | |
import javax.swing.JFrame; | |
import javax.swing.UIManager; | |
public class ControleInterface { | |
public static void main(String[] args) throws IOException { | |
try { | |
UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel"); | |
} catch ( Exception e ) { | |
e.printStackTrace(); | |
} | |
JanelaGUI janela = new JanelaGUI( ); | |
janela.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); | |
janela.setTitle("Controle de temperatura"); | |
janela.setResizable(false); | |
janela.setBounds(100, 100, 450, 300); | |
janela.setVisible(true); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package janela; | |
import java.awt.Color; | |
import java.awt.Font; | |
import java.awt.event.ActionEvent; | |
import java.awt.event.ActionListener; | |
import java.io.IOException; | |
import java.nio.file.Files; | |
import java.nio.file.Path; | |
import java.nio.file.Paths; | |
import java.text.DecimalFormat; | |
import javax.swing.DefaultComboBoxModel; | |
import javax.swing.ImageIcon; | |
import javax.swing.JButton; | |
import javax.swing.JComboBox; | |
import javax.swing.JFrame; | |
import javax.swing.JLabel; | |
import javax.swing.JSlider; | |
import javax.swing.Timer; | |
import javax.swing.UIManager; | |
import javax.swing.event.ChangeEvent; | |
import javax.swing.event.ChangeListener; | |
import objetos.Porta; | |
import serial.SerialComm; | |
import enuns.ImagemEnumCaminho; | |
import enuns.NomeEnumBotao; | |
import enuns.SerialEnumPorts; | |
import enuns.TempEnumArquivo; | |
public class JanelaGUI extends JFrame implements ActionListener { | |
private static final long serialVersionUID = 7990983487834138108L; | |
private static Path dados = Paths.get(TempEnumArquivo.TEMPERATURA.getCaminho()); | |
private static SerialComm serial = new SerialComm( ); | |
private static Porta porta = new Porta( ); | |
private boolean ligar = true; | |
private static JLabel lblC = new JLabel( ); | |
private static JLabel nada = new JLabel(""); | |
private static String temper; | |
private static final int BAUDIS = 9600; | |
private static byte[] bytes; | |
private Timer timer; | |
public JanelaGUI( ) throws IOException { | |
porta.setPorta(SerialEnumPorts.COM0.getPorta()); | |
porta.setBaudis(BAUDIS); | |
setBackground(UIManager.getColor("Button.background")); | |
JLabel lblNewLabel_3 = new JLabel(""); | |
JLabel lblNewLabel = new JLabel("Ventilador"); | |
JLabel lblNewLabel_2 = new JLabel("Temperatura está em:"); | |
JLabel lblRotaoEstEm = new JLabel("Rotação está em:"); | |
final JComboBox<SerialEnumPorts> comboBox = new JComboBox<SerialEnumPorts>(); | |
final JLabel label = new JLabel("0%"); | |
final JButton btnLigar = new JButton(NomeEnumBotao.LIGAR.toString()); | |
final JSlider slider = new JSlider(JSlider.VERTICAL, 0, 255, 0); | |
lblNewLabel.setFont(new Font("Arial", Font.BOLD | Font.ITALIC, 16)); | |
lblNewLabel.setBounds(72, 97, 86, 32); | |
comboBox.setModel(new DefaultComboBoxModel<SerialEnumPorts>(SerialEnumPorts.values())); | |
comboBox.addActionListener(new ActionListener() { | |
@Override | |
public void actionPerformed(ActionEvent e) { | |
SerialEnumPorts portaSerial = (enuns.SerialEnumPorts) comboBox.getSelectedItem( ); | |
porta.setPorta(portaSerial.getPorta( )); | |
} | |
}); | |
comboBox.setBounds(265, 97, 168, 25); | |
JLabel lblNewLabel_1 = new JLabel("Porta de comunicação:"); | |
lblNewLabel_1.setFont(new Font("Arial", Font.BOLD | Font.ITALIC, 15)); | |
lblNewLabel_1.setBounds(264, 70, 168, 15); | |
label.setFont(new Font("Arial", Font.BOLD | Font.ITALIC, 15)); | |
label.setBounds(72, 165, 60, 15); | |
slider.addChangeListener( new ChangeListener() { | |
@Override | |
public void stateChanged(ChangeEvent arg0) { | |
String dados = "c"; | |
serial.enviaDados(dados); | |
try { | |
Thread.sleep(1); | |
} catch (InterruptedException e) { | |
e.printStackTrace(); | |
} | |
int valor = slider.getValue( ); | |
int percente = (int) (valor / 2.55); | |
label.setText(percente + "%"); | |
dados = valor + ""; | |
if(valor < 10) { | |
dados = "00" + valor; | |
} else if(valor < 100) { | |
dados = "0" + valor; | |
} else if(valor <= 0) { | |
dados = "000"; | |
} | |
serial.enviaDados(dados); | |
} | |
}); | |
slider.setBounds(19, 58, 41, 208); | |
btnLigar.addActionListener(new ActionListener() { | |
@SuppressWarnings("deprecation") | |
public void actionPerformed(ActionEvent arg0) { | |
if(ligar) { | |
ligar = false; | |
lblC.setText(temper + "° C"); | |
slider.setEnabled(true); | |
btnLigar.setLabel(NomeEnumBotao.DESLIGAR.toString()); | |
btnLigar.setForeground(new Color(150, 0, 0)); | |
serial.ControlePorta(porta.getPorta( ), porta.getBaudis( )); | |
} else { | |
ligar = true; | |
slider.setEnabled(false); | |
porta.setNomeBotao(NomeEnumBotao.LIGAR.toString()); | |
btnLigar.setForeground(new Color(0, 128, 0)); | |
btnLigar.setLabel(NomeEnumBotao.LIGAR.toString()); | |
serial.enviaDados("c"); | |
slider.setValue(0); | |
try { | |
Thread.sleep(1); | |
} catch (InterruptedException e) { | |
e.printStackTrace(); | |
} | |
serial.enviaDados("000"); | |
serial.close( ); | |
} | |
comboBox.setEnabled(ligar); | |
} | |
}); | |
btnLigar.setForeground(new Color(0, 128, 0)); | |
lblNewLabel_2.setFont(new Font("Arial", Font.BOLD | Font.ITALIC, 15)); | |
lblNewLabel_2.setBounds(265, 152, 154, 15); | |
lblRotaoEstEm.setFont(new Font("Arial", Font.BOLD | Font.ITALIC, 15)); | |
lblRotaoEstEm.setBounds(72, 138, 129, 29); | |
if(ligar) { | |
bytes = Files.readAllBytes(dados); | |
timer = new Timer(500, this); | |
timer.start(); | |
} else { lblC.setText( "0º C" ); } | |
lblC.setFont(new Font("Arial", Font.BOLD | Font.ITALIC, 15)); | |
lblC.setBounds(265, 179, 60, 15); | |
lblNewLabel_3.setIcon(new ImageIcon(ImagemEnumCaminho.IMAGEM.getCaminho( ))); | |
lblNewLabel_3.setBounds(-29, 0, 354, 52); | |
btnLigar.setBounds(333, 228, 100, 27); | |
nada.setBounds(0, 0, 0, 0); | |
add(lblNewLabel); | |
add(lblNewLabel_2); | |
add(lblRotaoEstEm); | |
add(lblNewLabel_1); | |
add(slider); | |
add(btnLigar); | |
add(label); | |
add(lblNewLabel_3); | |
add(comboBox); | |
add(lblC); | |
add(nada); | |
slider.setEnabled(false); | |
comboBox.setEnabled(true); | |
} | |
@Override | |
public void actionPerformed(ActionEvent e) { | |
DecimalFormat decimal = new DecimalFormat( "0.0" ); | |
try { | |
bytes = Files.readAllBytes(dados); | |
try { | |
JanelaGUI.temper = decimal.format(Double.parseDouble(new String(bytes))); | |
} catch ( NumberFormatException e1 ){ | |
lblC.setText( JanelaGUI.temper + "° C" ); | |
} | |
lblC.setText( JanelaGUI.temper + "° C" ); | |
add(lblC); | |
add(nada); | |
} catch (IOException e1) { | |
e1.printStackTrace(); | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package enuns; | |
public enum NomeEnumBotao { | |
LIGAR, DESLIGAR; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package serial; | |
import enuns.TempEnumArquivo; | |
import gnu.io.CommPortIdentifier; | |
import gnu.io.NoSuchPortException; | |
import gnu.io.SerialPort; | |
import gnu.io.SerialPortEvent; | |
import gnu.io.SerialPortEventListener; | |
import java.io.IOException; | |
import java.io.InputStream; | |
import java.io.OutputStream; | |
import java.nio.file.Files; | |
import java.nio.file.Path; | |
import java.nio.file.Paths; | |
import javax.swing.JOptionPane; | |
public class SerialComm implements SerialPortEventListener { | |
private SerialPort port; | |
private OutputStream serialOut; | |
private int taxa; | |
private String portaCOM; | |
private InputStream inputStream; | |
Path dados = Paths.get(TempEnumArquivo.TEMPERATURA.getCaminho()); | |
public void ControlePorta(String portaCOM, int taxa) { | |
this.portaCOM = portaCOM; | |
this.taxa = taxa; | |
this.initialize(); | |
} | |
private void initialize() { | |
try { | |
CommPortIdentifier portId = null; | |
try { | |
portId = CommPortIdentifier.getPortIdentifier(this.portaCOM); | |
} catch (NoSuchPortException npe) { | |
JOptionPane.showMessageDialog(null, | |
"Porta COM não encontrada.", "Porta COM", | |
JOptionPane.PLAIN_MESSAGE); | |
port.close(); | |
} | |
port = (SerialPort) portId.open(this.getClass().getName(), 500); | |
serialOut = port.getOutputStream(); | |
inputStream = port.getInputStream(); | |
port.addEventListener(this); | |
port.notifyOnDataAvailable(true); | |
port.setSerialPortParams(this.taxa, // taxa de transferência da | |
// porta serial | |
SerialPort.DATABITS_8, // taxa de 10 bits 8 (envio) | |
SerialPort.STOPBITS_1, // taxa de 10 bits 1 (recebimento) | |
SerialPort.PARITY_NONE); // receber e enviar dados | |
} catch (Exception e) { | |
e.printStackTrace(); | |
} | |
} | |
public void close() { | |
port.close(); | |
System.out.println("Fechou a porta!!!!"); | |
} | |
public void enviaDados(String opcao) { | |
try { | |
serialOut.write(opcao.getBytes());// escreve o valor na porta serial para ser | |
// enviado | |
Thread.sleep(5); | |
serialOut.flush(); | |
} catch (IOException | InterruptedException e) { | |
JOptionPane.showMessageDialog(null, | |
"Não foi possível enviar o dado. ", "Enviar dados", | |
JOptionPane.PLAIN_MESSAGE); | |
port.close(); | |
} | |
} | |
@Override | |
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: | |
byte[] readBuffer = new byte[5]; | |
try { | |
int numBytes = 0; | |
while (inputStream.available() > 0) { | |
numBytes = inputStream.read(readBuffer); | |
} | |
Files.write(dados, readBuffer); | |
} catch (IOException e) { } | |
break; | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package enuns; | |
public enum SerialEnumPorts { | |
COM0("/dev/ttyUSB0"), | |
COM1("/dev/ttyUSB1"), | |
COM2("/dev/ttyUSB2"), | |
COM3("/dev/ttyUSB3"), | |
COM4("/dev/ttyUSB4"), | |
COM5("/dev/ttyUSB5"), | |
COM6("/dev/ttyUSB6"), | |
COM7("/dev/ttyUSB7"), | |
COM8("/dev/ttyUSB8"); | |
private final String porta; | |
private SerialEnumPorts( String porta ) { | |
this.porta = porta; | |
} | |
public String getPorta() { | |
return porta; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package enuns; | |
public enum TempEnumArquivo { | |
/* Aqui é o caminho para o arquivo que ele irá pegar o arquivo temp.txt */ | |
TEMPERATURA("/home/tony/workspace/Catolica/src/temp.txt"); | |
private String caminho; | |
private TempEnumArquivo( String caminho ) { | |
this.caminho = caminho; | |
} | |
public String getCaminho( ) { | |
return caminho; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment