Wednesday, September 30, 2015

Atmel Studio 7 is now live!

Arduino co-founder Massimo Banzi introduces Atmel Studio 7 and one of its unique features, which enables Makers and designers to import their Arduino sketches and then debug their code.




Atmel Studio 7 is free of charge and is integrated with the Atmel Software Framework (ASF)—a large library of free source code with 1,600 project examples. ASF strengthens Atmel Studio by providing, in the same environment, access to ready-to-use code that minimizes much of the low-level design required for projects. Standard IDEs are suited for creating new software for an MCU project. In addition to this, the Atmel Studio 7 IDP also:

  • Facilitates reuse of existing software and, by doing so, enables design differentiation.
  • Supports the product development process with easy access to integrated tools and software extensions through Atmel Gallery.
  • Reduces time to market by providing advanced features, an extensible software eco-system, and powerful debug integration.

One of the benefit for Arduino developer is Atmel Studio 7 features seamless one-click import of projects created in the Arduino development environment. Your sketch, including any libraries it references, will be imported into Studio 7 as a C++ project. Once imported, you can leverage the full capabilities of Studio 7 to fine-tune and debug your design. Atmel Studio 7 fully supports the powerful embedded debugger on the Arduino Zero board. For other Arduino boards, shield-adapters that expose debug connectors are available, or switch to one of the many available Xplained-Mini/PRO boards to fully leverage the Atmel HW eco-system. Regardless of what you choose, you will surely make something amazing.

An introduction to Atmel Studio 7, the free integrated development environment (IDE) for MCU development using Atmel | SMART ARM-based and AVR MCUs.



Download Atmel Studio 7 NOW.

Thursday, September 17, 2015

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

Actually, it's same as last post "Java/JavaFX/jSSC control Arduino + 8x8 LED Matrix", but run on Raspberry Pi 2/Raspbian remotely, instead of run on Windows 10/NetBeans locally.





Host development platform:
OS: Windows 10
IDE: NetBeans IDE 8.0.2
Programming Language: Java + JavaFX + jSSC

Target platform:
Raspberry Pi 2
OS: Raspbian
IP: 192.168.1.112
Both Host development platform and Target platform in the same Network.
(How to set Remote Java SE Platform to deploy on Raspberry Pi, refer to the video in the post "Java + JavaFX + jSSC run on Raspberry Pi, control Arduino Uno")

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 + 8x8 LED Matrix
Connected to Raspberry Pi 2 with USB.

Arduino Side:

Arduino code and connection between Arduino Uno and 8x8 LED Matrix, refer last post.

Java/JavaFX/jSSC code, program on Windows 10/NetBeans, run on Raspberry Pi 2:
(Basically same as last post, with moving btnExit to vBoxMatrix, such that user can exit the program in raspberry Pi UI.

    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);
        vBoxInfo.getChildren().add(label);
        
        //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.getChildren().add(btnExit);
        
        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());
                
            });
        }
    }

}



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.

Monday, September 14, 2015

Kamibot: Interactive Papercraft



Kamibot, simply put, is a paper robot hybrid. Users can build and rebuild their desired papercraft on a single robot. After building, users can move and interact with their papercraft. In addition, anyone can reprogram Kamibot to change their individual interactive experience.

http://www.kamibot.com/


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

Friday, September 11, 2015

Bi-direction communication between Arduino and PC using Java + jSSC

This example show Bi-direction communication between Arduino Uno and PC using Java + javaFX + jSSC:
Arduino to PC: Arduino Uno analog input, display on JavaFX LineChart
PC to Arduino: Button to control Arduino Uno on-board LED


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

Arduino side: AnalogInputToUSB.ino, run on Arduino Uno.
/*
 * AnalogInputUSB
 * Read analog input from analog pin 0
 * and send data to USB
 */

int ledPin = 13;
int analogPin = A0;
int analogValue = 0;

int incomingByte = 0;

void setup() {
  pinMode(ledPin, OUTPUT);
  Serial.begin(9600);
}

void loop() {

  if (Serial.available() > 0) {
    incomingByte = Serial.read();

    if(incomingByte & 0x01){
      digitalWrite(ledPin, HIGH);
    }else{
      digitalWrite(ledPin, LOW);
    }
  }
  
  analogValue = analogRead(analogPin);  //Read analog input
  analogValue = map(analogValue, 0, 1023, 0, 255);
  Serial.write(analogValue);            //write as byte, to USB

  delay(100);
}a

