0% found this document useful (0 votes)
76 views22 pages

Tutorial Java Arduino

This document provides code and instructions for using Arduino with Java (Netbeans) to turn LEDs on and off, read sensor data, save data to an Excel file, and create graphs of the sensor data. It includes Arduino code for writing (turning LEDs on/off), reading sensor values, and evaluating input data. It also includes Java code for connecting to Arduino, updating a table with sensor readings, saving the table to an Excel file, and creating an XY line chart to graph the sensor values over time.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
76 views22 pages

Tutorial Java Arduino

This document provides code and instructions for using Arduino with Java (Netbeans) to turn LEDs on and off, read sensor data, save data to an Excel file, and create graphs of the sensor data. It includes Arduino code for writing (turning LEDs on/off), reading sensor values, and evaluating input data. It also includes Java code for connecting to Arduino, updating a table with sensor readings, saving the table to an Excel file, and creating an XY line chart to graph the sensor values over time.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 22

Tutorial Java (Netbeans) - Arduino

Encender/Apagar _ LED
//Utilización de Librerías de Arduino para java
Librerías necesarias:
Código en Arduino

//Escritura

int led=13;
int led2=12;
char val;
void setup()
{
Serial.begin(9600);
pinMode(13, OUTPUT);
pinMode(12, OUTPUT);
}
void encender(){
digitalWrite(led, HIGH);
}
void apagar(){
digitalWrite(led, LOW);
}
void encender2(){
digitalWrite(led2, HIGH);
}
void apagar2(){
digitalWrite(led2, LOW);
}
void performCommand()
{
if (Serial.available())
{
val=Serial.read();
}
if (val == '1')
{
encender();
Serial.println("Encender led 1");
delay (200);
}
if (val == '2')
{
apagar();
Serial.println("Apagar led 1");
delay (200);
}
if (val == 'a')
{
encender2();
Serial.println("Encender led 2");
delay (200);
}
if (val == 's')
{
apagar2();
Serial.println("Apagar led 2");
delay (200);
}
}
void loop() {
performCommand();
}
//Lectura
void setup() {
Serial.begin(9600);
}

void loop() {
Serial.println("Bienvenida Familia!");
delay(2500);
}
Evaluación de datos de entrada
//Código de Arduino
int led=13;
char val;

// the setup routine runs once when you press reset:


void setup() {
// initialize serial communication at 9600 bits per second:
Serial.begin(9600);
pinMode(13, OUTPUT);
}
void encender(){
digitalWrite(led, HIGH);
}
void apagar(){
digitalWrite(led, LOW);
}
void performCommand()
{
if (Serial.available())
{
val=Serial.read();
}
if (val == '1')
{
encender();
//Serial.println("Encender led 1");
delay (200);
}
if (val == '2')
{
apagar();
//Serial.println("Apagar led 1");
delay (200);
}
}
// the loop routine runs over and over again forever:
void loop() {
// read the input on analog pin 0:
performCommand();
int sensorValue = analogRead(A0);
// Convert the analog reading (which goes from 0 - 1023) to a voltage (0 - 5V):
float voltage = sensorValue * (5.0 / 1023.0);
// print out the value you read:
Serial.println(voltage);
delay(1000);
}

//Guardando datos en Archivo de Excel y graficando

package proyecpanama;

import Arduino.Arduino;
import gnu.io.SerialPortEvent;
import gnu.io.SerialPortEventListener;
import java.awt.Color;
import java.io.FileOutputStream;
import java.util.Calendar;
import java.util.Locale;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFrame;
import javax.swing.table.DefaultTableModel;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;

