Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 10 of 10
  1. #1
    New Coder
    Join Date
    Dec 2010
    Posts
    17
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Question Java serial port reader help!!!

    hey,

    I've been working on a bit of code for the last few hours, but I can't get it to work... All it's meant to do is accept a bit of data coming from a serial port. I've checked my code, and tried to debug it, but I can't work out why it wont wont. it seems to be failing on line 66 which is the CommPortIdentifier.getPortIdentifiers(); part as a null point exception is thrown... I've got the comm.jar fail in my library, and other applications can use my serial port on my PC. I've tried running it on Ubuntu 10.10, windows XP, windows 7 and even on a mac, but I can't get it to work.

    This is my full code.... any help would be greatly appreciated.... I realise the run method doens't do anything as of yet.

    Code:
     
    package portreader;
    
    /**
     *
     * @author Pete
     *
     */
    
    import javax.comm.CommPortIdentifier;
    import javax.comm.PortInUseException;
    import javax.comm.SerialPort;
    import javax.comm.SerialPortEvent;
    import javax.comm.SerialPortEventListener;
    import javax.comm.UnsupportedCommOperationException;
    import java.io.IOException;
    import java.io.InputStream;
    import java.util.Enumeration;
    import java.util.TooManyListenersException;
    
    
    public class Main implements Runnable, SerialPortEventListener {
    
        static CommPortIdentifier portId;
        static CommPortIdentifier saveportId;
        static Enumeration portList;
        InputStream inputStream;
        SerialPort serialPort;
        Thread readThread;
        String defaultPort;
        boolean portFound = false;
    
        Main() {
            getPort();  
            ListenOnPort();
        }
    
        @Override
        public void run() {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException ex) {
            }
        }
    
        private void getPort() {
            portFound = false;
            String osname = System.getProperty("os.name").toLowerCase();
            if (osname.startsWith("windows")) {
                // windows
                defaultPort = "COM1";
            } else if (osname.startsWith("linux")) {
                // linux
                defaultPort = "/dev/ttyS0";
            } else if (osname.startsWith("mac")) {
                // mac
                defaultPort = "/dev/cuaa0";
            } else {
                defaultPort = null;
                System.out.println("Sorry, your operating system is not supported");
            }
    
    
            portList = CommPortIdentifier.getPortIdentifiers();
           while ((portList.hasMoreElements()) && !(portFound)) {
                portId = (CommPortIdentifier) portList.nextElement();
                if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
    
                    if (portId.getName().equals(defaultPort)) {
                        System.out.println("Found port: " + defaultPort);
                        portFound = true;
                    }
                }
            }
            if (!portFound) {
                System.err.println("port " + defaultPort + " not found."); //user feedback
                System.exit(1);
            }
        }
    
        private void ListenOnPort(){
            try {
                serialPort = (SerialPort) portId.open("", 3000);
            } catch (PortInUseException e) {
                System.out.println("The serial port you are trying to use is currently in use");
            }
            
            try {
                inputStream = serialPort.getInputStream();
            } catch (IOException e) {
            }
            try {
                serialPort.addEventListener(this);
            } catch (TooManyListenersException e) {
            }
            // activate the DATA_AVAILABLE notifier
            serialPort.notifyOnDataAvailable(true);
            try {
               
                serialPort.setSerialPortParams(4800,
                        SerialPort.DATABITS_8,
                        SerialPort.STOPBITS_1,
                        SerialPort.PARITY_NONE);
            } catch (UnsupportedCommOperationException e) {
            }
         
            readThread = new Thread(this);
            readThread.start();
        }
    
        @Override
        public void serialEvent(SerialPortEvent event) {
    
            switch (event.getEventType()) {
                case SerialPortEvent.BI:   // Break interrupt
                case SerialPortEvent.OE: // Overrun error
                case SerialPortEvent.FE: // Framing error
                case SerialPortEvent.PE: // Parity error
                case SerialPortEvent.CD: //Carrier detected
                case SerialPortEvent.CTS://Clear to send
                case SerialPortEvent.DSR:// Data set ready
                case SerialPortEvent.RI: // Ring indicator
                case SerialPortEvent.OUTPUT_BUFFER_EMPTY:
                    break; //Buffer empty
                case SerialPortEvent.DATA_AVAILABLE: //Data Available to be read
                 
    
                    byte[] readBuffer = new byte[20]; 
    
                    try {
                      
                        while (inputStream.available() > 0) {
                            int numBytes = inputStream.read(readBuffer);
                        }
                      
                        String result = new String(readBuffer);
                        System.out.println(result);
                    } catch (IOException e) {
                    }
                    break;
            }
    
        }
    
        public static void main(String[] args) {
            new Main();
        }
    }

  • #2
    New Coder
    Join Date
    Dec 2010
    Posts
    17
    Thanks
    1
    Thanked 0 Times in 0 Posts
    I've also tried changing the comm.jar file just encase... but same result...any help would be greatly appreciated...

  • #3
    Regular Coder
    Join Date
    Feb 2008
    Location
    Edinburgh - Scotland
    Posts
    107
    Thanks
    0
    Thanked 12 Times in 12 Posts
    Hey - ok so what is that method meant to do?

    Can you perhaps paste the code of the method call which is throwing the null pointer.... It may be that you are not calling things in the correct order - or its not setup right.

    Is there another library you could try instead?

  • #4
    New Coder
    Join Date
    Dec 2010
    Posts
    17
    Thanks
    1
    Thanked 0 Times in 0 Posts
    Quote Originally Posted by renegadeandy View Post
    Hey - ok so what is that method meant to do?

    Can you perhaps paste the code of the method call which is throwing the null pointer.... It may be that you are not calling things in the correct order - or its not setup right.

    Is there another library you could try instead?
    I've tried changing the library that I call, but it's not changed anything... The code that I've pasted is all of my program... that's all the code I've got, I don't understand why it's not working...

  • #5
    Regular Coder
    Join Date
    Feb 2008
    Location
    Edinburgh - Scotland
    Posts
    107
    Thanks
    0
    Thanked 12 Times in 12 Posts
    Well thats your code - and youve not even told us the code which is run inside that method. Come on, how can we help when you dont even give us the code which is failing.

  • #6
    New Coder
    Join Date
    Dec 2010
    Posts
    17
    Thanks
    1
    Thanked 0 Times in 0 Posts
    Quote Originally Posted by renegadeandy View Post
    Well thats your code - and youve not even told us the code which is run inside that method. Come on, how can we help when you dont even give us the code which is failing.
    I have...

    There are two methods.... getPort() & ListenOnPort()


    getPort() should find the platform it's running on, locate all the ports on the system, then checks that the port that it's found is a serial port, then check that it's the serial port you want.

    Then ListenOnPort, should listen to the port and notify the user when data is available...

    but it's just not finding the ports... and I can't work out why

  • #7
    Regular Coder
    Join Date
    Feb 2008
    Location
    Edinburgh - Scotland
    Posts
    107
    Thanks
    0
    Thanked 12 Times in 12 Posts
    Well give us the getPorts() method then inside [code] brackets....

  • #8
    New Coder
    Join Date
    Dec 2010
    Posts
    17
    Thanks
    1
    Thanked 0 Times in 0 Posts
    Quote Originally Posted by renegadeandy View Post
    Well give us the getPorts() method then inside [code] brackets....

    This is the whole program:
    Code:
    package portreader;
    
    /**
     *
     * @author Pete
     *
     */
    
    import javax.comm.CommPortIdentifier;
    import javax.comm.PortInUseException;
    import javax.comm.SerialPort;
    import javax.comm.SerialPortEvent;
    import javax.comm.SerialPortEventListener;
    import javax.comm.UnsupportedCommOperationException;
    import java.io.IOException;
    import java.io.InputStream;
    import java.util.Enumeration;
    import java.util.TooManyListenersException;
    
    
    public class Main implements Runnable, SerialPortEventListener {
    
        static CommPortIdentifier portId;
        static CommPortIdentifier saveportId;
        static Enumeration portList;
        InputStream inputStream;
        SerialPort serialPort;
        Thread readThread;
        String defaultPort;
        boolean portFound = false;
    
        Main() {
            getPort();  
            ListenOnPort();
        }
    
        @Override
        public void run() {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException ex) {
            }
        }
    
        private void getPort() {
            portFound = false;
            String osname = System.getProperty("os.name").toLowerCase();
            if (osname.startsWith("windows")) {
                // windows
                defaultPort = "COM1";
            } else if (osname.startsWith("linux")) {
                // linux
                defaultPort = "/dev/ttyS0";
            } else if (osname.startsWith("mac")) {
                // mac
                defaultPort = "/dev/cuaa0";
            } else {
                defaultPort = null;
                System.out.println("Sorry, your operating system is not supported");
            }
    
    
            portList = CommPortIdentifier.getPortIdentifiers();
           while ((portList.hasMoreElements()) && !(portFound)) {
                portId = (CommPortIdentifier) portList.nextElement();
                if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
    
                    if (portId.getName().equals(defaultPort)) {
                        System.out.println("Found port: " + defaultPort);
                        portFound = true;
                    }
                }
            }
            if (!portFound) {
                System.err.println("port " + defaultPort + " not found."); //user feedback
                System.exit(1);
            }
        }
    
        private void ListenOnPort(){
            try {
                serialPort = (SerialPort) portId.open("", 3000);
            } catch (PortInUseException e) {
                System.out.println("The serial port you are trying to use is currently in use");
            }
            
            try {
                inputStream = serialPort.getInputStream();
            } catch (IOException e) {
            }
            try {
                serialPort.addEventListener(this);
            } catch (TooManyListenersException e) {
            }
            // activate the DATA_AVAILABLE notifier
            serialPort.notifyOnDataAvailable(true);
            try {
               
                serialPort.setSerialPortParams(4800,
                        SerialPort.DATABITS_8,
                        SerialPort.STOPBITS_1,
                        SerialPort.PARITY_NONE);
            } catch (UnsupportedCommOperationException e) {
            }
         
            readThread = new Thread(this);
            readThread.start();
        }
    
        @Override
        public void serialEvent(SerialPortEvent event) {
    
            switch (event.getEventType()) {
                case SerialPortEvent.BI:   // Break interrupt
                case SerialPortEvent.OE: // Overrun error
                case SerialPortEvent.FE: // Framing error
                case SerialPortEvent.PE: // Parity error
                case SerialPortEvent.CD: //Carrier detected
                case SerialPortEvent.CTS://Clear to send
                case SerialPortEvent.DSR:// Data set ready
                case SerialPortEvent.RI: // Ring indicator
                case SerialPortEvent.OUTPUT_BUFFER_EMPTY:
                    break; //Buffer empty
                case SerialPortEvent.DATA_AVAILABLE: //Data Available to be read
                 
    
                    byte[] readBuffer = new byte[20]; 
    
                    try {
                      
                        while (inputStream.available() > 0) {
                            int numBytes = inputStream.read(readBuffer);
                        }
                      
                        String result = new String(readBuffer);
                        System.out.println(result);
                    } catch (IOException e) {
                    }
                    break;
            }
    
        }
    
        public static void main(String[] args) {
            new Main();
        }
    }

    This is the getPort() method:
    Code:
        private void getPort() {
            portFound = false;
            String osname = System.getProperty("os.name").toLowerCase();
            if (osname.startsWith("windows")) {
                // windows
                defaultPort = "COM1";
            } else if (osname.startsWith("linux")) {
                // linux
                defaultPort = "/dev/ttyS0";
            } else if (osname.startsWith("mac")) {
                // mac
                defaultPort = "/dev/cuaa0";
            } else {
                defaultPort = null;
                System.out.println("Sorry, your operating system is not supported");
            }
    
    
            portList = CommPortIdentifier.getPortIdentifiers();
           while ((portList.hasMoreElements()) && !(portFound)) {
                portId = (CommPortIdentifier) portList.nextElement();
                if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
    
                    if (portId.getName().equals(defaultPort)) {
                        System.out.println("Found port: " + defaultPort);
                        portFound = true;
                    }
                }
            }
            if (!portFound) {
                System.err.println("port " + defaultPort + " not found."); //user feedback
                System.exit(1);
            }
        }


    Thank you in advance.

  • #9
    Regular Coder
    Join Date
    Feb 2008
    Location
    Edinburgh - Scotland
    Posts
    107
    Thanks
    0
    Thanked 12 Times in 12 Posts
    And before I look into this...your computer has com ports right?!

  • #10
    New Coder
    Join Date
    Dec 2010
    Posts
    17
    Thanks
    1
    Thanked 0 Times in 0 Posts
    Quote Originally Posted by renegadeandy View Post
    And before I look into this...your computer has com ports right?!
    yes.... in fact, it has com1 and com2

    even tried it on my friends computer who's running ubtunu, he has the port /dev/ttyS0

    but still no luck... I really can't understand why it's not working... I've been through the code so many times, and checked everything, but it's just not working....


  •  

    Tags for this Thread

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •