Java串口写/发送ASCII数据 [英] Java serial port write/send ASCII data

查看:490
本文介绍了Java串口写/发送ASCII数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题是我需要通过蓝牙在Java中控制移动机器人E-puck,通过发送命令如D,100,100来设置速度,E以获得速度等等。我有一些代码:

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:

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

所以用这个方法我只能这样做发送 byte [] 数据,但我的机器人不会理解。
例如以前我一直在Matlab上使用这个命令:

So with this method write I can only send byte[] data, but my robot won't understand that. For example previously I have been using this commands on Matlab like that:

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

或仅限于程序Putty类型:

Or on program Putty type only:

D,100,100 `enter`

其他信息:

我也想通了,Matlab还有另一个解决方案。

I've also figured out, that Matlab has another solution for same thing.

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

在这种情况下:

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

在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);

然后:

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


推荐答案

代码注释中的主要细节。现在,您可以通过在命令窗口 D,1000,-500 中键入并按下回车来更改车轮速度。

Main details in code comments. Now you can change wheel speed by typing in command window D,1000,-500 and hitting 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();
                }
        }
}

这篇关于Java串口写/发送ASCII数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