martes, 3 de mayo de 2016

Proyecto Arduino ethernet SD + consola en Java 1/X

     Este proyecto vengo pensándolo desde hace mucho tiempo pero es desde hace poco tiempo que me he puesto con él enserio. Se trata de comunicarse con Arduino usando la tarjeta ethernet SD usando un navegador cualquiera y la conexión USB con una consola programada en Java.

     El concepto del proyecto estaría resumido en el siguiente esquema que podéis descargar desde mi web por si queréis hacer modificaciones:


     El proyecto no está completo. Lo estoy desarrollando de momento solo bajo Linux. Ubuntu para ser exactos. Esto es solo una aproximación. De hecho, esta versión tiene  dos fallos al presentar en la consola los datos enviados y recibidos, y al capturar el evento de datos recibidos siempre da como positivo a tal evento. Cosas muy raras. A lo mejor me puedes ayudar a solucionar estos problemillas.

     El siguiente código es el que estará almacenado en Arduino:


#include <Ethernet.h>
#include <SPI.h>

const int BLUE    =5;
const int GREEN   =6;
const int RED     =7;
const int SPEAKER =3;
// Configuration Night Light
const int RLED    =9;    //Red LED on pin 9 (PWM)
const int LIGHT   =0;    //Lght Sensor on Analog Pin 0
const int MIN_LIGHT=200; //Minimum expected light value
const int MAX_LIGHT=900; //Maximum Expected Light value
int val = 0;             //variable to hold the analog reading
String AnalogLed;

//For controlling LEDS and the speaker
//If you want to control additional things, add variables to control them here.
int freq = 0;
int pin;
char dato[16];
String inString = "";

//Set to your MAC address!
//It should be on your sticker. If you can't find it,
//make one up, or use this one.
byte mac[] = { 0x90, 0xA2, 0xDA, 0x00, 0x4A, 0xE0 };
// the dns server ip
IPAddress dnServer(192, 168, 0, 1);
// the router's gateway address:
IPAddress gateway(192, 168, 0, 1);
// the subnet:
IPAddress subnet(255, 255, 255, 0);
// Set the static IP address to use if the DHCP fails to assign
IPAddress ip(192, 168, 0, 20);

//Start the server on port 80
EthernetServer server = EthernetServer(80); //port 80

boolean receiving = false; //To keep track of whether we are getting data.

void setup()
{
  Serial.begin(9600);

  pinMode(RED, OUTPUT);
  pinMode(GREEN, OUTPUT);
  pinMode(BLUE, OUTPUT);
  // Configuration Night Light
  pinMode(RLED, OUTPUT); //Set LED pin as output
   
  Ethernet.begin(mac, ip, dnServer, gateway, subnet);
  //Start the server
  server.begin();
  Serial.print("Server Started.\nLocal IP: ");
  Serial.println(Ethernet.localIP());

}

void loop()
{
  EthernetClient client = server.available();

  if (Serial.available() > 0)
  {
    // https://www.arduino.cc/en/Tutorial/StringToIntExample
    int inChar = Serial.read();
    if(isDigit(inChar))
    {
      inString += (char)inChar;
    }
    if(inChar == '\n')
    {
      Serial.print("Pin: ");
      pin = inString.toInt();
      Serial.println(pin);
      if (pin == 55)
        digitalWrite(7, !digitalRead(7));
      else
        digitalWrite(pin, !digitalRead(pin));
      inString = "";
    }
   
    delay(1000);
    for(int i=0; i<10; i++) {
      digitalWrite(7, !digitalRead(7));
      if (pin != 0)
        Serial.println(pin);
      delay(200);
    }
  }
     
  if (client)
  {
    //An HTTP request ends with a blank line
    boolean currentLineIsBlank = true;
    boolean sentHeader = false;

    while (client.connected())
    {
      if (client.available())
      {
        char c = client.read(); //Read from the incoming buffer
      
        if(receiving && c == ' ') receiving = false; //done receiving
        if(c == '?') receiving = true; //found arguments
      
        //This looks at the GET requests
        if(receiving)
        {
          //An LED command is specified with an L
          if (c == 'L')
          {
            Serial.print("Toggling Pin ");
            pin = client.parseInt();
            Serial.println(pin);
            digitalWrite(pin, !digitalRead(pin));
           
            delay(1000);
            for(int i=0; i<10; i++) {
              digitalWrite(pin, !digitalRead(pin));
              Serial.println(pin);
              delay(200);
            }
           
            break;
          }
          //A speaker command is specified with an S
          else if (c == 'S')
          {
            Serial.print("Setting Frequency to ");
            freq = client.parseInt();
            Serial.println(freq);
            if (freq == 0)
              noTone(SPEAKER);
            else
              tone(SPEAKER, freq);
            break;
          }
          //Add similarly formatted else if statements here
          //TO CONTROL ADDITIONAL THINGS
          else if (c == 'A')
          {
            if (val < 0 || val > 255)
            {
              val = 0;
              break;
            }
            val = client.parseInt();
            Serial.print("Dando brillo al led con valor analogico: ");
            Serial.println(val);
            analogWrite(RLED, val);                       //control the LED
            break;
          }
        }
      
        //Print out the response header and the HTML page
        if(!sentHeader)
        {
          //Send a standard HTTP response header
          client.println("HTTP/1.1 200 OK");
          client.println("Content-Type: text/html\n");
    
          //Red toggle button
          client.println("<form action='' method='get'>");
          client.println("<input type='hidden' name='L' value='7' />");
          client.println("<input type='submit' value='Toggle Red' />");
          client.println("</form>");
    
          // Green toggle button
          client.println("<form action='' method='get'>");
          client.println("<input type='hidden' name='L' value='6' />");
          client.println("<input type='submit' value='Toggle Green' />");
          client.println("</form>");
    
          //Blue toggle button
          client.println("<form action='' method='get'>");
          client.println("<input type='hidden' name='L' value='5' />");
          client.println("<input type='submit' value='Toggle Orange' />");
          client.println("</form>");
    
          //Speaker frequency slider
          client.println("<form action='' method='get'>");
          client.print("<input type='range' name='S' min='0' max='1000' step='100' value='0'/>");
          client.println("<input type='submit' value='Set Frequency' />");
          client.println("</form>");
         
          // Control de salida analgica
          client.println("<form action='' method='get'>");
          client.println("Introduzca un valor para la salida analogica (0-255): <input type='text' name='A' min='0' max='255' value='0' />");
          //client.println("Introduzca un valor para la salida analogica (0-255): <input type='text' name='A' min='0' max='255' value='"+String(val)+"' />");
          client.println("<input type='submit' value='Set Analogic Blue Light' />");
          client.println("</form>");         
    
          //Add additional forms forms for controlling more things here.
         
          sentHeader = true;
        }
 
        if (c == '\n' && currentLineIsBlank) break;

        if (c == '\n')
        {
          currentLineIsBlank = true;
        }
        else if (c != '\r')
        {
          currentLineIsBlank = false;
        }
      }
    }
    delay(100); //Give the web browser time to receive the data
    client.stop(); //Close the connection:
  }
}


     Es una versión un poco extendida del código expuesto en GitHub control_led_speaker.ino. Solo que le he puesto que trate los datos recibidos por el puerto serie (a la postre USB, en Linux '/dev/ttyUSB0') y que devuelva por el puerto serie el mismo dato enviado por consola desde el PC. Puedes descargar el código desde mi web.

     El código Java es el siguiente:

import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;
import gnu.io.SerialPortEvent;
import gnu.io.SerialPortEventListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 *//**
 * @author mario
 */
public class JAVADUINO_Frame extends javax.swing.JFrame implements SerialPortEventListener {

    /**
     * Creates new form JAVADUINO_Frame
     */
    private static final String TURN_Verde="5";
    private static final String TURN_Verde_ON="6";
    private static final String TURN_Rojo_OFF="9";
    private static final String TURN_Rojo_ON="7";
    private String vBuffer;
   
    //Variables de conexión
    private OutputStream output = null;
    SerialPort serialPort;
    InputStream inputStream;    // Para leer el puerto serie
    /**
     * A BufferedReader which will be fed by a InputStreamReader converting the
     * bytes into characters making the displayed results codepage independent
     */
    private BufferedReader input;
   
    private InputStreamReader inputBuffer;
   
    private final String PUERTO = "/dev/ttyUSB0";
    private static final int TIMEOUT = 2000; //Milisegundos
    private static final int DATA_RATE = 9600;
   
    /*
     * Bloque de código para abrir del puerto serie
     */
    public SerialPort abrirPuertoSerie(final String nombrePuerto) throws Exception {
        CommPortIdentifier portId;  // puerto: nombre original.
        SerialPort puertoSerie;
        final Enumeration portEnum = CommPortIdentifier.getPortIdentifiers();   // listaPuertos: nombre original.
       
        while (portEnum.hasMoreElements()) {
            portId = (CommPortIdentifier) portEnum.nextElement();
            if (portId.getName().equals(nombrePuerto)) {
                puertoSerie = (SerialPort)portId.open("PuertoSerie", TIMEOUT);
                puertoSerie.setSerialPortParams(9600,
                                                SerialPort.DATABITS_8,
                                                SerialPort.STOPBITS_1,
                                                SerialPort.PARITY_NONE);
                return puertoSerie;
            }
        }
        throw new Exception("Nombre de puerto invalido");
    }
    /**
     * Manualmente un evento sobre el puerto serie. Lee los datos y los imprime.
     * Handle an event on the serial port. Read the data and print it.
     * Código extraido de http://playground.arduino.cc/Interfacing/Java
     * @param oEvent
     */
    @Override
    public synchronized void serialEvent(SerialPortEvent oEvent) {       
        // Web de Oracle que trata los eventos del puerto serie:
        // DATA_AVAILABLE: https://docs.oracle.com/cd/E17802_01/products/products/javacomm/reference/api/javax/comm/SerialPortEvent.html#DATA_AVAILABLE
        // DATA_AVAILABLE: https://docs.oracle.com/cd/E17802_01/products/products/javacomm/reference/api/constant-values.html#javax.comm.SerialPortEvent.DATA_AVAILABLE
        if (oEvent.getEventType() == SerialPortEvent.DATA_AVAILABLE && oEvent.getNewValue()) { // types int
            try {
               
                jTextAreaEventos.append("Capturado evento: " + Integer.toString(oEvent.getEventType()) + "\n");
                //String inputLine = input.readLine();
                //jAreaMensajes.append(inputLine + "\n");
                // Desde http://playground.arduino.cc/Interfacing/Java
                input = new BufferedReader(new InputStreamReader(serialPort.getInputStream()));
                jAreaMensajes.append(input + "\n");
                System.out.println(oEvent.getSource().toString());  // " " + input
            } catch (Exception e) {
                System.err.println(e.toString());
            }
        }
        // Ignore all the other eventTypes, but you should consider the other ones.
       
    }
   
    public JAVADUINO_Frame() {
        initComponents();
        inicializarConexion();
        jLabel1.setIcon(new ImageIcon("src/IconoLedRojoApagado.png"));
        jLabel3.setIcon(new ImageIcon("src/IconoLedAmarilloApagado.png"));   
        setTitle("JAVADUINO");
        jRadioButton1.setSelected(true);
    }
   
    public void inicializarConexion(){
        CommPortIdentifier puertoID=null;
        Enumeration puertoEnum = CommPortIdentifier.getPortIdentifiers();
       
        while(puertoEnum.hasMoreElements()){
            CommPortIdentifier actualPuertoID=(CommPortIdentifier) puertoEnum.nextElement();
            if(PUERTO.equals(actualPuertoID.getName())){
                puertoID = actualPuertoID;
                // jAreaMensajes.append("Puerto encontrado: " + puertoID.getName() + "\n");
                jLblDatosConexcion.setText("Puerto encontrado: " + PUERTO); // puertoID.getName()
                break;
            }
        }
       
        if(puertoID == null){
            mostrarError("No se puede conectar al puerto");
            System.exit(ERROR);
        }
       
        try{
            serialPort = (SerialPort) puertoID.open(this.getClass().getName(), TIMEOUT);
            //Parámetros puerto serie
            serialPort.setSerialPortParams(DATA_RATE, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
            output = serialPort.getOutputStream();
            //input = serialPort.getInputStream();
            jAreaMensajes.append("Puerto seleccionado: " + output.toString() + "\n");
           
            // add event listeners
            serialPort.addEventListener(this);
            serialPort.notifyOnDataAvailable(true);
            //serialPort.notifyOnOutputEmpty(rootPaneCheckingEnabled);    // Para evaluar la segunda forma de tratar el evento del puerto serie.
            jAreaMensajes.append("Preparado para capturar el evento: " + Integer.toString(SerialPortEvent.DATA_AVAILABLE) + "\n");
        } catch(Exception e){
            mostrarError(e.getMessage());
            System.exit(ERROR);
        }
    }
   
    /**
     * Esto debería ser llamado cuando paras de usar el puerto.
     * Esto prevendrá que el puerto se quede bloqueado en las plataformas Linux.
     * This should be called when you stop using the port. This will prevent
     * port locking on platforms like Linux.
     * Código extraido de http://playground.arduino.cc/Interfacing/Java
     */
    public synchronized void close() {
        if (serialPort != null) {
            serialPort.removeEventListener();
            serialPort.close();
        }
    }
   
    public void openPort() {
        CommPortIdentifier puertoID=null;
        Enumeration puertoEnum = CommPortIdentifier.getPortIdentifiers();
       
        while(puertoEnum.hasMoreElements()){
            CommPortIdentifier actualPuertoID=(CommPortIdentifier) puertoEnum.nextElement();
            if(PUERTO.equals(actualPuertoID.getName())){
                puertoID = actualPuertoID;
                // jAreaMensajes.append("Puerto encontrado: " + puertoID.getName() + "\n");
                jLblDatosConexcion.setText("Puerto encontrado: " + PUERTO); // puertoID.getName()
                break;
            }
        }
       
        if(puertoID == null){
            mostrarError("No se puede conectar al puerto");
            System.exit(ERROR);
        }
       
        if (serialPort == null) {
            try{
            serialPort = (SerialPort) puertoID.open(this.getClass().getName(), TIMEOUT);
            //Parámetros puerto serie
            serialPort.setSerialPortParams(DATA_RATE, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
            output = serialPort.getOutputStream();
            //input = serialPort.getInputStream();
            jAreaMensajes.append("Puerto seleccionado: " + output.toString() + "\n");
           
            // add event listeners
            serialPort.addEventListener(this);
            serialPort.notifyOnDataAvailable(true);
            //serialPort.notifyOnOutputEmpty(rootPaneCheckingEnabled);    // Para evaluar la segunda forma de tratar el evento del puerto serie.
            jAreaMensajes.append("Preparado para capturar el evento: " + Integer.toString(SerialPortEvent.DATA_AVAILABLE) + "\n");
            } catch(Exception e){
                mostrarError(e.getMessage());
                System.exit(ERROR);
            }
        }
    }
   
    private void enviarDatos(String datos){
        try{
            output.write(datos.getBytes());
            //output.write(7);
            jAreaMensajes.append("Enviado: " + datos.getBytes().toString() + "\n"); //  + datos.getBytes()
        } catch(Exception e){
            mostrarError("ERROR");
            System.exit(ERROR);
        }
    }   
   
    public void mostrarError(String mensaje){
        JOptionPane.showMessageDialog(this, mensaje, "ERROR", JOptionPane.ERROR_MESSAGE);
    }
   
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                         
    private void initComponents() {

        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jRadioButton1 = new javax.swing.JRadioButton();
        jRadioButton2 = new javax.swing.JRadioButton();
        jLabel3 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jAreaMensajes = new javax.swing.JTextArea();
        jLabelPort = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLblDatosConexcion = new javax.swing.JLabel();
        jScrollPane2 = new javax.swing.JScrollPane();
        jTextAreaEventos = new javax.swing.JTextArea();
        jButtonClosePort = new javax.swing.JButton();
        jButtonBorrarMensajes = new javax.swing.JButton();
        jButtonOpenPort = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                close(evt);
            }
        });

        jButton1.setText("OFF");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setText("ON ");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jLabel1.setText("jLabel1");
        jLabel1.setMaximumSize(new java.awt.Dimension(50, 50));
        jLabel1.setMinimumSize(new java.awt.Dimension(50, 50));
        jLabel1.setPreferredSize(new java.awt.Dimension(50, 50));

        jRadioButton1.setText("ROJO");

        jRadioButton2.setText("AMARILLO");

        jLabel3.setText("jLabel3");
        jLabel3.setMaximumSize(new java.awt.Dimension(50, 50));
        jLabel3.setMinimumSize(new java.awt.Dimension(50, 50));
        jLabel3.setPreferredSize(new java.awt.Dimension(50, 50));

        jAreaMensajes.setColumns(20);
        jAreaMensajes.setRows(5);
        jScrollPane1.setViewportView(jAreaMensajes);

        jTextAreaEventos.setColumns(20);
        jTextAreaEventos.setRows(5);
        jScrollPane2.setViewportView(jTextAreaEventos);

