Android串口例子

一个月后需要参加新大陆的物联网大赛,这几天开始集训了,我负责 Android这一块,这里面需要用到android串口技术,然后就轰轰烈烈就开始做了,查资料。终于在今天做出来了一个,废话了,赶紧来。

 

这里需要用到官方提供的例程源代码开源的串口类android-serialport-api。其主页在这里http://code.google.com/p/android-serialport-api/ 但是下载下来发现并不知道怎么用,然后就又查资料。主要还是借鉴这位仁兄的。http://lpcjrflsa.iteye.com/blog/2097280

1  首先做的是创建新的工程然后添加一下文件



我所说的添加的文件并不是和官方提供的例程源代码开源的串口类android-serialport-api。完全一样 我下的就是完全一样的  ,这个官方的好像是新的或是旧的,就两句代码是不样的

还有几处就不一一点出了,总之差别不大,多一个Tag参数,不过新手还是别管他。最好用我提供的代码。第一次发不知道怎么附件代码,一会再说把。

 2 布局

接下来就是先写个布局呗,这是我写的 比我看到的Demo我有添加了一个清除接收数据的按钮。

我想这种问题你们都不是事,/!!!!!!!!!!!这几个粉红色的字是按钮控件,我把背景设成透明了别误会了。


3代码

好了 然后就是关于这个页面的Code了,

