简体   繁体   English

Java串行端口写入/发送ASCII数据

[英]Java serial port write/send ASCII data

My problem is that I need to control mobile robot E-puck via Bluetooth in Java, by sending it commands like "D,100,100" to set speed, "E" to get speed, and etc. I have some code: 我的问题是我需要通过Java中的蓝牙控制移动机器人E-puck,方法是发送诸如“ D,100,100”来设置速度,“ E”来获得速度等命令。我有一些代码:

String command = "D,100,100";
OutputStream mOutputToPort = serialPort.getOutputStream();
mOutputToPort.write(command.getBytes());

So with this method write I can only send byte[] data, but my robot won't understand that. 因此,使用这种write方法,我只能发送byte[]数据,但我的机器人无法理解。 For example previously I have been using this commands on Matlab like that: 例如,以前我一直在Matlab上使用以下命令:

s = serial('COM45');
fopen(s);
fprintf(s,'D,100,100','async');

Or on program Putty type only: 或仅在程序腻子类型上:

D,100,100 `enter`

Additional info: 附加信息:

I've also figured out, that Matlab has another solution for same thing. 我还发现,Matlab对于同一件事有另一种解决方案。

s = serial('COM45');
fopen(s);
data=[typecast(int8('-D'),'int8') typecast(int16(500),'int8') typecast(int16(500),'int8')];

In this case: 在这种情况下:

data = [  -68  -12    1  -12    1];
fwrite(s,data,'int8','async');

Wouldn't it be the same in Java: 在Java中不是一样的:

  byte data[] = new byte[5];
  data[0] = -'D';
  data[1] = (byte)(500 & 0xFF);
  data[2] = (byte)(500 >> 8);
  data[3] = (byte)(500 & 0xFF);
  data[4] = (byte)(500>> 8);

And then: 接着:

OutputStream mOutputToPort = serialPort.getOutputStream();
mOutputToPort.write(data);
mOutputToPort.flush();

Main details in code comments. 代码注释中的主要详细信息。 Now you can change wheel speed by typing in command window D,1000,-500 and hitting enter. 现在,您可以通过在命令窗口D,1000,-500键入并按Enter键来更改轮速。

public class serialRobot {

        public static void main(String[] s) {
                SerialPort serialPort = null;
                try {
                        CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier("COM71");
                        if (portIdentifier.isCurrentlyOwned()) {
                                System.out.println("Port in use!");
                        } else {
                                System.out.println(portIdentifier.getName());

                                serialPort = (SerialPort) portIdentifier.open(
                                                "ListPortClass", 300);
                                int b = serialPort.getBaudRate();
                                System.out.println(Integer.toString(b));
                                serialPort.setSerialPortParams(115200, SerialPort.DATABITS_8,
                                                SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
                                serialPort.setInputBufferSize(65536);
                                serialPort.setOutputBufferSize(4096);

                                System.out.println("Opened " + portIdentifier.getName());

                                OutputStream mOutputToPort = serialPort.getOutputStream();
                                InputStream mInputFromPort = serialPort.getInputStream();


                                PerpetualThread t = readAndPrint(mInputFromPort);

                                inputAndSend(mOutputToPort);


                                t.stopRunning();

                                mOutputToPort.close();
                                mInputFromPort.close();
                        }
                } catch (IOException ex) {
                        System.out.println("IOException : " + ex.getMessage());
                } catch (UnsupportedCommOperationException ex) {
                        System.out.println("UnsupportedCommOperationException : " + ex.getMessage());
                } catch (NoSuchPortException ex) {
                        System.out.println("NoSuchPortException : " + ex.getMessage());
                } catch (PortInUseException ex) {
                        System.out.println("PortInUseException : " + ex.getMessage());
                } finally {
                        if(serialPort != null) {
                                serialPort.close();
                        }
                }

        }

        private static PerpetualThread readAndPrint(InputStream in) {
                final BufferedInputStream b = new BufferedInputStream(in);
                PerpetualThread thread = new PerpetualThread() {

                        @Override
                        public void run() {
                                byte[] data = new byte[16];
                                int len = 0;
                                for(;isRunning();) {
                                        try {
                                                len = b.read(data);
                                        } catch (IOException e) {
                                                e.printStackTrace();
                                        }
                                        if(len > 0) {
                                                System.out.print(new String(data, 0, len));
                                        }
                                }
                        }

                };

                thread.start();

                return thread;
        }

        private static void inputAndSend(OutputStream out) {
                BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
                int k = 0;
                for(;;) {

                        String komanda;
                        try {
                                komanda = in.readLine();
                        } catch (IOException e) {
                                e.printStackTrace();
                                return;
                        }
                        komanda = komanda.trim();

                        if(komanda.equalsIgnoreCase("end"))       return;

                        byte komandaSiust[] = proces(komanda); //Command we send after first 

//connection, it's byte array where 0 member is the letter that describes type of command, next two members 

// is about left wheel speed, and the last two - right wheel speed.



                        try {
                               if(k == 0){
                                String siunc = "P,0,0\n"; // This command must be sent first time, when robot is connected, otherwise other commands won't work
                                ByteBuffer bb = ByteBuffer.wrap(siunc.getBytes("UTF-8"));
                                bb.order(ByteOrder.LITTLE_ENDIAN);
                                out.write(bb.array());
                                out.flush();      
                               }else{
                               ByteBuffer bb = ByteBuffer.wrap(komandaSiust);
                               bb.order(ByteOrder.LITTLE_ENDIAN);
                               out.write(bb.array());
                               out.flush();
                               }
                               k++;

                        } catch (IOException e) {
                                e.printStackTrace();
                                return;
                        }
                }
        }

        private static byte[] proces(String tekstas){
            tekstas = tekstas.trim();
            char[] charArray = tekstas.toCharArray();
            byte kodas1[];



            int fComa = tekstas.indexOf(',', 1);
            int sComa = tekstas.indexOf(',', 2);
            int matavimas = charArray.length;
            int skir1 = sComa - fComa - 1;
            int skir2 = matavimas - sComa -1;

            char leftSpeed[] = new char[skir1];

            for(int i = 0; i < skir1; i++){
                  leftSpeed[i] = charArray[fComa + i + 1];
            }

            char rightSpeed[] = new char[skir2];

            for(int i = 0; i < skir2; i++){
                rightSpeed[i] = charArray[sComa + i + 1];
            }
            String right = String.valueOf(rightSpeed);
            String left = String.valueOf(leftSpeed);


            int val1 = Integer.parseInt(left);
            int val2 = Integer.parseInt(right);
            kodas1 = new byte[5];
            kodas1[0] = (byte)-charArray[0];
            kodas1[1] = (byte)(val1 & 0xFF);
            kodas1[2] = (byte)(val1 >> 8);
            kodas1[3] = (byte)(val2 & 0xFF);
            kodas1[4] = (byte)(val2 >> 8);

            return kodas1;


        }

        private static class PerpetualThread extends Thread {
                private boolean isRunning = true;

                public boolean isRunning() {    return isRunning;       }

                public void stopRunning()       {
                        isRunning = false;
                        this.interrupt();
                }
        }
}

According to the documentation , you need to call setSerialPortParams(int baudrate, int dataBits, int stopBits, int parity) on your serial port. 根据文档 ,您需要在串行端口上调用setSerialPortParams(int baudrate, int dataBits, int stopBits, int parity)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM