Click here to Skip to main content
15,886,840 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have made an app, that when you click a button, it scans for the serial ports, and tries to connect to each one that contains the string:
"/dev/ttyACM"+i

I am trying to find out to whic port my arduino is connected to. after that I send a byte to it, and wait another byte in response, that way I know it is my arduino.
After that, I turn on/off a led after 1 second, making it blink.
It detects when the arduino is disconnected and starts scanning the ports again, the problem I'm having, is that even though I reconnect the arduino and I know to which port it is connected to, the java app just wont reconnect to the arduino.
Here is my code:
package serialscan;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
//package TestBatery001;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JLabel;
import javax.swing.JProgressBar;
//import jPicUsb.*;
import java.awt.Color;
import java.awt.Graphics2D;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;
import javax.swing.JTextField;
import javax.swing.Painter;
import javax.swing.UIDefaults;
import javax.swing.UIManager;
import javax.swing.plaf.basic.BasicProgressBarUI;
//import Serialio.*;
import jssc.SerialPort;
import jssc.SerialPortEvent;
import jssc.SerialPortException;
import jssc.SerialPortList;

/**
 *
 * @author Faster
 */
public class Barra extends Thread {

    JLabel com;
    int i = 0;
    SerialPort port;
    byte inBytes;
    boolean state = false;
    String puerto;
    String[] puertos;

    public Barra(JLabel com) throws Exception {

        this.com = com;

    }

    public void run() {
        while (true) {
            try {
                puertos = SerialPortList.getPortNames();
            } catch (Exception ex) {
            }
            if (state == false) {
                chequeo();//Revisa los puertos, si ya se conecto, solo se ejecuta esa vez, hasta que se desconecte el aparato
            } else {        //en ese caso, debe volver a escanear los otros puertos.
                if (port.isOpened()) {
                    try {                        
                        port.writeByte((byte) 49);
                        TimeUnit.SECONDS.sleep(1);
                        port.writeByte((byte) 48);
                        TimeUnit.SECONDS.sleep(1);
                        try{
                            if(!puertos[i].contains(puerto)){
                                port.closePort();
                                state=false;
                                i++;
                            }                                                            
                        }catch(Exception ex){state=false;
                        //i++;
                        }
                        System.out.println("entro al ciclo on/off");
                    } catch (SerialPortException ex) {
                        Logger.getLogger(Barra.class.getName()).log(Level.SEVERE, null, ex);
                    } catch (InterruptedException ex) {
                        Logger.getLogger(Barra.class.getName()).log(Level.SEVERE, null, ex);
                    }
                } else {
                    state = false;
                }
            }

        }
    }

    protected byte getByte() throws jssc.SerialPortException {
        try{
            while (port.getInputBufferBytesCount() < 1) {
                try {
                    Thread.sleep(1);
                    if (Thread.currentThread().isInterrupted()) {
                        return 0;
                    }
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                    return 0;
                }
            }    
            return (byte) (port.readBytes(1))[0];
        }catch(Exception ex){state=false;}return 0;
}
        
    

    public void chequeo() {
        //String puerto = "/dev/ttyACM" + i;            
        puerto = "/dev/ttyACM" + (i);
        port = new SerialPort(puerto);
        System.setProperty("JSSC_NO_TIOCEXCL", "");
        try {
            if (!port.isOpened()) {
                port.openPort();
                TimeUnit.SECONDS.sleep(10);
                port.writeByte((byte) 1);
                inBytes = getByte();
                //Read
                System.out.println("1. port " + puerto + " is opened");
            }
        } catch (Exception ex) {
            //i++;
            System.out.println("serialexception");           
        }

        if (!port.isOpened()) {
            i++;
            try {
                try{
                port.closePort();
                }catch(Exception ex){state=false;
                }
                System.out.println("3. port " + puerto + " is not opened! NOT ARDUINO");
                System.out.println("b " + getByte());
            } catch (SerialPortException ex) {
                Logger.getLogger(Barra.class.getName()).log(Level.SEVERE, null, ex);
            }
            System.out.println("2. port " + puerto + " is not opened!");
            if (i == 10) {
                i = 0;
            }
        } else if (port.isOpened()) {
            //TimeUnit.SECONDS.sleep(10);
            if (inBytes == (byte) 1) {
                System.out.println("arduino");
                System.out.println("2. port " + puerto + " is opened!");
                state = true;
                try {
                    System.out.println("byte " + getByte());
                } catch (SerialPortException ex) {
                    Logger.getLogger(Barra.class.getName()).log(Level.SEVERE, null, ex);
                }

            }

        }
    }
}

That is the code for the thread and that is what does all the process.
Can someone please help me fix this?
I really need my app to reconnect to the arduino, once it is reconnected to the computer.
Thanks!
Posted

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900