这是我的:

  1. package android.serialport;  
  2.    
  3. import java.io.File;  
  4. import java.io.FileInputStream;  
  5. import java.io.FileOutputStream;  
  6. import java.io.IOException;  
  7. import java.text.BreakIterator;  
  8. import java.util.ServiceConfigurationError;  
  9.    
  10. import android.os.Bundle;  
  11. import android.app.Activity;  
  12. import android.view.Menu;  
  13. import android.view.View;  
  14. import android.view.View.OnClickListener;  
  15. import android.view.Window;  
  16. import android.widget.Button;  
  17. import android.widget.EditText;  
  18. import android.widget.Toast;  
  19.    
  20. public class MyserialActivity extendsActivity  
  21. {  
  22.           EditText sendedit;  
  23.           EditText receiveedit;  
  24.           FileInputStream mInStream;  
  25.           FileOutputStream mOutStream;  
  26.           SerialPort classserialport;  
  27.           ReadThread mReadThread;  
  28.             
  29.           private class ReadThread extends Thread  
  30.           {  
  31.                     public void run()  
  32.                     {  
  33.                              super.run();  
  34.                              while(!isInterrupted())  
  35.                              {  
  36.                                       int size;  
  37.                              }  
  38.                     }  
  39.           }  
  40.             
  41.             
  42.           void onDataReceive(final byte[] buffer,finalint size)  
  43.           {  
  44.                     runOnUiThread(new Runnable()  
  45.                    {  
  46.                              
  47.                             @Override  
  48.                             publicvoid run()  
  49.                             {  
  50.                                      // TODO Auto-generated method stub  
  51.                             if(mReadThread  != null)  
  52.                             {  
  53.                                      receiveedit.append(newString(buffer,0,size));  
  54.                             }  
  55.                             }  
  56.                    });  
  57.           }  
  58.          @Override  
  59.          protectedvoid onCreate(Bundle savedInstanceState)  
  60.          {  
  61.                    super.onCreate(savedInstanceState);  
  62.                    this.requestWindowFeature(Window.FEATURE_NO_TITLE);  
  63.                    setContentView(R.layout.activity_myserial);  
  64.           
  65.                    sendedit= (EditText)findViewById(R.id.editText1);  
  66.                    receiveedit=(EditText)findViewById(R.id.editText2);  
  67.                     
  68.                     
  69.                    receiveedit.setFocusable(false);//进制输入  
  70.                    /* 
  71.                     * 打开串口 
  72.                     * */  
  73.                    finalButton openserial =(Button)findViewById(R.id.button1);  
  74.                    openserial.setOnClickListener(newView.OnClickListener()  
  75.                    {  
  76.                              
  77.                             @Override  
  78.                             publicvoid onClick(View arg0)  
  79.                             {  
  80.                                      //TODO Auto-generated method stub  
  81.                                      try  
  82.                                      {  
  83.                                                classserialport=new SerialPort(new File("/dev/ttyS2"),9600);  
  84.                                      }catch(SecurityExceptione)  
  85.                                      {  
  86.                                                e.printStackTrace();  
  87.                                      }  
  88.                                      catch(IOExceptione)  
  89.                                      {  
  90.                                                e.printStackTrace();  
  91.                                      }  
  92.                                      mInStream=(FileInputStream) classserialport.getInputStream();  
  93.                                      Toast.makeText(MyserialActivity.this,"串口打开成功",Toast.LENGTH_SHORT).show();  
  94.                             }  
  95.                    });  
  96.          /* 
  97.           * 发送数据 
  98.           * */  
  99.                    finalButton sendButton =(Button)findViewById(R.id.button2);  
  100.                    sendButton.setOnClickListener(newView.OnClickListener()  
  101.                    {  
  102.                              
  103.                             @Override  
  104.                             publicvoid onClick(View arg0)  
  105.                             {  
  106.                                       
  107.                                      Stringindata;  
  108.                                      indata=sendedit.getText().toString();  
  109.                                      //TODO Auto-generated method stub  
  110.                                      try  
  111.                                      {  
  112.                                                mOutStream=(FileOutputStream) classserialport.getOutputStream();  
  113.                                                mOutStream.write(indata.getBytes());  
  114.                                                mOutStream.write('\n');  
  115.                                      }  
  116.                                      catch(IOExceptione)  
  117.                                      {  
  118.                                                e.printStackTrace();  
  119.                                      }  
  120.                                      Toast.makeText(MyserialActivity.this,"数据发送成功",Toast.LENGTH_SHORT).show();  
  121.                                      sendedit.setText("");  
  122.                             }  
  123.                    });  
  124.          /* 
  125.           * 接收数据 
  126.           * */          
  127.                    finalButton receButton= (Button)findViewById(R.id.button3);  
  128.                    receButton.setOnClickListener(newView.OnClickListener()  
  129.                    {//inttag =0;  
  130.                              
  131.                             @Override  
  132.                             publicvoid onClick(View arg0)  
  133.                             {  
  134.                                      // TODO Auto-generated method stub  
  135.                                      intsize;  
  136.                                      try  
  137.                                      {  
  138.                                                byte[]buffer = new byte[64];  
  139.                                                if(mInStream== nullreturn;  
  140.                                                size= mInStream.read(buffer);  
  141.                                                if(size>0)  
  142.                                                {  
  143.                                                         receiveedit.setText("");  
  144.                                                          
  145.                                                }  
  146.                                                if(size>0)  
  147.                                                {  
  148.                                                         onDataReceive(buffer,size);  
  149.                                                }  
  150.                                                         inttag =1;  
  151.                                                          
  152.                                                         receiveedit.setText(newString(buffer, 0, size));  
  153.    
  154.                                      }catch(IOExceptione)  
  155.                                      {  
  156.                                                e.printStackTrace();  
  157.                                                return;  
  158.                                      }  
  159.                             }  
  160.    
  161.                             privateboolean isInterrupted()  
  162.                             {  
  163.                                       // TODO Auto-generated methodstub  
  164.                                      returnfalse;  
  165.                             }  
  166.                    });  
  167.                    /* 
  168.                     * 清楚接收区 
  169.                     * */  
  170.                    finalButton ClearButton = (Button)findViewById(R.id.clear);  
  171.                    ClearButton.setOnClickListener(newView.OnClickListener()  
  172.                    {  
  173.                              
  174.                             @Override  
  175.                             publicvoid onClick(View arg0)  
  176.                             {  
  177.                                      //TODO Auto-generated method stub  
  178.                                      receiveedit.setText("");  
  179.                             }  
  180.                    });  
  181.                     
  182.                     
  183.                     
  184.          }  
  185.    
  186.          @Override  
  187.          publicboolean onCreateOptionsMenu(Menu menu)  
  188.          {  
  189.                    //Inflate the menu; this adds items to the action bar if it is present.  
  190.                    getMenuInflater().inflate(R.menu.myserial,menu);  
  191.                    returntrue;  
  192.          }  
  193.    
  194. }  

好吧  你做好了。

3需要加载的文件

下面我把所需要添加的代码贴一贴

第一个是Serialport.Java

  1. /* 
  2.  * Copyright 2009 Cedric Priscal 
  3.  *  
  4.  * Licensed under the Apache License, Version 2.0 (the "License"); 
  5.  * you may not use this file except in compliance with the License. 
  6.  * You may obtain a copy of the License at 
  7.  *  
  8.  * http://www.apache.org/licenses/LICENSE-2.0 
  9.  *  
  10.  * Unless required by applicable law or agreed to in writing, software 
  11.  * distributed under the License is distributed on an "AS IS" BASIS, 
  12.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
  13.  * See the License for the specific language governing permissions and 
  14.  * limitations under the License.  
  15.  */  
  16.   
  17. package android.serialport;  
  18.   
  19. import java.io.File;  
  20. import java.io.FileDescriptor;  
  21. import java.io.FileInputStream;  
  22. import java.io.FileOutputStream;  
  23. import java.io.IOException;  
  24. import java.io.InputStream;  
  25. import java.io.OutputStream;  
  26.   
  27. import android.util.Log;  
  28.   
  29. public class SerialPort {  
  30.   
  31.     private static final String TAG = "SerialPort";  
  32.   
  33.     /* 
  34.      * Do not remove or rename the field mFd: it is used by native method close(); 
  35.      */  
  36.     private FileDescriptor mFd;  //创建一个文件描述符对象 mFd  
  37.     private FileInputStream mFileInputStream;  
  38.     private FileOutputStream mFileOutputStream;  
  39.   
  40.     public SerialPort(File device, int baudrate) throws SecurityException, IOException {  
  41. /* 
  42.  * 检查访问权限 
  43.  * */  
  44.         /* Check access permission */  
  45.         if (!device.canRead() || !device.canWrite()) {//如果设备不可读或者设备不可写  
  46.             try {  
  47.                 /* Missing read/write permission, trying to chmod the file *///没有读写权限,就尝试去挂载权限  
  48.                 Process su; //流程进程  su  
  49.                 su = Runtime.getRuntime().exec("/system/bin/su");//通过执行挂载到/system/bin/su 获得执行  
  50.                 String cmd = "chmod 777 " + device.getAbsolutePath() + "\n"  
  51.                         + "exit\n";  
  52.                 /*String cmd = "chmod 777 /dev/s3c_serial0" + "\n" 
  53.                 + "exit\n";*/  
  54.                 su.getOutputStream().write(cmd.getBytes());//进程。获得输出流。写(命令。获得二进制)   
  55.                 if ((su.waitFor() != 0) || !device.canRead()  
  56.                         || !device.canWrite()) {//如果 进程等待不是0 或者 设备不能读写就  
  57.                     throw new SecurityException();//抛出一个权限异常  
  58.                 }  
  59.             } catch (Exception e) {  
  60.                 e.printStackTrace();  
  61.                 throw new SecurityException();  
  62.             }  
  63.         }  
  64. /* 
  65.  *  
  66.  * */  
  67.         mFd = open(device.getAbsolutePath(), baudrate);  
  68.         //device.getAbsolutePath()这是要挂载的路径new File("/dev/ttyS2")  
  69.         if (mFd == null) {  
  70.             Log.e(TAG, "native open returns null");  
  71.             throw new IOException();//输入输出异常  
  72.         }  
  73.         //将文件描述符       做输入输出流的参数      传递给创建的输入输出流  
  74.         mFileInputStream = new FileInputStream(mFd);  
  75.         mFileOutputStream = new FileOutputStream(mFd);  
  76.     }  
  77.   
  78.     // Getters and setters  
  79.     public InputStream getInputStream() {  
  80.         return mFileInputStream;  
  81.     }  
  82.   
  83.     public OutputStream getOutputStream() {  
  84.         return mFileOutputStream;  
  85.     }  
  86.   
  87.     // JNI  
  88.     private native static FileDescriptor open(String path, int baudrate);  
  89.     public native void close();  
  90.     static {  
  91.         System.loadLibrary("serial_port");  
  92.     }  
  93. }  

第二个是SerialPortFinder.java
  1. /* 
  2.  * Copyright 2009 Cedric Priscal 
  3.  *  
  4.  * Licensed under the Apache License, Version 2.0 (the "License"); 
  5.  * you may not use this file except in compliance with the License. 
  6.  * You may obtain a copy of the License at 
  7.  *  
  8.  * http://www.apache.org/licenses/LICENSE-2.0 
  9.  *  
  10.  * Unless required by applicable law or agreed to in writing, software 
  11.  * distributed under the License is distributed on an "AS IS" BASIS, 
  12.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
  13.  * See the License for the specific language governing permissions and 
  14.  * limitations under the License.  
  15.  */  
  16.   
  17. package android.serialport;  
  18.   
  19. import java.io.File;  
  20. import java.io.FileReader;  
  21. import java.io.IOException;  
  22. import java.io.LineNumberReader;  
  23. import java.util.Iterator;  
  24. import java.util.Vector;  
  25.   
  26. import android.util.Log;  
  27.   
  28. public class SerialPortFinder {  
  29.   
  30.     /* 
  31.      * 创建一个驱动程序类 
  32.      * */  
  33.     public class Driver {  
  34.         public Driver(String name, String root) {  
  35.             mDriverName = name;//String 类型的  
  36.             mDeviceRoot = root;  
  37.         }  
  38.         private String mDriverName;  
  39.         private String mDeviceRoot;  
  40.         Vector<File> mDevices = null;  
  41.         /* 
  42.          * Vector 类在 java 中可以实现自动增长的对象数组 
  43.          * 简单的使用方法如下: 
  44.         vector<int> test;//建立一个vector 
  45.         test.push_back(1); 
  46.         test.push_back(2);//把1和2压入vector这样test[0]就是1,test[1]就是2 
  47.          * */  
  48.         public Vector<File> getDevices() {  
  49.             if (mDevices == null) {  
  50.                 mDevices = new Vector<File>();  
  51.                 File dev = new File("/dev");  
  52.                 File[] files = dev.listFiles();  
  53.                 int i;  
  54.                 for (i=0; i<files.length; i++) {  
  55.                     if (files[i].getAbsolutePath().startsWith(mDeviceRoot)) {  
  56.                         Log.d(TAG, "Found new device: " + files[i]);  
  57.                         mDevices.add(files[i]);  
  58.                     }  
  59.                 }  
  60.             }  
  61.             return mDevices;  
  62.         }  
  63.           
  64.         public String getName() {  
  65.             return mDriverName;  
  66.         }  
  67.     }  
  68. /* 
  69.  *  
  70.  *  
  71.  * */  
  72.     private static final String TAG = "SerialPort";  
  73.   
  74.     private Vector<Driver> mDrivers = null;  
  75.   
  76.     Vector<Driver> getDrivers() throws IOException {  
  77.         if (mDrivers == null) {  
  78.             mDrivers = new Vector<Driver>();  
  79.             LineNumberReader r = new LineNumberReader(new FileReader("/proc/tty/drivers"));  
  80.             String l;  
  81.             while((l = r.readLine()) != null) {  
  82.                 String[] w = l.split(" +");  
  83.                 if ((w.length == 5) && (w[4].equals("serial"))) {  
  84.                     Log.d(TAG, "Found new driver: " + w[1]);  
  85.                     mDrivers.add(new Driver(w[0], w[1]));  
  86.                 }  
  87.             }  
  88.             r.close();  
  89.         }  
  90.         return mDrivers;  
  91.     }  
  92.   
  93.     public String[] getAllDevices() {  
  94.         Vector<String> devices = new Vector<String>();  
  95.         // Parse each driver  
  96.         Iterator<Driver> itdriv;  
  97.         try {  
  98.             itdriv = getDrivers().iterator();  
  99.             while(itdriv.hasNext()) {  
  100.                 Driver driver = itdriv.next();  
  101.                 Iterator<File> itdev = driver.getDevices().iterator();  
  102.                 while(itdev.hasNext()) {  
  103.                     String device = itdev.next().getName();  
  104.                     String value = String.format("%s (%s)", device, driver.getName());  
  105.                     devices.add(value);  
  106.                 }  
  107.             }  
  108.         } catch (IOException e) {  
  109.             e.printStackTrace();  
  110.         }  
  111.         return devices.toArray(new String[devices.size()]);  
  112.     }  
  113.   
  114.     public String[] getAllDevicesPath() {  
  115.         Vector<String> devices = new Vector<String>();  
  116.         // Parse each driver  
  117.         Iterator<Driver> itdriv;  
  118.         try {  
  119.             itdriv = getDrivers().iterator();  
  120.             while(itdriv.hasNext()) {  
  121.                 Driver driver = itdriv.next();  
  122.                 Iterator<File> itdev = driver.getDevices().iterator();  
  123.                 while(itdev.hasNext()) {  
  124.                     String device = itdev.next().getAbsolutePath();  
  125.                     devices.add(device);  
  126.                 }  
  127.             }  
  128.         } catch (IOException e) {  
  129.             e.printStackTrace();  
  130.         }  
  131.         return devices.toArray(new String[devices.size()]);  
  132.     }  
  133. }  

第三个是Android.mk
  1. #  
  2. # Copyright 2009 Cedric Priscal  
  3.   
  4. # Licensed under the Apache License, Version 2.0 (the "License");  
  5. # you may not use this file except in compliance with the License.  
  6. # You may obtain a copy of the License at  
  7.   
  8. # http://www.apache.org/licenses/LICENSE-2.0  
  9.   
  10. # Unless required by applicable law or agreed to in writing, software  
  11. # distributed under the License is distributed on an "AS IS" BASIS,  
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  
  13. # See the License for the specific language governing permissions and  
  14. # limitations under the License.   
  15. #  
  16.   
  17. LOCAL_PATH := $(call my-dir)  
  18.   
  19. include $(CLEAR_VARS)  
  20.   
  21. TARGET_PLATFORM := android-3  
  22. LOCAL_MODULE    := serial_port  
  23. LOCAL_SRC_FILES := SerialPort.c  
  24. LOCAL_LDLIBS    := -llog  
  25.   
  26. include $(BUILD_SHARED_LIBRARY)  

第四个是SerialPort.c
  1. /* 
  2.  * Copyright 2009 Cedric Priscal 
  3.  * 
  4.  * Licensed under the Apache License, Version 2.0 (the "License"); 
  5.  * you may not use this file except in compliance with the License. 
  6.  * You may obtain a copy of the License at 
  7.  * 
  8.  * http://www.apache.org/licenses/LICENSE-2.0 
  9.  * 
  10.  * Unless required by applicable law or agreed to in writing, software 
  11.  * distributed under the License is distributed on an "AS IS" BASIS, 
  12.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
  13.  * See the License for the specific language governing permissions and 
  14.  * limitations under the License. 
  15.  */  
  16.   
  17. #include <termios.h>  
  18. #include <unistd.h>  
  19. #include <sys/types.h>  
  20. #include <sys/stat.h>  
  21. #include <fcntl.h>  
  22. #include <string.h>  
  23. #include <jni.h>  
  24.   
  25. #include "android/log.h"  
  26. static const charchar *TAG="serial_port";  
  27. #define LOGI(fmt, args...) __android_log_print(ANDROID_LOG_INFO,  TAG, fmt, ##args)  
  28. #define LOGD(fmt, args...) __android_log_print(ANDROID_LOG_DEBUG, TAG, fmt, ##args)  
  29. #define LOGE(fmt, args...) __android_log_print(ANDROID_LOG_ERROR, TAG, fmt, ##args)  
  30.   
  31. static speed_t getBaudrate(jint baudrate)  
  32. {  
  33.     switch(baudrate) {  
  34.     case 0return B0;  
  35.     case 50return B50;  
  36.     case 75return B75;  
  37.     case 110return B110;  
  38.     case 134return B134;  
  39.     case 150return B150;  
  40.     case 200return B200;  
  41.     case 300return B300;  
  42.     case 600return B600;  
  43.     case 1200return B1200;  
  44.     case 1800return B1800;  
  45.     case 2400return B2400;  
  46.     case 4800return B4800;  
  47.     case 9600return B9600;  
  48.     case 19200return B19200;  
  49.     case 38400return B38400;  
  50.     case 57600return B57600;  
  51.     case 115200return B115200;  
  52.     case 230400return B230400;  
  53.     case 460800return B460800;  
  54.     case 500000return B500000;  
  55.     case 576000return B576000;  
  56.     case 921600return B921600;  
  57.     case 1000000return B1000000;  
  58.     case 1152000return B1152000;  
  59.     case 1500000return B1500000;  
  60.     case 2000000return B2000000;  
  61.     case 2500000return B2500000;  
  62.     case 3000000return B3000000;  
  63.     case 3500000return B3500000;  
  64.     case 4000000return B4000000;  
  65.     defaultreturn -1;  
  66.     }  
  67. }  
  68.   
  69. /* 
  70.  * Class:     cedric_serial_SerialPort 
  71.  * Method:    open 
  72.  * Signature: (Ljava/lang/String;)V 
  73.  */  
  74. JNIEXPORT jobject JNICALL Java_android_serialport_SerialPort_open  
  75.   (JNIEnv *env, jobject thiz, jstring path, jint baudrate)  
  76. {  
  77.     int fd;  
  78.     speed_t speed;  
  79.     jobject mFileDescriptor;  
  80.   
  81.     /* Check arguments */  
  82.     {  
  83.         speed = getBaudrate(baudrate);  
  84.         if (speed == -1) {  
  85.             /* TODO: throw an exception */  
  86.             LOGE("Invalid baudrate");  
  87.             return NULL;  
  88.         }  
  89.     }  
  90.   
  91.     /* Opening device */  
  92.     {  
  93.         jboolean iscopy;  
  94.         const charchar *path_utf = (*env)->GetStringUTFChars(env, path, &iscopy);  
  95.         LOGD("Opening serial port %s", path_utf);  
  96.         fd = open(path_utf, O_RDWR | O_DIRECT | O_SYNC);  
  97.         LOGD("open() fd = %d", fd);  
  98.         (*env)->ReleaseStringUTFChars(env, path, path_utf);  
  99.         if (fd == -1)  
  100.         {  
  101.             /* Throw an exception */  
  102.             LOGE("Cannot open port");  
  103.             /* TODO: throw an exception */  
  104.             return NULL;  
  105.         }  
  106.     }  
  107.   
  108.     /* Configure device */  
  109.     {  
  110.         struct termios cfg;  
  111.         LOGD("Configuring serial port");  
  112.         if (tcgetattr(fd, &cfg))  
  113.         {  
  114.             LOGE("tcgetattr() failed");  
  115.             close(fd);  
  116.             /* TODO: throw an exception */  
  117.             return NULL;  
  118.         }  
  119.   
  120.         cfmakeraw(&cfg);  
  121.         cfsetispeed(&cfg, speed);  
  122.         cfsetospeed(&cfg, speed);  
  123.   
  124.         if (tcsetattr(fd, TCSANOW, &cfg))  
  125.         {  
  126.             LOGE("tcsetattr() failed");  
  127.             close(fd);  
  128.             /* TODO: throw an exception */  
  129.             return NULL;  
  130.         }  
  131.     }  
  132.   
  133.     /* Create a corresponding file descriptor */  
  134.     {  
  135.         jclass cFileDescriptor = (*env)->FindClass(env, "java/io/FileDescriptor");  
  136.         jmethodID iFileDescriptor = (*env)->GetMethodID(env, cFileDescriptor, "<init>""()V");  
  137.         jfieldID descriptorID = (*env)->GetFieldID(env, cFileDescriptor, "descriptor""I");  
  138.         mFileDescriptor = (*env)->NewObject(env, cFileDescriptor, iFileDescriptor);  
  139.         (*env)->SetIntField(env, mFileDescriptor, descriptorID, (jint)fd);  
  140.     }  
  141.   
  142.     return mFileDescriptor;  
  143. }  
  144.   
  145. /* 
  146.  * Class:     cedric_serial_SerialPort 
  147.  * Method:    close 
  148.  * Signature: ()V 
  149.  */  
  150. JNIEXPORT void JNICALL Java_android_serialport_SerialPort_close  
  151.   (JNIEnv *env, jobject thiz)  
  152. {  
  153.     jclass SerialPortClass = (*env)->GetObjectClass(env, thiz);  
  154.     jclass FileDescriptorClass = (*env)->FindClass(env, "java/io/FileDescriptor");  
  155.   
  156.     jfieldID mFdID = (*env)->GetFieldID(env, SerialPortClass, "mFd""Ljava/io/FileDescriptor;");  
  157.     jfieldID descriptorID = (*env)->GetFieldID(env, FileDescriptorClass, "descriptor""I");  
  158.   
  159.     jobject mFd = (*env)->GetObjectField(env, thiz, mFdID);  
  160.     jint descriptor = (*env)->GetIntField(env, mFd, descriptorID);  
  161.   
  162.     LOGD("close(fd = %d)", descriptor);  
  163.     close(descriptor);  
  164. }  

接下来还要添加库这个需要添加文件(文件一会再传)一会给你们一个例子自己可以裁剪。



4运行

这个串口通讯就完成了。

接下来就需要用在Windows  中的DOS下进行一下操作//这样是为了打开串口Com2   获得串口权限 (如果adb    emulator 不是内部外部命令的话就去配置环境变量那就去百度一下怎么配置adb  和  emulator.的环境变量。




运行后把APP装进去 

然后下载一个串口调试助手  就可以进行调试了。

你就一台电脑而且没有串口线的时候你就可以下载一个虚拟串口软件 我今天才发现的神器名字是Configure Virtual Serial Port Driver


自己做的   程序源代码  实例在这里  你们可以下载一下http://download.csdn.NET/detail/csdnhejingzhou/9181897

然后看结果


本文章借鉴了http://lpcjrflsa.iteye.com/blog/2097280。

  • 0
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值