Showing posts with label USB. Show all posts
Showing posts with label USB. Show all posts

Wednesday, September 16, 2015

Java/JavaFX/jSSC control Arduino + 8x8 LED Matrix

It's a example to control Arduino Uno + 8x8 LED Matrix, from USB connected PC running Windows 10, programmed with Java + JavaFX + jSSC(java-simple-serial-connector).



Arduino Side:

Connection between Arduino Uno and 8x8 LED:


UnoSerialInMatrix.ino
// 2-dimensional array of row pin numbers:
const int row[8] = {
  2, 7, 19, 5, 13, 18, 12, 16
};

// 2-dimensional array of column pin numbers:
const int col[8] = {
  6, 11, 10, 3, 17, 4, 8, 9
};

// 2-dimensional array of pixels:
int pixels[8][8];

int incomingByte = 0;

void setup() {
  // initialize the I/O pins as outputs
  // iterate over the pins:
  for (int thisPin = 0; thisPin < 8; thisPin++) {
    // initialize the output pins:
    pinMode(col[thisPin], OUTPUT);
    pinMode(row[thisPin], OUTPUT);
    // take the col pins (i.e. the cathodes) high to ensure that
    // the LEDS are off:
    digitalWrite(col[thisPin], HIGH);
  }

  clearScr();

  Serial.begin(9600);
  
}

void loop() {
  if (Serial.available() > 0) {
    incomingByte = Serial.read();
    doProcess(incomingByte);
  }
  
  // draw the screen:
  refreshScreen();

}

const int SYNC_WORD = 0xFF;
const int ST_0_IDLE = 0;
const int ST_1_WAITX = 1;
const int ST_2_WAITY = 2;
const int ST_3_WAITB = 3;
int prc_State = ST_0_IDLE;
int dotX, dotY, dotB;

void doProcess(int b){
  switch(prc_State){
    case ST_0_IDLE:
        if(b == SYNC_WORD){
          prc_State = ST_1_WAITX;
          Serial.println("1");
        }
        break;
    case ST_1_WAITX:
        dotX = b;
        prc_State = ST_2_WAITY;
        Serial.println("2");
        break;
    case ST_2_WAITY:
        dotY = b;
        prc_State = ST_3_WAITB;
        Serial.println("3");
        break;
    case ST_3_WAITB:

        if(b == 1){
          pixels[dotY][dotX] = LOW;
        }else{
          pixels[dotY][dotX] = HIGH;
        }

        prc_State = ST_0_IDLE;
        Serial.println("0");
        break;
    default:
        prc_State = ST_0_IDLE;
  }
}

void clearScr(){
  for (int x = 0; x < 8; x++) {
    for (int y = 0; y < 8; y++) {
      pixels[x][y] = HIGH;
    }
  }
}

void refreshScreen() {
  // iterate over the rows (anodes):
  for (int thisRow = 0; thisRow < 8; thisRow++) {
    // take the row pin (anode) high:
    digitalWrite(row[thisRow], HIGH);
    // iterate over the cols (cathodes):
    for (int thisCol = 0; thisCol < 8; thisCol++) {
      // get the state of the current pixel;
      int thisPixel = pixels[thisRow][thisCol];
      // when the row is HIGH and the col is LOW,
      // the LED where they meet turns on:
      digitalWrite(col[thisCol], thisPixel);
      // turn the pixel off:
      if (thisPixel == LOW) {
        digitalWrite(col[thisCol], HIGH);
      }
    }
    // take the row pin low to turn off the whole row:
    digitalWrite(row[thisRow], LOW);
  }
}

PC Side:

Before start, you have to Prepare jSSC on your NetBeans project.

JavaFX_Matrix.java
package javafx_matrix;

import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.control.RadioButton;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.scene.text.Font;
import javafx.stage.Stage;
import jssc.SerialPort;
import static jssc.SerialPort.MASK_RXCHAR;
import jssc.SerialPortEvent;
import jssc.SerialPortException;
import jssc.SerialPortList;

public class JavaFX_Matrix extends Application {
    
    final private int NUM_X = 8;
    final private int NUM_Y = 8;
    
    SerialPort arduinoPort = null;
    ObservableList<String> portList;

    @Override
    public void start(Stage primaryStage) {
        
        //ComboBox for port selection
        detectPort();
        final ComboBox comboBoxPorts = new ComboBox(portList);
        comboBoxPorts.valueProperty()
                .addListener(new ChangeListener<String>() {

            @Override
            public void changed(ObservableValue<? extends String> observable, 
                    String oldValue, String newValue) {

                System.out.println(newValue);
                disconnectArduino();
                connectArduino(newValue);
            }

        });
        
        //
        
        final Label label = new Label("arduino-er.blogspot.com");
        label.setFont(Font.font("Arial", 24));
        
        Button btnExit = new Button("Exit");
        btnExit.setOnAction((ActionEvent event) -> {
            Platform.exit();
        });

        VBox vBoxInfo = new VBox();
        vBoxInfo.getChildren().addAll(label, btnExit);
        
        //Matrix of RadioButton
        VBox vBoxMatrix = new VBox();
        vBoxMatrix.setPadding(new Insets(10, 10, 10, 10));

        for(int y=0; y<NUM_Y; y++){
            
            HBox box = new HBox();
            for(int x=0; x<NUM_X; x++){
                MatrixButton btn = new MatrixButton(x, y);
                box.getChildren().add(btn);
            }
            vBoxMatrix.getChildren().add(box);
            
        }
        
        vBoxMatrix.widthProperty().addListener(new ChangeListener<Number>(){

            @Override
            public void changed(ObservableValue<? extends Number> observable, Number oldValue, Number newValue) {
                comboBoxPorts.setPrefWidth((double)newValue);
                btnExit.setPrefWidth((double)newValue);
            }
        });

        BorderPane borderPane = new BorderPane();
        borderPane.setTop(comboBoxPorts);
        borderPane.setCenter(vBoxMatrix);
        borderPane.setBottom(vBoxInfo);

        Scene scene = new Scene(borderPane, 300, 250);

        primaryStage.setTitle("Arduino-er");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
    
    @Override
    public void stop() throws Exception {
        disconnectArduino();
        super.stop();
    }
    
    private void detectPort(){
         
        portList = FXCollections.observableArrayList();
 
        String[] serialPortNames = SerialPortList.getPortNames();
        for(String name: serialPortNames){
            System.out.println(name);
            portList.add(name);
        }
    }
    
    public boolean connectArduino(String port){
        
        System.out.println("connectArduino");
        
        boolean success = false;
        SerialPort serialPort = new SerialPort(port);
        try {
            serialPort.openPort();
            serialPort.setParams(
                    SerialPort.BAUDRATE_9600,
                    SerialPort.DATABITS_8,
                    SerialPort.STOPBITS_1,
                    SerialPort.PARITY_NONE);
            serialPort.setEventsMask(MASK_RXCHAR);
            serialPort.addEventListener((SerialPortEvent serialPortEvent) -> {
                if(serialPortEvent.isRXCHAR()){            
                    //receive something for debug
                    try {
                        String st = serialPort.readString(serialPortEvent
                                .getEventValue());
                        System.out.println(st);
                        
                    } catch (SerialPortException ex) {
                        Logger.getLogger(JavaFX_Matrix.class.getName())
                                .log(Level.SEVERE, null, ex);
                    }
                    
                }
            });
            
            arduinoPort = serialPort;
            
            //Send dummy to clear buffer
            try {
                Thread.sleep(2000);
            } catch (InterruptedException ex) {
                Logger.getLogger(JavaFX_Matrix.class.getName())
                        .log(Level.SEVERE, null, ex);
            }
            sendDotArduino(0, 0, false);
            
            success = true;
        } catch (SerialPortException ex) {
            Logger.getLogger(JavaFX_Matrix.class.getName())
                    .log(Level.SEVERE, null, ex);
            System.out.println("SerialPortException: " + ex.toString());
        }

        return success;
    }
    
    public void disconnectArduino(){
        
        System.out.println("disconnectArduino()");
        if(arduinoPort != null){
            try {
                arduinoPort.removeEventListener();
                
                if(arduinoPort.isOpened()){
                    arduinoPort.closePort();
                }
                
                arduinoPort = null;
            } catch (SerialPortException ex) {
                Logger.getLogger(JavaFX_Matrix.class.getName())
                        .log(Level.SEVERE, null, ex);
            }
        }
    }
    
    public void sendDotArduino(int x, int y, boolean s){
        final byte SYNC_WORD = (byte)0xFF;
        if(arduinoPort != null){
            byte[] buffer = new byte[]{
                SYNC_WORD,
                (byte)x, 
                (byte)y, 
                (byte)(s ? 1 : 0)
            };

            try {
                arduinoPort.writeBytes(buffer);
            } catch (SerialPortException ex) {
                Logger.getLogger(JavaFX_Matrix.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    class MatrixButton extends RadioButton {

        public MatrixButton(int x, int y) {
            
            setOnAction((ActionEvent event) -> {
                
                RadioButton src = (RadioButton) event.getSource();    
                JavaFX_Matrix.this.sendDotArduino(x, y, src.isSelected());
                
            });
        }
    }

}


Next:
Raspberry Pi control Arduino + 8x8 LED Matrix, using Java/JavaFX/jSSC


- More example of Java/JavaFX/jSSC communicate with Arduino.

Sunday, September 13, 2015

Java + JavaFX + jSSC run on Raspberry Pi, control Arduino Uno

Last post show a example of Java + JavaFX + jSSC run on PC/Windows 10 developed in NetBeans IDE, to communicate with/control Arduino Uno. Here we remote run it on Raspberry Pi to communicate with/control Arduino Uno.

This video show how to create Remote Java SE Platform on NetBeans IDE run on Windows 10, and run it remotely on Raspberry Pi 2.


Host development platform:
OS: Windows 10
IDE: NetBeans IDE 8.0.2
Programming Language: Java + JavaFX + jSSC (refer last post Last Post)

Target platform:
Raspberry Pi 2
OS: Raspbian
IP: 192.168.1.110
Both Host development platform and Target platform in the same Network.

remark: due to something wrong on my Raspberry Pi 2 cannot detect monitor correctly, I have to edit /boot/config.txt to set framebuffer_width and framebuffer_height to 500x400. So the screen output may be differency to you.

Arduino Side:
Board: Arduino Uno
Connected to Raspberry Pi 2 with USB.
Program and Connection: (refer last post Last Post)


Related:
- Raspberry Pi control Arduino + 8x8 LED Matrix, using Java/JavaFX/jSSC

Tuesday, September 8, 2015

Example of using jSSC, communicate between JavaFX and Arduino Uno via USB Serial port

Prepare a simple sketch run on Arduino Uno to send a counting number to serial port, tested on Windows 10.

BlinkUSB.ino
/*
 * Send number to Serial
 */
int i = 0;

// the setup function runs once when you press reset or power the board
void setup() {
  // initialize digital pin 13 as an output.
  pinMode(13, OUTPUT);
  Serial.begin(9600);
}

// the loop function runs over and over again forever
void loop() {

  Serial.print(i);
  i++;
  
  digitalWrite(13, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1000);              // wait for a second
  digitalWrite(13, LOW);    // turn the LED off by making the voltage LOW
  delay(1000);              // wait for a second
}

Read last post to "Prepare jSSC - download and add library to NetBeans, and create project using jSSC library".

modify the java code, JavaFX_jssc_Uno.java
/*
 * Example of using jSSC library to handle serial port
 * Receive number from Arduino via USB/Serial and display on Label
 */
package javafx_jssc_uno;

import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.Scene;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import jssc.SerialPort;
import static jssc.SerialPort.MASK_RXCHAR;
import jssc.SerialPortEvent;
import jssc.SerialPortException;
import jssc.SerialPortList;

public class JavaFX_jssc_Uno extends Application {
    
    SerialPort arduinoPort = null;
    ObservableList<String> portList;
    
    Label labelValue;
     
    private void detectPort(){
         
        portList = FXCollections.observableArrayList();
 
        String[] serialPortNames = SerialPortList.getPortNames();
        for(String name: serialPortNames){
            System.out.println(name);
            portList.add(name);
        }
    }
    
    @Override
    public void start(Stage primaryStage) {
        
        labelValue = new Label();
        
        detectPort();
        final ComboBox comboBoxPorts = new ComboBox(portList);
        comboBoxPorts.valueProperty()
                .addListener(new ChangeListener<String>() {

            @Override
            public void changed(ObservableValue<? extends String> observable, 
                    String oldValue, String newValue) {

                System.out.println(newValue);
                disconnectArduino();
                connectArduino(newValue);
            }

        });
        
        VBox vBox = new VBox();
        vBox.getChildren().addAll(
                comboBoxPorts, labelValue);
        
        StackPane root = new StackPane();
        root.getChildren().add(vBox);
        
        Scene scene = new Scene(root, 300, 250);
        
        primaryStage.setTitle("Hello World!");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    public boolean connectArduino(String port){
        
        System.out.println("connectArduino");
        
        boolean success = false;
        SerialPort serialPort = new SerialPort(port);
        try {
            serialPort.openPort();
            serialPort.setParams(
                    SerialPort.BAUDRATE_9600,
                    SerialPort.DATABITS_8,
                    SerialPort.STOPBITS_1,
                    SerialPort.PARITY_NONE);
            serialPort.setEventsMask(MASK_RXCHAR);
            serialPort.addEventListener((SerialPortEvent serialPortEvent) -> {
                if(serialPortEvent.isRXCHAR()){
                    try {
                        String st = serialPort.readString(serialPortEvent
                                .getEventValue());
                        System.out.println(st);
                        
                        //Update label in ui thread
                        Platform.runLater(() -> {
                            labelValue.setText(st);
                        });
                        
                    } catch (SerialPortException ex) {
                        Logger.getLogger(JavaFX_jssc_Uno.class.getName())
                                .log(Level.SEVERE, null, ex);
                    }
                    
                }
            });
            
            arduinoPort = serialPort;
            success = true;
        } catch (SerialPortException ex) {
            Logger.getLogger(JavaFX_jssc_Uno.class.getName())
                    .log(Level.SEVERE, null, ex);
            System.out.println("SerialPortException: " + ex.toString());
        }

        return success;
    }
    
    public void disconnectArduino(){
        
        System.out.println("disconnectArduino()");
        if(arduinoPort != null){
            try {
                arduinoPort.removeEventListener();
                
                if(arduinoPort.isOpened()){
                    arduinoPort.closePort();
                }
                
            } catch (SerialPortException ex) {
                Logger.getLogger(JavaFX_jssc_Uno.class.getName())
                        .log(Level.SEVERE, null, ex);
            }
        }
    }

    @Override
    public void stop() throws Exception {
        disconnectArduino();
        super.stop();
    }
            
    public static void main(String[] args) {
        launch(args);
    }
    
}



Next:
- JavaFX + jSSC - read byte from Arduino Uno, read from Analog Input

Prepare jSSC - download and add library to NetBeans, and create project using it.

jSSC (Java Simple Serial Connector) is a library for working with serial ports from Java. jSSC support Win32(Win98-Win8), Win64, Linux(x86, x86-64, ARM), Solaris(x86, x86-64), Mac OS X 10.5 and higher(x86, x86-64, PPC, PPC64)

link: https://code.google.com/p/java-simple-serial-connector/

Here show how to download and add library to NetBeans, and create NetBeans project using jSSC library. Next post will show a javaFX example to communicate with Arduino Uno via USB Serial.

Prepare jSSC - java serial port communication library - Download and add library to NetBeans


Prepare jSSC - Create NetBeans project using jSSC library



Example of using Java + jSSC:
- Example of using jSSC, communicate between JavaFX and Arduino Uno via USB Serial port
- JavaFX + jSSC - read byte from Arduino Uno, read from Analog Input
JavaFX + jSSC - read byte from Arduino Uno, display in LineChart
Bi-direction communication between Arduino and PC using Java + jSSC
Java + JavaFX + jSSC run on Raspberry Pi, control Arduino Uno
Java/JavaFX/jSSC control Arduino + 8x8 LED Matrix
- Raspberry Pi control Arduino + 8x8 LED Matrix, using Java/JavaFX/jSSC

Friday, April 3, 2015

Get idVendor and idProduct of your Arduino/USB devices

To know the idVendor and idProduct of your Arduino/USB devices, in Linux system, we can use the dmesg command, to read messages from kernel ring buffer.


- with your Arduino/USB devices NOT connected, run the command to clear the buffer.
$ sudo dmesg -c

- Connect Arduino/USB devices, enter the command:
$ dmesg

- The latest connect device will be shown, include its idVendor and idProduct:

Tuesday, November 4, 2014

Use jSSC (Java Simple Serial Connector) on Windows 8.1

jSSC (Java Simple Serial Connector) is a library for working with serial ports from Java. jSSC support Win32(Win98-Win8), Win64, Linux(x86, x86-64, ARM), Solaris(x86, x86-64), Mac OS X 10.5 and higher(x86, x86-64, PPC.

My old post show how to Install and test java-simple-serial-connector with Arduino, running on Ubuntu and Netbeans IDE.

This video show how to use jSSC on Windows 8.1/Nerbeans IDE. Basically it is the same, with different COM port assignment.


The Java code is listed here. It send a message to Arduino Esplora via USB Serial port, COM3, using jSSC library.

package java_testjssc;
 
import jssc.SerialPort;
import jssc.SerialPortException;
 
public class Java_testjSSC {
 
    public static void main(String[] args) {
        SerialPort serialPort = new SerialPort("COM3");
        try {
            System.out.println("Port opened: " + serialPort.openPort());
            System.out.println("Params setted: " 
                + serialPort.setParams(9600, 8, 1, 0));
            System.out.println("\"Hello World!!!\" successfully writen to port: " 
                + serialPort.writeBytes("Hello World!!!".getBytes()));
            System.out.println("Port closed: " 
                + serialPort.closePort());
        }
        catch (SerialPortException ex){
            System.out.println(ex);
        }
    }
     
}

The Arduino side code, refer to the post "Serial communication between Arduino Esplora and PC".



Monday, March 10, 2014

Arduino + Raspberry Pi + Node.js

Cross-post with Hello Raspberry Pi: Communication between RAspberry Pi and Arduino, using Node.js.

This example demonstrate how to send data between Raspberry Pi and Arduino Esplora board via USB, using Node.js.


Node.js script run on Raspberry Pi.
//To install 'serialport' locally, enter the command:
//$ npm install serialport
//Otherwise, Error: Cannot find module 'serialport' will reported

var SerialPort = require("serialport").SerialPort
var serialPort = new SerialPort('/dev/ttyACM0', 
    {   baudrate: 9600,
        dataBits: 8,
        parity: 'none',
        stopBits: 1,
        flowControl: false
    });

serialPort.on("open", function () {
    console.log('open');
    serialPort.on('data', function(data) {
        console.log('data received: ' + data);
        });
    serialPort.write("Hello from Raspberry Pi\n", function(err, results) {
        console.log('err ' + err);
        console.log('results ' + results);
        });
});

Arduino side, (same as in the post "Serial communication between Arduino Esplora and PC").
#include <Esplora.h>
#include <TFT.h>
#include <SPI.h>
 
int prevSw1 = HIGH;
int incomingByte = 0;
String charsIn = "";
char printout[20];  //max char to print: 20
  
void setup() {
   
    EsploraTFT.begin();  
    EsploraTFT.background(0,0,0);
    EsploraTFT.stroke(255,255,255);  //preset stroke color
      
    //Setup Serial Port with baud rate of 9600
    Serial.begin(9600);
     
    //indicate start
    Esplora.writeRGB(255, 255, 255);
    delay(250);
    Esplora.writeRGB(0, 0, 0);
     
}
  
void loop() {
    int sw1 = Esplora.readButton(SWITCH_1);
    if(sw1 != prevSw1){
      if(sw1 == LOW){
        Serial.println("Hello from Arduino Esplora");
      }
      prevSw1 = sw1;
    }
     
    while (Serial.available()) {
      char charRead = Serial.read();
      charsIn.concat(charRead);
    }
    if(charsIn != ""){
      Serial.println("How are you, " + charsIn);
      charsIn.toCharArray(printout, 21);
      EsploraTFT.background(0,0,0);
      EsploraTFT.text(printout, 0, 10);
      charsIn = "";
    }
}

Tuesday, March 4, 2014

Bi-direction serial communication using java-simple-serial-connector

Last post "JavaFX + java-simple-serial-connector + Arduino" implement simple one way communication from PC run JavaFX to Arduino. This example implement bi-direction sending and receiving between PC and Arduino, using java-simple-serial-connector.



To implement receiving, we have to implement SerialPortEventListener, and add it with serialPort.addEventListener().

package javafx_jssc;

import java.io.UnsupportedEncodingException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.TextField;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import javafx.stage.WindowEvent;
import jssc.SerialPort;
import jssc.SerialPortEvent;
import jssc.SerialPortEventListener;
import jssc.SerialPortException;
import jssc.SerialPortList;

public class JavaFX_jSSC extends Application {

    SerialPort serialPort;
    ObservableList<String> portList;

    ComboBox comboBoxPorts;
    TextField textFieldOut, textFieldIn;
    Button btnOpenSerial, btnCloseSerial, btnSend;

    private void detectPort() {

        portList = FXCollections.observableArrayList();

        String[] serialPortNames = SerialPortList.getPortNames();
        for (String name : serialPortNames) {
            System.out.println(name);
            portList.add(name);
        }
    }

    @Override
    public void start(Stage primaryStage) {

        detectPort();

        comboBoxPorts = new ComboBox(portList);
        textFieldOut = new TextField();
        textFieldIn = new TextField();

        btnOpenSerial = new Button("Open Serial Port");
        btnCloseSerial = new Button("Close Serial Port");
        btnSend = new Button("Send");
        btnSend.setDisable(true);   //default disable before serial port open
        
        btnOpenSerial.setOnAction(new EventHandler<ActionEvent>() {

            @Override
            public void handle(ActionEvent t) {
                closeSerialPort();              //close serial port before open
                if(openSerialPort()){
                    btnSend.setDisable(false);
                }else{
                    btnSend.setDisable(true);
                }
            }
        });
        
        btnCloseSerial.setOnAction(new EventHandler<ActionEvent>() {

            @Override
            public void handle(ActionEvent t) {
                closeSerialPort();
                btnSend.setDisable(true);
            }
        });

        btnSend.setOnAction(new EventHandler<ActionEvent>() {

            @Override
            public void handle(ActionEvent t) {
                
                if(serialPort != null && serialPort.isOpened()){
                    try {
                        String stringOut = textFieldOut.getText();
                        serialPort.writeBytes(stringOut.getBytes());
                    } catch (SerialPortException ex) {
                        Logger.getLogger(JavaFX_jSSC.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }else{
                    System.out.println("Something wrong!");
                }
            }
        });

        VBox vBox = new VBox();
        vBox.getChildren().addAll(
                comboBoxPorts,
                textFieldOut,
                textFieldIn,
                btnOpenSerial,
                btnCloseSerial,
                btnSend);

        StackPane root = new StackPane();
        root.getChildren().add(vBox);

        Scene scene = new Scene(root, 300, 250);

        primaryStage.setOnCloseRequest(new EventHandler<WindowEvent>() {

            @Override
            public void handle(WindowEvent t) {
                closeSerialPort();
            }
        });

        primaryStage.setTitle("Hello World!");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }

    private boolean openSerialPort() {
        boolean success = false;
        
        if (comboBoxPorts.getValue() != null
                && !comboBoxPorts.getValue().toString().isEmpty()) {
            try {
                serialPort = new SerialPort(comboBoxPorts.getValue().toString());
                
                serialPort.openPort();
                serialPort.setParams(
                        SerialPort.BAUDRATE_9600,
                        SerialPort.DATABITS_8,
                        SerialPort.STOPBITS_1,
                        SerialPort.PARITY_NONE);
                
                serialPort.addEventListener(new MySerialPortEventListener());
                
                success = true;
            } catch (SerialPortException ex) {
                Logger.getLogger(JavaFX_jSSC.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        return success;
    }

    private void closeSerialPort() {
        if (serialPort != null && serialPort.isOpened()) {
            try {
                serialPort.closePort();
            } catch (SerialPortException ex) {
                Logger.getLogger(JavaFX_jSSC.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        
        serialPort = null;
    }
    
    class MySerialPortEventListener implements SerialPortEventListener {

        @Override
        public void serialEvent(SerialPortEvent serialPortEvent) {
            
            if(serialPortEvent.isRXCHAR()){
                try {
                    int byteCount = serialPortEvent.getEventValue();
                    byte bufferIn[] = serialPort.readBytes(byteCount);
                    
                    String stringIn = "";
                    try {
                        stringIn = new String(bufferIn, "UTF-8");
                    } catch (UnsupportedEncodingException ex) {
                        Logger.getLogger(JavaFX_jSSC.class.getName()).log(Level.SEVERE, null, ex);
                    }
                    textFieldIn.setText(stringIn);
                    
                } catch (SerialPortException ex) {
                    Logger.getLogger(JavaFX_jSSC.class.getName()).log(Level.SEVERE, null, ex);
                }
                
            }
            
        }
        
    }
}

Arduino Esplora side, refer to previous post.

Monday, March 3, 2014

JavaFX + java-simple-serial-connector + Arduino

This example implement a simple Java application using java-simple-serial-connector library (jSSC) , with JavaFX user interface, send bytes to Arduino Esplora via USB.



package javafx_jssc;

import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.TextField;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import jssc.SerialPort;
import jssc.SerialPortException;
import jssc.SerialPortList;

public class JavaFX_jSSC extends Application {
    
    ObservableList<String> portList;
    
    private void detectPort(){
        
        portList = FXCollections.observableArrayList();

        String[] serialPortNames = SerialPortList.getPortNames();
        for(String name: serialPortNames){
            System.out.println(name);
            portList.add(name);
        }
    }
    
    @Override
    public void start(Stage primaryStage) {
        
        detectPort();

        final ComboBox comboBoxPorts = new ComboBox(portList);
        final TextField textFieldOut = new TextField();
        Button btnSend = new Button("Send");
        
        btnSend.setOnAction(new EventHandler<ActionEvent>() {

            @Override
            public void handle(ActionEvent t) {

                if(comboBoxPorts.getValue() != null && 
                    !comboBoxPorts.getValue().toString().isEmpty()){
                    
                    String stringOut = textFieldOut.getText();
                    
                    try {
                        SerialPort serialPort = 
                            new SerialPort(comboBoxPorts.getValue().toString());                        
                        
                        serialPort.openPort();
                        serialPort.setParams(
                                SerialPort.BAUDRATE_9600,
                                SerialPort.DATABITS_8,
                                SerialPort.STOPBITS_1,
                                SerialPort.PARITY_NONE);
                        serialPort.writeBytes(stringOut.getBytes());
                        serialPort.closePort();
                        
                    } catch (SerialPortException ex) {
                        Logger.getLogger(
                            JavaFX_jSSC.class.getName()).log(Level.SEVERE, null, ex);
                    }
                    
                }else{
                    System.out.println("No SerialPort selected!");
                }
            }
        });
        
        VBox vBox = new VBox();
        vBox.getChildren().addAll(
                comboBoxPorts, 
                textFieldOut, 
                btnSend);
        
        StackPane root = new StackPane();
        root.getChildren().add(vBox);
        
        Scene scene = new Scene(root, 300, 250);
        
        primaryStage.setTitle("Hello World!");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
    
}


Arduino code in Esplora side (same as in the post "Serial communication between Arduino Esplora and PC").
#include <Esplora.h>
#include <TFT.h>
#include <SPI.h>

int prevSw1 = HIGH;
int incomingByte = 0;
String charsIn = "";
char printout[20];  //max char to print: 20
 
void setup() {
  
    EsploraTFT.begin();  
    EsploraTFT.background(0,0,0);
    EsploraTFT.stroke(255,255,255);  //preset stroke color
     
    //Setup Serial Port with baud rate of 9600
    Serial.begin(9600);
    
    //indicate start
    Esplora.writeRGB(255, 255, 255);
    delay(250);
    Esplora.writeRGB(0, 0, 0);
    
}
 
void loop() {
    int sw1 = Esplora.readButton(SWITCH_1);
    if(sw1 != prevSw1){
      if(sw1 == LOW){
        Serial.println("Hello from Arduino Esplora");
      }
      prevSw1 = sw1;
    }
    
    while (Serial.available()) {
      char charRead = Serial.read();
      charsIn.concat(charRead);
    }
    if(charsIn != ""){
      Serial.println("How are you, " + charsIn);
      charsIn.toCharArray(printout, 21);
      EsploraTFT.background(0,0,0);
      EsploraTFT.text(printout, 0, 10);
      charsIn = "";
    }
}

Read last post for Install and test java-simple-serial-connector with Arduino.

Next:
- Bi-direction serial communication using java-simple-serial-connector


Install and test java-simple-serial-connector with Arduino, on Ubuntu

As the new Arduino 1.5.6 BETA replaced RXTX library with JSSC (https://code.google.com/p/java-simple-serial-connector/), this video show how to install JSSC and setup on Netbeans, build a Hello World run on Ubuntu Linux, to send data to Arduino Esplora board. Actually the setup steps and example code follow https://code.google.com/p/java-simple-serial-connector/wiki/jSSC_Start_Working.



In order to work on Ubuntu, modify the example code to change SerialPort to "/dev/ttyACM0".

package java_testjssc;

import jssc.SerialPort;
import jssc.SerialPortException;

public class Java_testjSSC {

    public static void main(String[] args) {
        SerialPort serialPort = new SerialPort("/dev/ttyACM0");
        try {
            System.out.println("Port opened: " + serialPort.openPort());
            System.out.println("Params setted: " + serialPort.setParams(9600, 8, 1, 0));
            System.out.println("\"Hello World!!!\" successfully writen to port: " + serialPort.writeBytes("Hello World!!!".getBytes()));
            System.out.println("Port closed: " + serialPort.closePort());
        }
        catch (SerialPortException ex){
            System.out.println(ex);
        }
    }
    
}

The Arduino side code, refer to the post "Serial communication between Arduino Esplora and PC".

Next: A simple Java application using java-simple-serial-connector library (jSSC) , with JavaFX user interface, send bytes to Arduino Esplora via USB.

Related: Use jSSC (Java Simple Serial Connector) on Windows 8.1

Saturday, March 2, 2013

USB OTG



USB OTG (On-The-Go), often abbreviated USB OTG or just OTG, is a specification that allows USB devices such as digital audio players or mobile phones to act as a host, allowing other USB devices like a USB flash drive, mouse, or keyboard to be attached to them. Unlike conventional USB systems, USB OTG systems can drop the hosting role and act as normal USB devices when attached to another host. This can be used to allow a mobile phone to act as host for a flash drive and read its contents, downloading music for instance, but then act as a flash drive when plugged into a host computer and allow the host to read off the new content.

Read more:


Friday, March 1, 2013

Cabling to connect Arduino Due with Android device

In order to connect Arduino Due with Android device to achieve ADK function, a Micro USB OTG Cable is needed, connected to Native USB Port of Arduino Due. Another normal USB cable is used to connect the USB OTG Cable and Android device. In such connection, the Arduino Due act as host, the Android act as accessory.

Connect Arduino Due and Android device with OTG USB Cable
Connect Arduino Due and Android device with OTG USB Cable