java serial communication

Solutions on MaxInterview for java serial communication by the best coders in the world

showing results for - "java serial communication"
Maria José
10 Oct 2019
1import java.util.Scanner;
2import javax.swing.JFrame;
3import javax.swing.JSlider;
4import j.extensions.comm.*;
5 
6public class Main {
7 
8        public static void main(String[] args) {
9                // create a window with a slider
10                JFrame window = new JFrame();
11                JSlider slider = new JSlider();
12                slider.setMaximum(1023);
13                window.add(slider);
14                window.pack();
15                window.setVisible(true);
16               
17                // determine which serial port to use
18                SerialComm ports[] = SerialComm.getCommPorts();
19                System.out.println("Select a port:");
20                int i = 1;
21                for(SerialComm port : ports) {
22                        System.out.println(i++ + ". " + port.getSystemPortName());
23                }
24                Scanner s = new Scanner(System.in);
25                int chosenPort = s.nextInt();
26
27                // open and configure the port
28                SerialComm port = ports[chosenPort - 1];
29                if(port.openPort()) {
30                        System.out.println("Successfully opened the port.");
31                } else {
32                        System.out.println("Unable to open the port.");
33                        return;
34                }
35                port.setComPortTimeouts(SerialComm.TIMEOUT_READ_SEMI_BLOCKING, 0, 0);
36               
37                // enter into an infinite loop that reads from the port and updates the GUI
38                Scanner data = new Scanner(port.getInputStream());
39                while(data.hasNextLine()) {
40                        int number = 0;
41                        try{number = Integer.parseInt(data.nextLine());}catch(Exception e){}
42                        slider.setValue(number);
43                }
44        }
45
46}
47