Sunday, January 26, 2014

Serial Communication: Arduino Esplora and Java with Swing - ColorPicker

It's a example to show communication between Arduino and PC running Java with RxTx library. The PC side implement javax.swing.JColorChooser to choice color, then send to Arduino Esplora via USB serial, then set LCD screen and RGB LED color accordingly. (It's another example using JavaFX interface)


In the PC side, it's JColorChooser (copied from http://examples.oreilly.com/jswing2/code/ch12/ColorPicker.java), once user selected color, the RGB bytes will be sent to Arduino using RXTX Java Library.

Before start coding, read the posts "Setup RxTx for Arduino and Java example" and "Create Java project using librxtx-java in Netbeans, work with Arduino".

Java code using Swing in PC side:
package javaswingcolorpicker;

import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;
import gnu.io.SerialPortEvent;
import gnu.io.SerialPortEventListener;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.Enumeration;
import javax.swing.JButton;
import javax.swing.JColorChooser;
import javax.swing.JFrame;

public class JavaSwingColorPicker extends JFrame {
    
    MyRxTx myRxTx;

    public JavaSwingColorPicker() {
        super("JColorChooser Test Frame");
        setSize(200, 100);
        final Container contentPane = getContentPane();
        final JButton go = new JButton("Show JColorChooser");
        go.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                Color c;
                c = JColorChooser.showDialog(
                        ((Component) e.getSource()).getParent(),
                        "Demo", Color.blue);
                contentPane.setBackground(c);

                byte byteR = (byte)(c.getRed());
                byte byteG = (byte)(c.getGreen());
                byte byteB = (byte)(c.getBlue() );
                
                try {
                    byte[] bytesToSent = 
                            new byte[]{byteB, byteG, byteR};
                    myRxTx.output.write(bytesToSent);
                    
                } catch (IOException ex) {
                    System.out.println(ex.toString());
                }
            }
        });
        contentPane.add(go, BorderLayout.SOUTH);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        
        myRxTx = new MyRxTx();
        myRxTx.initialize();
    }

    public static void main(String[] args) {
        JavaSwingColorPicker myColorPicker = new JavaSwingColorPicker();
        myColorPicker.setVisible(true);
        
    }

    class MyRxTx implements SerialPortEventListener {

        SerialPort serialPort;
        /**
         * The port we're normally going to use.
         */
        private final String PORT_NAMES[] = {
            "/dev/ttyACM0", //for Ubuntu
            "/dev/tty.usbserial-A9007UX1", // Mac OS X
            "/dev/ttyUSB0", // Linux
            "COM3", // Windows
        };
        private BufferedReader input;
        private OutputStream output;
        private static final int TIME_OUT = 2000;
        private static final int DATA_RATE = 9600;

        public void initialize() {
            CommPortIdentifier portId = null;
            Enumeration portEnum = CommPortIdentifier.getPortIdentifiers();

            //First, Find an instance of serial port as set in PORT_NAMES.
            while (portEnum.hasMoreElements()) {
                CommPortIdentifier currPortId
                        = (CommPortIdentifier) portEnum.nextElement();
                for (String portName : PORT_NAMES) {
                    if (currPortId.getName().equals(portName)) {
                        portId = currPortId;
                        break;
                    }
                }
            }
            if (portId == null) {
                System.out.println("Could not find COM port.");
                return;
            } else {
                System.out.println("Port Name: " + portId.getName() + "\n"
                        + "Current Owner: " + portId.getCurrentOwner() + "\n"
                        + "Port Type: " + portId.getPortType());
            }

            try {
                // open serial port, and use class name for the appName.
                serialPort = (SerialPort) portId.open(this.getClass().getName(),
                        TIME_OUT);

                // set port parameters
                serialPort.setSerialPortParams(DATA_RATE,
                        SerialPort.DATABITS_8,
                        SerialPort.STOPBITS_1,
                        SerialPort.PARITY_NONE);

                // open the streams
                input = new BufferedReader(
                        new InputStreamReader(serialPort.getInputStream()));
                output = serialPort.getOutputStream();

                // add event listeners
                serialPort.addEventListener(this);
                serialPort.notifyOnDataAvailable(true);
            } catch (Exception e) {
                System.err.println(e.toString());
            }
        }

        @Override
        public void serialEvent(SerialPortEvent spe) {
            if (spe.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
                try {
                    final String inputLine = input.readLine();
                    System.out.println(inputLine);
                } catch (Exception e) {
                    System.err.println(e.toString());
                }
            }
        }

        /**
         * This should be called when you stop using the port. This will prevent
         * port locking on platforms like Linux.
         */
        public synchronized void close() {
            if (serialPort != null) {
                serialPort.removeEventListener();
                serialPort.close();
            }
        }
    }

}
For the source code in Arduino Esplora, refer to last post "Send array of byte from PC to Arduino Esplora, in JavaFX - ColorPicker".


download filesDownload the files.

No comments:

Post a Comment