PC Side, 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.event.ActionEvent;
import javafx.scene.Scene;
import javafx.scene.chart.LineChart;
import javafx.scene.chart.NumberAxis;
import javafx.scene.chart.XYChart;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.control.ToggleButton;
import javafx.scene.layout.StackPane;
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_jssc_Uno extends Application {
    
    SerialPort arduinoPort = null;
    ObservableList<String> portList;
    
    ToggleButton tbLED13;
    Label labelValue;
    final int NUM_OF_POINT = 50;
    XYChart.Series series;
     
    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();
        labelValue.setFont(new Font("Arial", 28));
        
        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);
                
                tbLED13.setSelected(false);
            }

        });
        
        //Toggle Button to control LED on Arduino 
        tbLED13 = new ToggleButton("Arduino LED 13");
        tbLED13.setOnAction((ActionEvent event) -> {
            updateLED13();
        });
        
        //LineChart
        final NumberAxis xAxis = new NumberAxis();
        final NumberAxis yAxis = new NumberAxis();
        yAxis.setLabel("Voltage");
        
        final LineChart<Number,Number> lineChart = 
                new LineChart<>(xAxis,yAxis);
        lineChart.setTitle("Arduino Uno A0 Analog Input");
        series = new XYChart.Series();
        series.setName("A0 analog input");
        lineChart.getData().add(series);
        lineChart.setAnimated(false);
        
        //pre-load with dummy data
        for(int i=0; i<NUM_OF_POINT; i++){
            series.getData().add(new XYChart.Data(i, 0));
        }
        //
        
        VBox vBox = new VBox();
        vBox.getChildren().addAll(
                comboBoxPorts,  
                tbLED13, 
                labelValue, 
                lineChart);
        
        StackPane root = new StackPane();
        root.getChildren().add(vBox);
        
        Scene scene = new Scene(root, 500, 400);
        
        primaryStage.setTitle(
                "arduino-er.blogspot.com: Java + JavaFX + jSSC demo");
        primaryStage.setScene(scene);
        primaryStage.show();
    }
    
    private void updateLED13(){
        try {
            if(tbLED13.isSelected()){
                if(arduinoPort != null){
                    arduinoPort.writeByte((byte)0x01);
                    System.out.println("LED 13 ON");
                }else{
                    System.out.println("arduinoPort not connected!");
                }
            }else {
                if(arduinoPort != null){
                    arduinoPort.writeByte((byte)0x00);
                    System.out.println("LED 13 OFF");
                }else{
                    System.out.println("arduinoPort not connected!");
                }
            }
        }catch (SerialPortException ex) {
            Logger.getLogger(JavaFX_jssc_Uno.class.getName())
                    .log(Level.SEVERE, null, ex);
        }
    }
    
    public void shiftSeriesData(float newValue)
    {
        for(int i=0; i<NUM_OF_POINT-1; i++){
            XYChart.Data<String, Number> ShiftDataUp = 
                    (XYChart.Data<String, Number>)series.getData().get(i+1);
            Number shiftValue = ShiftDataUp.getYValue();
            XYChart.Data<String, Number> ShiftDataDn = 
                    (XYChart.Data<String, Number>)series.getData().get(i);
            ShiftDataDn.setYValue(shiftValue);
        }
        XYChart.Data<String, Number> lastData = 
            (XYChart.Data<String, Number>)series.getData().get(NUM_OF_POINT-1);
        lastData.setYValue(newValue);
    }

    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 {
                        
                        byte[] b = serialPort.readBytes();
                        int value = b[0] & 0xff;    //convert to int
                        String st = String.valueOf(value);

                        //Update label in ui thread
                        Platform.runLater(() -> {
                            labelValue.setText(st);
                            shiftSeriesData((float)value * 5/255); //in 5V scale
                        });
                        
                    } 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();
                }
                
                arduinoPort = null;
            } 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);
    }
    
}


Connect a potentiometer in Arduino Uno side to set analog input A0.
Next:
- Run it remotely on Raspberry Pi 2.

Wednesday, September 9, 2015

JavaFX + jSSC - read byte from Arduino Uno, display in LineChart


