Android接入RS232-新闻详情

Android接入RS232


发布时间:2017-07-26责任编辑:朱明 浏览:2449


接入代码主要是使用一个开源项目:http://code.google.com/p/android-serialport-api/

首先现在下载SDK以及demo

平板连接仪器后,进入Setup界面,查看端口路径。

1.png

Demo中的代码示例较多,可以收集所有串口信息。

实际应用中,我们往往不需要如此多的功能,也不需要用户去选择串口。

我们只需要知道设备使用的几号串口,然后把串口路径记下来就好了。

private String path = "/dev/ttyS0";

public void onCreate() throws SecurityException, IOException {

           try {

                 mSerialPort = new SerialPort(new File(path), baudrate);

                 mOutputStream = mSerialPort.getOutputStream();

                 mInputStream = mSerialPort.getInputStream();

                

                 mReadThread = new ReadThread();

                 isStop = false;

                 mReadThread.start();

           }

      }

 

public SerialPort(File device, int baudrate) throws SecurityException, IOException {

           mFd = open(device.getAbsolutePath(), baudrate);

           if (mFd == null) {

                 throw new IOException();

           }

           mFileInputStream = new FileInputStream(mFd);

           mFileOutputStream = new FileOutputStream(mFd);

      }

 

注意事项:

一、      baudrateDataBitsStopBits的设置,如果与设备的参数设置不同,那么就无法进行通信。

二、      接入前与硬件方进行充分沟通。因为设备的数个串口,有时可能会有硬件问题,例如com0串口通讯不稳定,但是com1com2com3就没这个问题。

三、      平板开机启动程序的话,串口通讯尽量不要立即开启。因为根据平板的不同,串口驱动有时没能立即启动,需要开机后过几秒才有效。


春秋工作室  供稿