Showing posts with label analog input. Show all posts
Showing posts with label analog input. Show all posts

Monday, April 4, 2016

NodeMCU to read analog input, A0.


Last post introduced "Serial Plotter in Arduino IDE" with Arduino Uno example to read analog input and println to Serial Port, to display on Arduino Software's Serial Plotter. The example can direct re-compile and run target NodeMCU/ESP8266.



remark: Fritzing part of NodeMCU can be found HERE.

Example code, same as in last post.
const int AnalogIn  = A0;

int readingIn = 0;

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

void loop() {
  readingIn = analogRead(AnalogIn);
  Serial.println(readingIn);
}


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

Thursday, March 28, 2013

Read analog input of Arduino Due board

The Arduino Due Board has 12 analog inputs (pins from A0 to A11), each of which can provide 12 bits of resolution (i.e. 4096 different values). By default, the resolution of the readings is set at 10 bits, for compatibility with other Arduino boards. It is possible to change the resolution of the ADC with analogReadResolution(). The Due’s analog inputs pins measure from ground to a maximum value of 3.3V.

Applying more then 3.3V on the Due’s pins will damage the SAM3X chip. The analogReference() function is ignored on the Due.

Analog input pins on Arduino Due Board
Analog input pins on Arduino Due Board

Example to read from Analog Input:

int analogInputA0 = A0;
int varA0;

void setup() {
  Serial.begin(9600);
  analogReadResolution(12);  //set ADC resolution to 12 bits

}

void loop() {
  varA0 = analogRead(analogInputA0);  //read ADC input
  Serial.println(varA0, HEX);         //print as HEX
  delay(1000);
}

Read Analog Input on Arduino Due
Read Analog Input on Arduino Due


If the code compiled with error: 'analogReadResolution' was not declared in this scope.
Check if you select the correct Tools -> Board.