Similar to last example "JavaFX + jSSC - read byte from Arduino Uno, read from Analog Input". This example plot the analog data in JavaFX LineChart. (This video show the effect of calling lineChart.setAnimated(false) and default true also.)


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

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.chart.LineChart;
import javafx.scene.chart.NumberAxis;
import javafx.scene.chart.XYChart;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.layout.StackPane;
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_jssc_Uno extends Application {
    
    SerialPort arduinoPort = null;
    ObservableList<String> portList;
    
    Label labelValue;
    final int NUM_OF_POINT = 50;
    XYChart.Series series;
     
    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();
        labelValue.setFont(new Font("Arial", 28));
        
        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);
            }

        });
        
        //LineChart
        final NumberAxis xAxis = new NumberAxis();
        final NumberAxis yAxis = new NumberAxis();
        yAxis.setLabel("Voltage");
        
        final LineChart<Number,Number> lineChart = 
                new LineChart<>(xAxis,yAxis);
        lineChart.setTitle("Arduino Uno A0 Analog Input");
        series = new XYChart.Series();
        series.setName("A0 analog input");
        lineChart.getData().add(series);
        lineChart.setAnimated(false);
        
        //pre-load with dummy data
        for(int i=0; i<NUM_OF_POINT; i++){
            series.getData().add(new XYChart.Data(i, 0));
        }
        //
        
        VBox vBox = new VBox();
        vBox.getChildren().addAll(
                comboBoxPorts, labelValue, lineChart);
        
        StackPane root = new StackPane();
        root.getChildren().add(vBox);
        
        Scene scene = new Scene(root, 500, 400);
        
        primaryStage.setTitle(
                "arduino-er.blogspot.com: Java + JavaFX + jSSC demo");
        primaryStage.setScene(scene);
        primaryStage.show();
    }
    
    public void shiftSeriesData(float newValue)
    {
        for(int i=0; i<NUM_OF_POINT-1; i++){
            XYChart.Data<String, Number> ShiftDataUp = 
                    (XYChart.Data<String, Number>)series.getData().get(i+1);
            Number shiftValue = ShiftDataUp.getYValue();
            XYChart.Data<String, Number> ShiftDataDn = 
                    (XYChart.Data<String, Number>)series.getData().get(i);
            ShiftDataDn.setYValue(shiftValue);
        }
        XYChart.Data<String, Number> lastData = 
            (XYChart.Data<String, Number>)series.getData().get(NUM_OF_POINT-1);
        lastData.setYValue(newValue);
    }

    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 {
                        
                        byte[] b = serialPort.readBytes();
                        int value = b[0] & 0xff;    //convert to int
                        String st = String.valueOf(value);

                        //Update label in ui thread
                        Platform.runLater(() -> {
                            labelValue.setText(st);
                            shiftSeriesData((float)value * 5/255); //in 5V scale
                        });
                        
                    } 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);
    }
    
}


For the Arduino Uno side and hardware connection, refer to last post "JavaFX + jSSC - read byte from Arduino Uno, read from Analog Input".

Next:
Bi-direction communication between Arduino and PC using Java + jSSC

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

This example show how to use Java + jSSC + JavaFX running on PC/Windows 10, read bytes from USB/Serial. The data sent from Arduino Uno by reading analog input. The PC and Arduino Uno connected with USB.


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

Java code, run on PC side - 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.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_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();
        labelValue.setFont(new Font("Arial", 150));
        
        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 {
                        
                        byte[] b = serialPort.readBytes();
                        int value = b[0] & 0xff;    //convert to int
                        String st = String.valueOf(value);


                        //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);
    }
    
}


Arduino Uno side - AnalogInputToUSB.ino
/*
 * AnalogInputUSB
 * Read analog input from analog pin 0
 * and send data to USB
 */

int ledPin = 13;
int analogPin = A0;
int analogValue = 0;

void setup() {
  pinMode(ledPin, OUTPUT);
  Serial.begin(9600);
}

void loop() {
  digitalWrite(ledPin, HIGH);
  
  analogValue = analogRead(analogPin);  //Read analog input
  analogValue = map(analogValue, 0, 1023, 0, 255);
  Serial.write(analogValue);            //write as byte, to USB
  
  digitalWrite(ledPin, LOW);
  delay(1000);
}

Connect a potentiometer in Analog Input A0 as input.


Next:
JavaFX + jSSC - read byte from Arduino Uno, display in LineChart

Download and Install 64 bit Fritzing on Windows 10


Fritzing is an open-source hardware initiative that makes electronics accessible as a creative material for anyone.

http://fritzing.org/

Video show how to download and install 64 bit Fritzing on Windows 10




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

Monday, September 7, 2015

Install Arduino Software (IDE) on Windows 10



To install Arduino Software (IDE) on Windows 10, visit https://www.arduino.cc/en/Main/Software to download and run Windows Installer.

This video show the steps:




Due to any reason, you cannot install the Arduino driver on Windows, you can try to update the driver manually in your Device Manager.