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

Java Arduino LED Control Tutorial

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, writing the table to an Excel file, and creating an XY line chart to graph the sensor values over time.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views22 pages

Java Arduino LED Control Tutorial

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, writing the table to an Excel file, and creating an XY line chart to graph the sensor values over time.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

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()
{
[Link](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 ([Link]())
{
val=[Link]();
}
if (val == '1')
{
encender();
[Link]("Encender led 1");
delay (200);
}
if (val == '2')
{
apagar();
[Link]("Apagar led 1");
delay (200);
}
if (val == 'a')
{
encender2();
[Link]("Encender led 2");
delay (200);
}
if (val == 's')
{
apagar2();
[Link]("Apagar led 2");
delay (200);
}
}
void loop() {
performCommand();
}
//Lectura
void setup() {
[Link](9600);
}

void loop() {
[Link]("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:
[Link](9600);
pinMode(13, OUTPUT);
}
void encender(){
digitalWrite(led, HIGH);
}
void apagar(){
digitalWrite(led, LOW);
}
void performCommand()
{
if ([Link]())
{
val=[Link]();
}
if (val == '1')
{
encender();
//[Link]("Encender led 1");
delay (200);
}
if (val == '2')
{
apagar();
//[Link]("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:
[Link](voltage);
delay(1000);
}

//Guardando datos en Archivo de Excel y graficando

package proyecpanama;

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

/**
*
* @author JULIAN MOLINA
*/
public class Ventana extends [Link] {

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= [Link]();
DefaultTableModel Modelo;
SerialPortEventListener evento= new SerialPortEventListener () {

@Override
public void serialEvent(SerialPortEvent spe) {
if([Link]()==true)
{
String sensor=[Link]();
[Link](sensor);
[Link](sensor);
conver=[Link](sensor);
if (conver <= 3){
[Link]("Alarma ON");
[Link]([Link]);
}
else{
[Link]("Func. Normal");
[Link]([Link]);
}
/*try {
// [Link]([Link]());
[Link]((char)[Link]());
} catch (Exception ex) {
[Link]([Link]()).log([Link], null, ex);
}*/
i++;
[Link](i,conver);
TableUpdate();
}
}
};

public void TableUpdate(){


String Output="";
String hora=[Link](Calendar.HOUR_OF_DAY)+"";
String minuto=[Link]([Link])+"";
String segundos=[Link]([Link])+"";
if ([Link](hora) < 10){
hora="0" + hora;
}
if ([Link](minuto) < 10){
minuto="0" + minuto;
}
if ([Link](segundos) < 10){
segundos="0" + segundos;
}
Output =hora + ":" + minuto + ":"+ segundos;
Calendario = [Link]();
[Link](new Object[]{""+Output,conver});
}

public void FicheroExcel(String input){


HSSFWorkbook libro=new HSSFWorkbook();
HSSFSheet hoja=[Link]();
HSSFRow fila=[Link](0);
HSSFCell celda=[Link](0);
[Link]("Datos leidos del Voltaje");
fila=[Link](1);
celda=[Link](0);
[Link]("HORA");
celda=[Link](1);
[Link]("VOLTIOS");

for (int i=0 ; i<= [Link]() - 1; i++){


fila= [Link](i + 2);
for (int j=0 ; j<=1;j++){
celda=[Link](j);
[Link]([Link](i, j).toString());
}
}
try {
FileOutputStream Fichero=new FileOutputStream(input);
[Link](Fichero);
[Link]();
} catch (Exception e){
[Link]();
}
}

/**
* Creates new form Ventana
*/
public Ventana() {
initComponents();
Modelo=(DefaultTableModel) [Link]();
try {
[Link]("COM3", 2000, 9600, evento);
} catch (Exception ex) {
[Link]([Link]()).log([Link], null, ex);
}
[Link](0, 0);
[Link] (Serie);
Grafica = [Link]("Estado del Voltaje vs Tiempo", "Tiempo", "Voltios",
Coleccion, [Link], 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 [Link]();


jButton2 = new [Link]();
jLabel1 = new [Link]();
jLabel2 = new [Link]();
jLabel3 = new [Link]();
jLabel4 = new [Link]();
jLabel5 = new [Link]();
jLabel6 = new [Link]();
jLabel7 = new [Link]();
jLabel8 = new [Link]();
jButton3 = new [Link]();
jScrollPane1 = new [Link]();
jTable1 = new [Link]();
jButton4 = new [Link]();
jLabel9 = new [Link]();

setDefaultCloseOperation([Link].EXIT_ON_CLOSE);

[Link](new [Link]("Tahoma", 1, 14)); // NOI18N


[Link]("Encender");
[Link](new [Link]() {
public void actionPerformed([Link] evt) {
jButton1ActionPerformed(evt);
}
});

[Link](new [Link]("Tahoma", 1, 14)); // NOI18N


[Link]("Apagar");
[Link](new [Link]() {
public void actionPerformed([Link] evt) {
jButton2ActionPerformed(evt);
}
});

[Link](new [Link]("Tahoma", 1, 14)); // NOI18N


[Link](new [Link](0, 0, 255));
[Link]("LED 1");

[Link](new [Link]("Tahoma", 1, 14)); // NOI18N


[Link](new [Link](0, 0, 255));
[Link]("SENSOR");

[Link](new [Link]("Tahoma", 1, 14)); // NOI18N


[Link]("--------");

[Link](new [Link]("Tahoma", 1, 11)); // NOI18N


[Link]("Voltios");

[Link]([Link]);
[Link]("---------");

[Link]("Escritura de Datos");

[Link]("Lectura de Datos");

[Link](new [Link]("Tahoma", 2, 11)); // NOI18N


[Link]("Evaluación");

[Link](new [Link](204, 0, 0));


[Link](new [Link]("Tahoma", 1, 11)); // NOI18N
[Link](new [Link](204, 255, 204));
[Link]("GRÁFICAR");
[Link](new [Link]() {
public void actionPerformed([Link] evt) {
jButton3ActionPerformed(evt);
}
});

[Link](new [Link](
new Object [][] {

},
new String [] {
"Hora", "Voltaje"
}
));
[Link](jTable1);

[Link](new [Link](0, 153, 51));


[Link](new [Link]("Tahoma", 1, 11)); // NOI18N
[Link](new [Link](255, 255, 255));
[Link]("Exportar a Excel");
[Link](new [Link]() {
public void actionPerformed([Link] evt) {
jButton4ActionPerformed(evt);
}
});

[Link](new [Link]("Tahoma", 1, 10)); // NOI18N


[Link]("Diseño: Julian Molina");

[Link] layout = new [Link](getContentPane());


getContentPane().setLayout(layout);
[Link](
[Link]([Link])
.addGroup([Link]()
.addGap(21, 21, 21)
.addGroup([Link]([Link])
.addGroup([Link]()
.addComponent(jLabel6)
.addGap(0, 0, Short.MAX_VALUE))
.addGroup([Link]()
.addGroup([Link]([Link])
.addGroup([Link]()

.addGroup([Link]([Link])
.addComponent(jLabel1)
.addComponent(jLabel2))
.addGroup([Link]([Link])
.addGroup([Link]()
.addPreferredGap([Link])
.addComponent(jLabel3)
.addPreferredGap([Link])
.addComponent(jLabel4))
.addGroup([Link]()
.addGap(34, 34, 34)
.addComponent(jButton1))))
.addComponent(jLabel7))
.addGap(20, 20, 20)
.addGroup([Link]([Link])
.addGroup([Link]()
.addGap(18, 18, 18)

.addGroup([Link]([Link])
.addGroup([Link]()
.addGap(10, 10, 10)
.addComponent(jLabel8))
.addComponent(jButton2))
.addGap(0, 0, Short.MAX_VALUE))
.addGroup([Link]()
.addGap(3, 3, 3)
.addComponent(jLabel5, [Link].DEFAULT_SIZE, 100,
Short.MAX_VALUE)))
.addContainerGap())))
.addGroup([Link]()
.addContainerGap()
.addGroup([Link]([Link])
.addGroup([Link]()
.addComponent(jScrollPane1, [Link].PREFERRED_SIZE, 321,
[Link].PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
.addGroup([Link]()
.addComponent(jButton4)
.addPreferredGap([Link],
[Link].DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButton3)))
.addContainerGap())
.addGroup([Link]()
.addContainerGap()
.addComponent(jLabel9)
.addContainerGap([Link].DEFAULT_SIZE, Short.MAX_VALUE))
);
[Link](
[Link]([Link])
.addGroup([Link]()
.addComponent(jLabel6)
.addGap(9, 9, 9)
.addGroup([Link]([Link])
.addComponent(jButton1)
.addComponent(jLabel1)
.addComponent(jButton2))
.addGap(15, 15, 15)
.addGroup([Link]([Link])
.addComponent(jLabel7)
.addComponent(jLabel8))
.addPreferredGap([Link])
.addGroup([Link]([Link])
.addComponent(jLabel2)
.addComponent(jLabel3)
.addComponent(jLabel4)
.addComponent(jLabel5))
.addGap(18, 18, 18)
.addComponent(jScrollPane1, [Link].PREFERRED_SIZE, 91,
[Link].PREFERRED_SIZE)
.addGap(18, 18, 18)
.addGroup([Link]([Link])
.addComponent(jButton4)
.addComponent(jButton3))
.addPreferredGap([Link], 12,
Short.MAX_VALUE)
.addComponent(jLabel9))
);

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

private void jButton1ActionPerformed([Link] evt) {


try {
[Link]("1");
} catch (Exception ex) {
[Link]([Link]()).log([Link], null, ex);
}
}

private void jButton2ActionPerformed([Link] evt) {


try {
[Link]("2");
} catch (Exception ex) {
[Link]([Link]()).log([Link], null, ex);
}

private void jButton3ActionPerformed([Link] evt) {


ChartPanel Panel= new ChartPanel(Grafica);
JFrame Ventana2 = new JFrame("Grafica por JFreeChart");
[Link]().add(Panel);
[Link]();
[Link](true);
[Link](JFrame.EXIT_ON_CLOSE);

private void jButton4ActionPerformed([Link] evt) {


[Link] Ventana3 = new [Link]();
String ruta= "";
try {
if([Link](null) == Ventana3.APPROVE_OPTION){
ruta=[Link]().getAbsolutePath()+".xls";
FicheroExcel(ruta);
}
}catch (Exception ex){
[Link]();
}

// TODO add your handling code here:


}

/**
* @param args the command line arguments
*/
// Variables declaration - do not modify
private [Link] jButton1;
private [Link] jButton2;
private [Link] jButton3;
private [Link] jButton4;
private [Link] jLabel1;
private [Link] jLabel2;
private [Link] jLabel3;
private [Link] jLabel4;
private [Link] jLabel5;
private [Link] jLabel6;
private [Link] jLabel7;
private [Link] jLabel8;
private [Link] jLabel9;
private [Link] jScrollPane1;
private [Link] 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:
[Link](9600);
pinMode(13, OUTPUT);
pinMode(12,OUTPUT);
pinMode(11,OUTPUT);
}
void encender(){
digitalWrite(led, HIGH);
}
void apagar(){
digitalWrite(led, LOW);
}
void performCommand()
{
if ([Link]())
{
val=[Link]();
}
if (val == '1')
{
encender();
//[Link]("Encender led 1");
delay (200);
}
if (val == '2')
{
apagar();
//[Link]("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:
[Link](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

[Link]
[Link]

[Link]

[Link]

[Link]
C2167O4cU&v=umQi5URC-DM

[Link]

Common questions

Powered by AI

Challenges in converting sensor data into voltages include the accuracy of the ADC (Analog-Digital Converter), noise and interference affecting the readings, and precision in conversion formulas. The expression, sensorValue * (5.0 / 1023.0), assumes a perfect linear response and calibrated reference voltage, any deviations or ADC errors could lead to incorrect voltages .

The LED state is controlled by reading character inputs from the serial interface. In the performCommand function, the code checks if data is available on the Serial. If available, it reads the character input. Depending on the character ('1', '2', 'a', 's'), it executes functions like encender()/apagar() for LED 1 and encender2()/apagar2() for LED 2 .

Design considerations for choosing pin configurations include the power and current limitations of the pins, avoiding conflicts by not assigning overlapping functions to pins, and ensuring logical mapping with the physical layout for ease of debugging. Selection should consider input/output requirements, signal types (analog/digital), and multiplexing possibilities for optimization .

Graphical libraries and series are used to visualize sensor data by organizing it into a visual format that is easily interpretable. Libraries like JFreeChart are used to create charts from data series, such as XYSeries, which store pairs of data points. The createXYLineChart function creates a line chart that portrays sensor data over time, making data patterns more visible and comprehensible .

The Java interface in LED control systems uses GUI components like buttons and labels to facilitate user interaction. Users can toggle LEDs using buttons that trigger event listeners. These listeners send character data over a serial connection to Arduino, which interprets them as commands to operate LEDs. Labels display the state of the system, providing feedback to users .

Error handling in file operations is crucial to ensure data integrity and prevent application crashes. During data export to Excel, errors such as IOExceptions can occur if the file path is invalid or the file is inaccessible. Try-catch blocks capture such exceptions, providing opportunities to log errors, notify users, or retry operations, thus maintaining robust file handling .

The logic for activating alarms based on voltage readings hinges on threshold comparison. In Arduino's loop function, the voltage is read and compared against a set threshold (e.g., 3 volts). If the reading is under the threshold, certain LEDs (e.g., led2) are turned on to signal an alarm, else another set of LEDs (e.g., led3) indicate normal functioning. This logic ensures real-time response to sensor values .

The setup routine in Arduino LED control projects initializes serial communication and sets the pin modes for the LEDs. Specifically, by using Serial.begin(9600), it establishes the communication speed at 9600 bits per second. The pinMode function is then used to set specified pins (like 13 and 12) as OUTPUT, enabling them to control LEDs by sending high or low signals .

Libraries in Java-Arduino projects enhance functionality by providing pre-built, tested components that simplify tasks like serial communication (e.g., RXTX), data visualization (e.g., JFreeChart), and Excel handling (e.g., Apache POI). This abstraction allows developers to focus on high-level application logic rather than low-level implementation details, improving efficiency and reliability .

Java synchronizes data with Arduino through serial communication, capturing sensor data sent by Arduino. This data is then processed and stored in a table model in Java. The FicheroExcel method is used to write this data into an Excel file, involving creating HSSFWorkbook and filling it with data records retrieved from the table model, writing it to a file system through FileOutputStream .

You might also like