        jButtonClosePort.setText("Cerrar puerto");
        jButtonClosePort.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jButtonClosePortMouseClicked(evt);
            }
        });

        jButtonBorrarMensajes.setText("Borrar");
        jButtonBorrarMensajes.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jButtonBorrarMensajesMouseClicked(evt);
            }
        });

        jButtonOpenPort.setText("Abrir puerto");
        jButtonOpenPort.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jButtonOpenPortMouseClicked(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLblDatosConexcion)
                        .addGap(12, 12, 12)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 294, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabelPort, javax.swing.GroupLayout.PREFERRED_SIZE, 977, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                        .addGroup(layout.createSequentialGroup()
                            .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGroup(layout.createSequentialGroup()
                            .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 115, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                            .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 158, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                            .addComponent(jButtonClosePort, javax.swing.GroupLayout.PREFERRED_SIZE, 116, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                            .addComponent(jButtonBorrarMensajes, javax.swing.GroupLayout.PREFERRED_SIZE, 144, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                            .addComponent(jButtonOpenPort, javax.swing.GroupLayout.PREFERRED_SIZE, 136, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addComponent(jRadioButton1)
                        .addComponent(jRadioButton2)
                        .addGroup(layout.createSequentialGroup()
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 484, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                            .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 451, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jRadioButton1)
                .addGap(18, 18, 18)
                .addComponent(jRadioButton2)
                .addGap(61, 61, 61)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton1)
                    .addComponent(jButton2)
                    .addComponent(jButtonClosePort)
                    .addComponent(jButtonBorrarMensajes)
                    .addComponent(jButtonOpenPort))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 376, Short.MAX_VALUE)
                    .addComponent(jScrollPane1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLblDatosConexcion, javax.swing.GroupLayout.PREFERRED_SIZE, 17, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabelPort, javax.swing.GroupLayout.PREFERRED_SIZE, 16, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(0, 0, Short.MAX_VALUE))))
        );

        pack();
    }// </editor-fold>                       

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                        
        // TODO add your handling code here:
        if(jRadioButton1.isSelected()){
            enviarDatos(TURN_Rojo_ON);
            jLabel1.setIcon(new ImageIcon("src/IconoLedRojo.png"));
        }
        if(jRadioButton2.isSelected()){
            enviarDatos(TURN_Verde_ON);
            jLabel3.setIcon(new ImageIcon("src/IconoLedAmarillo.png"));
        }
    }                                       

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                        
        // TODO add your handling code here:
        if(jRadioButton1.isSelected()){
            enviarDatos(TURN_Rojo_OFF);
            jLabel1.setIcon(new ImageIcon("src/IconoLedRojoApagado.png"));
        }
        if(jRadioButton2.isSelected()){
            enviarDatos(TURN_Verde);
            jLabel3.setIcon(new ImageIcon("src/IconoLedAmarilloApagado.png"));
        }
    }                                       

    private void close(java.awt.event.WindowEvent evt) {                      
        // TODO add your handling code here:
        if (serialPort != null) {
            serialPort.removeEventListener();
            serialPort.close();
        }
    }                     

    private void jButtonClosePortMouseClicked(java.awt.event.MouseEvent evt) {                                             
        // TODO add your handling code here:
        close();
        jLabelPort.setText("Puerto encontrado: " + PUERTO);
    }                                            

    private void jButtonBorrarMensajesMouseClicked(java.awt.event.MouseEvent evt) {                                                  
        // TODO add your handling code here:
        jAreaMensajes.setText("");
        jTextAreaEventos.setText("");
    }                                                 

    private void jButtonOpenPortMouseClicked(java.awt.event.MouseEvent evt) {                                            
        // TODO add your handling code here:
        openPort();
    }                                           
  
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) throws Exception {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(JAVADUINO_Frame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(JAVADUINO_Frame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(JAVADUINO_Frame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(JAVADUINO_Frame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new JAVADUINO_Frame().setVisible(true);
            }
        });
    }
   
    // Variables declaration - do not modify                    
    private javax.swing.JTextArea jAreaMensajes;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButtonBorrarMensajes;
    private javax.swing.JButton jButtonClosePort;
    private javax.swing.JButton jButtonOpenPort;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabelPort;
    private javax.swing.JLabel jLblDatosConexcion;
    private javax.swing.JRadioButton jRadioButton1;
    private javax.swing.JRadioButton jRadioButton2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTextArea jTextAreaEventos;
    // End of variables declaration                  
}



     Es una modificación sobre un proyecto llamado JAVADUINO hecho con swing. Solo que el código expuesto trata el evento de datos en el buffer de entrada. También lo podéis descargar desde mi web. Tiene algunos fragmentos más de código comentado de las pruebas realizadas para tratar el evento del buffer y leer correctamente del puerto serie.

     El código está bastante comentado por lo que no veo necesario comentarlo externamente. Las webs que nombro ya comentan los códigos extendidamente y hay multitud de webs donde explican por separado cada una de las funciones. Además, es un código muy sencillo. Lo importante en este punto es: '¿que se quiere conseguir?' y el 'objetivo final' expuesto en el esquema. La web, con los archivos correspondientes, que servirá Arduino estará alojada en la tarjeta SD.

     Y esto es todo de momento sobre este proyecto.

Entradas relacionadas:

Entrada 124 - Programando una consola en Java con NetBeans 2/X 
Entrada 123 - Como crear un proyecto con Swing en NetBeans 8.X
Entrada 117 - Configuración de la shield ethernet SD de Arduino

     @eltiopacote
Listado entradas: http://www.pacovalverde.es/indice/

No hay comentarios:

Publicar un comentario