/**
*
* @author JULIAN MOLINA
*/
public class Ventana extends javax.swing.JFrame {

Arduino Arduino= new Arduino();


//Variables para Graficar datos sensados
final XYSeries Serie= new XYSeries("Estado Voltaje");
final XYSeriesCollection Coleccion= new XYSeriesCollection();
JFreeChart Grafica;
int i=0;
float conver;
//Tabla excel
Calendar Calendario= Calendar.getInstance();
DefaultTableModel Modelo;
SerialPortEventListener evento= new SerialPortEventListener () {

@Override
public void serialEvent(SerialPortEvent spe) {
if(Arduino.MessageAvailable()==true)
{
String sensor=Arduino.PrintMessage();
jLabel3.setText(sensor);
System.out.println(sensor);
conver=Float.parseFloat(sensor);
if (conver <= 3){
jLabel5.setText("Alarma ON");
jLabel5.setForeground(Color.red);
}
else{
jLabel5.setText("Func. Normal");
jLabel5.setForeground(Color.black);
}
/*try {
// System.out.println(Arduino.ReceiveData());
System.out.println((char)Arduino.ReceiveData());
} catch (Exception ex) {
Logger.getLogger(Ventana.class.getName()).log(Level.SEVERE, null, ex);
}*/
i++;
Serie.add(i,conver);
TableUpdate();
}
}
};

public void TableUpdate(){


String Output="";
String hora=Calendario.get(Calendar.HOUR_OF_DAY)+"";
String minuto=Calendario.get(Calendar.MINUTE)+"";
String segundos=Calendario.get(Calendar.SECOND)+"";
if (Integer.parseInt(hora) < 10){
hora="0" + hora;
}
if (Integer.parseInt(minuto) < 10){
minuto="0" + minuto;
}
if (Integer.parseInt(segundos) < 10){
segundos="0" + segundos;
}
Output =hora + ":" + minuto + ":"+ segundos;
Calendario = Calendar.getInstance();

Modelo.addRow(new Object[]{""+Output,conver});
}

public void FicheroExcel(String input){


HSSFWorkbook libro=new HSSFWorkbook();
HSSFSheet hoja=libro.createSheet();
HSSFRow fila=hoja.createRow(0);
HSSFCell celda=fila.createCell(0);
celda.setCellValue("Datos leidos del Voltaje");
fila=hoja.createRow(1);
celda=fila.createCell(0);
celda.setCellValue("HORA");
celda=fila.createCell(1);
celda.setCellValue("VOLTIOS");

for (int i=0 ; i<= Modelo.getRowCount() - 1; i++){


fila= hoja.createRow(i + 2);
for (int j=0 ; j<=1;j++){
celda=fila.createCell(j);
celda.setCellValue(jTable1.getValueAt(i, j).toString());
}
}
try {
FileOutputStream Fichero=new FileOutputStream(input);
libro.write(Fichero);
Fichero.close();
} catch (Exception e){
e.printStackTrace();
}
}

/**
* Creates new form Ventana
*/
public Ventana() {
initComponents();
Modelo=(DefaultTableModel) jTable1.getModel();
try {
Arduino.ArduinoRXTX("COM3", 2000, 9600, evento);
} catch (Exception ex) {
Logger.getLogger(Ventana.class.getName()).log(Level.SEVERE, null, ex);
}
Serie.add(0, 0);
Coleccion.addSeries (Serie);
Grafica = ChartFactory.createXYLineChart("Estado del Voltaje vs Tiempo", "Tiempo", "Voltios",
Coleccion, PlotOrientation.VERTICAL, true, true, false);
}

/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {

jButton1 = new javax.swing.JButton();


jButton2 = new javax.swing.JButton();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
jLabel6 = new javax.swing.JLabel();
jLabel7 = new javax.swing.JLabel();
jLabel8 = new javax.swing.JLabel();
jButton3 = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
jTable1 = new javax.swing.JTable();
jButton4 = new javax.swing.JButton();
jLabel9 = new javax.swing.JLabel();

setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

jButton1.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N


jButton1.setText("Encender");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jButton2.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
jButton2.setText("Apagar");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});

jLabel1.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N


jLabel1.setForeground(new java.awt.Color(0, 0, 255));
jLabel1.setText("LED 1");

jLabel2.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N


jLabel2.setForeground(new java.awt.Color(0, 0, 255));
jLabel2.setText("SENSOR");

jLabel3.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N


jLabel3.setText("--------");

jLabel4.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N


jLabel4.setText("Voltios");

jLabel5.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel5.setText("---------");

jLabel6.setText("Escritura de Datos");

jLabel7.setText("Lectura de Datos");

jLabel8.setFont(new java.awt.Font("Tahoma", 2, 11)); // NOI18N


jLabel8.setText("Evaluación");

jButton3.setBackground(new java.awt.Color(204, 0, 0));


jButton3.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
jButton3.setForeground(new java.awt.Color(204, 255, 204));
jButton3.setText("GRÁFICAR");
jButton3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton3ActionPerformed(evt);
}
});
jTable1.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {

},
new String [] {
"Hora", "Voltaje"
}
));
jScrollPane1.setViewportView(jTable1);

jButton4.setBackground(new java.awt.Color(0, 153, 51));


jButton4.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
jButton4.setForeground(new java.awt.Color(255, 255, 255));
jButton4.setText("Exportar a Excel");
jButton4.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton4ActionPerformed(evt);
}
});

jLabel9.setFont(new java.awt.Font("Tahoma", 1, 10)); // NOI18N


jLabel9.setText("Diseño: Julian Molina");

javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());


getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(21, 21, 21)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel6)
.addGap(0, 0, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()

.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1)
.addComponent(jLabel2))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel3)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel4))
.addGroup(layout.createSequentialGroup()
.addGap(34, 34, 34)
.addComponent(jButton1))))
.addComponent(jLabel7))
.addGap(20, 20, 20)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(18, 18, 18)

.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(10, 10, 10)
.addComponent(jLabel8))
.addComponent(jButton2))
.addGap(0, 0, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addGap(3, 3, 3)
.addComponent(jLabel5, javax.swing.GroupLayout.DEFAULT_SIZE, 100,
Short.MAX_VALUE)))
.addContainerGap())))
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 321,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addComponent(jButton4)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED,
javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButton3)))
.addContainerGap())
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel9)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel6)
.addGap(9, 9, 9)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton1)
.addComponent(jLabel1)
.addComponent(jButton2))
.addGap(15, 15, 15)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel7)
.addComponent(jLabel8))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(jLabel3)
.addComponent(jLabel4)
.addComponent(jLabel5))
.addGap(18, 18, 18)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 91,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton4)
.addComponent(jButton3))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 12,
Short.MAX_VALUE)
.addComponent(jLabel9))
);

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

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {


try {
Arduino.SendData("1");
} catch (Exception ex) {
Logger.getLogger(Ventana.class.getName()).log(Level.SEVERE, null, ex);
}
}

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {


try {
Arduino.SendData("2");
} catch (Exception ex) {
Logger.getLogger(Ventana.class.getName()).log(Level.SEVERE, null, ex);
}

private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {


ChartPanel Panel= new ChartPanel(Grafica);
JFrame Ventana2 = new JFrame("Grafica por JFreeChart");
Ventana2.getContentPane().add(Panel);
Ventana2.pack();
Ventana2.setVisible(true);
Ventana2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {


javax.swing.JFileChooser Ventana3 = new javax.swing.JFileChooser();
String ruta= "";
try {
if(Ventana3.showSaveDialog(null) == Ventana3.APPROVE_OPTION){
ruta=Ventana3.getSelectedFile().getAbsolutePath()+".xls";
FicheroExcel(ruta);
}
}catch (Exception ex){
ex.printStackTrace();
}

// TODO add your handling code here:


}

/**
* @param args the command line arguments
*/
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JButton jButton3;
private javax.swing.JButton jButton4;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JLabel jLabel8;
private javax.swing.JLabel jLabel9;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTable jTable1;
// End of variables declaration
}
//Código completo en Arduino
int led=13;
int led2=12;
int led3=11;
char val;

// the setup routine runs once when you press reset:


void setup() {
// initialize serial communication at 9600 bits per second:
Serial.begin(9600);
pinMode(13, OUTPUT);
pinMode(12,OUTPUT);
pinMode(11,OUTPUT);
}
void encender(){
digitalWrite(led, HIGH);
}
void apagar(){
digitalWrite(led, LOW);
}
void performCommand()
{
if (Serial.available())
{
val=Serial.read();
}
if (val == '1')
{
encender();
//Serial.println("Encender led 1");
delay (200);
}
if (val == '2')
{
apagar();
//Serial.println("Apagar led 1");
delay (200);
}
}
// the loop routine runs over and over again forever:
void loop() {
// read the input on analog pin 0:
performCommand();
int sensorValue = analogRead(A0);
// Convert the analog reading (which goes from 0 - 1023) to a voltage (0 - 5V):
float voltage = sensorValue * (5.0 / 1023.0);
// print out the value you read:
Serial.println(voltage);
delay(1000);
if (voltage <= 3){
digitalWrite(led2, HIGH);
digitalWrite(led3, LOW);
}
if (voltage > 3){
digitalWrite(led2, LOW);
digitalWrite(led3, HIGH);
}
}

Ruta de librería para conexión serial y paralela (SO Windows a 64 Bits)

C:\Users\JULIAN MOLINA\Documents\2014B\Archivos_serial_java

Webgrafia

http://sourceforge.net/projects/arduinoyjava/files/RXTX%20drivers/
https://www.youtube.com/watch?v=RMcL-Cn1qVM

https://www.youtube.com/watch?v=3QgY5JjQxuI

https://www.youtube.com/watch?v=N_C2167O4cU

https://www.youtube.com/watch?
annotation_id=annotation_707248209&feature=iv&src_vid=N_C2167O4cU&v=umQi5URC-DM

https://www.youtube.com/watch?v=kSB9bLhF8v4

You might also like