当前位置:   article > 正文

Android串口例子_android串口编程实例

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

好吧  你做好了。

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. package android.serialport;
  17. import java.io.File;
  18. import java.io.FileDescriptor;
  19. import java.io.FileInputStream;
  20. import java.io.FileOutputStream;
  21. import java.io.IOException;
  22. import java.io.InputStream;
  23. import java.io.OutputStream;
  24. import android.util.Log;
  25. public class SerialPort {
  26. private static final String TAG = "SerialPort";
  27. /*
  28. * Do not remove or rename the field mFd: it is used by native method close();
  29. */
  30. private FileDescriptor mFd; //创建一个文件描述符对象 mFd
  31. private FileInputStream mFileInputStream;
  32. private FileOutputStream mFileOutputStream;
  33. public SerialPort(File device, int baudrate) throws SecurityException, IOException {
  34. /*
  35. * 检查访问权限
  36. * */
  37. /* Check access permission */
  38. if (!device.canRead() || !device.canWrite()) {//如果设备不可读或者设备不可写
  39. try {
  40. /* Missing read/write permission, trying to chmod the file *///没有读写权限,就尝试去挂载权限
  41. Process su; //流程进程 su
  42. su = Runtime.getRuntime().exec("/system/bin/su");//通过执行挂载到/system/bin/su 获得执行
  43. String cmd = "chmod 777 " + device.getAbsolutePath() + "\n"
  44. + "exit\n";
  45. /*String cmd = "chmod 777 /dev/s3c_serial0" + "\n"
  46. + "exit\n";*/
  47. su.getOutputStream().write(cmd.getBytes());//进程。获得输出流。写(命令。获得二进制)
  48. if ((su.waitFor() != 0) || !device.canRead()
  49. || !device.canWrite()) {//如果 进程等待不是0 或者 设备不能读写就
  50. throw new SecurityException();//抛出一个权限异常
  51. }
  52. } catch (Exception e) {
  53. e.printStackTrace();
  54. throw new SecurityException();
  55. }
  56. }
  57. /*
  58. *
  59. * */
  60. mFd = open(device.getAbsolutePath(), baudrate);
  61. //device.getAbsolutePath()这是要挂载的路径new File("/dev/ttyS2")
  62. if (mFd == null) {
  63. Log.e(TAG, "native open returns null");
  64. throw new IOException();//输入输出异常
  65. }
  66. //将文件描述符 做输入输出流的参数 传递给创建的输入输出流
  67. mFileInputStream = new FileInputStream(mFd);
  68. mFileOutputStream = new FileOutputStream(mFd);
  69. }
  70. // Getters and setters
  71. public InputStream getInputStream() {
  72. return mFileInputStream;
  73. }
  74. public OutputStream getOutputStream() {
  75. return mFileOutputStream;
  76. }
  77. // JNI
  78. private native static FileDescriptor open(String path, int baudrate);
  79. public native void close();
  80. static {
  81. System.loadLibrary("serial_port");
  82. }
  83. }

第二个是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. package android.serialport;
  17. import java.io.File;
  18. import java.io.FileReader;
  19. import java.io.IOException;
  20. import java.io.LineNumberReader;
  21. import java.util.Iterator;
  22. import java.util.Vector;
  23. import android.util.Log;
  24. public class SerialPortFinder {
  25. /*
  26. * 创建一个驱动程序类
  27. * */
  28. public class Driver {
  29. public Driver(String name, String root) {
  30. mDriverName = name;//String 类型的
  31. mDeviceRoot = root;
  32. }
  33. private String mDriverName;
  34. private String mDeviceRoot;
  35. Vector<File> mDevices = null;
  36. /*
  37. * Vector 类在 java 中可以实现自动增长的对象数组
  38. * 简单的使用方法如下:
  39. vector<int> test;//建立一个vector
  40. test.push_back(1);
  41. test.push_back(2);//把1和2压入vector这样test[0]就是1,test[1]就是2
  42. * */
  43. public Vector<File> getDevices() {
  44. if (mDevices == null) {
  45. mDevices = new Vector<File>();
  46. File dev = new File("/dev");
  47. File[] files = dev.listFiles();
  48. int i;
  49. for (i=0; i<files.length; i++) {
  50. if (files[i].getAbsolutePath().startsWith(mDeviceRoot)) {
  51. Log.d(TAG, "Found new device: " + files[i]);
  52. mDevices.add(files[i]);
  53. }
  54. }
  55. }
  56. return mDevices;
  57. }
  58. public String getName() {
  59. return mDriverName;
  60. }
  61. }
  62. /*
  63. *
  64. *
  65. * */
  66. private static final String TAG = "SerialPort";
  67. private Vector<Driver> mDrivers = null;
  68. Vector<Driver> getDrivers() throws IOException {
  69. if (mDrivers == null) {
  70. mDrivers = new Vector<Driver>();
  71. LineNumberReader r = new LineNumberReader(new FileReader("/proc/tty/drivers"));
  72. String l;
  73. while((l = r.readLine()) != null) {
  74. String[] w = l.split(" +");
  75. if ((w.length == 5) && (w[4].equals("serial"))) {
  76. Log.d(TAG, "Found new driver: " + w[1]);
  77. mDrivers.add(new Driver(w[0], w[1]));
  78. }
  79. }
  80. r.close();
  81. }
  82. return mDrivers;
  83. }
  84. public String[] getAllDevices() {
  85. Vector<String> devices = new Vector<String>();
  86. // Parse each driver
  87. Iterator<Driver> itdriv;
  88. try {
  89. itdriv = getDrivers().iterator();
  90. while(itdriv.hasNext()) {
  91. Driver driver = itdriv.next();
  92. Iterator<File> itdev = driver.getDevices().iterator();
  93. while(itdev.hasNext()) {
  94. String device = itdev.next().getName();
  95. String value = String.format("%s (%s)", device, driver.getName());
  96. devices.add(value);
  97. }
  98. }
  99. } catch (IOException e) {
  100. e.printStackTrace();
  101. }
  102. return devices.toArray(new String[devices.size()]);
  103. }
  104. public String[] getAllDevicesPath() {
  105. Vector<String> devices = new Vector<String>();
  106. // Parse each driver
  107. Iterator<Driver> itdriv;
  108. try {
  109. itdriv = getDrivers().iterator();
  110. while(itdriv.hasNext()) {
  111. Driver driver = itdriv.next();
  112. Iterator<File> itdev = driver.getDevices().iterator();
  113. while(itdev.hasNext()) {
  114. String device = itdev.next().getAbsolutePath();
  115. devices.add(device);
  116. }
  117. }
  118. } catch (IOException e) {
  119. e.printStackTrace();
  120. }
  121. return devices.toArray(new String[devices.size()]);
  122. }
  123. }

第三个是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. LOCAL_PATH := $(call my-dir)
  17. include $(CLEAR_VARS)
  18. TARGET_PLATFORM := android-3
  19. LOCAL_MODULE := serial_port
  20. LOCAL_SRC_FILES := SerialPort.c
  21. LOCAL_LDLIBS := -llog
  22. 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. #include <termios.h>
  17. #include <unistd.h>
  18. #include <sys/types.h>
  19. #include <sys/stat.h>
  20. #include <fcntl.h>
  21. #include <string.h>
  22. #include <jni.h>
  23. #include "android/log.h"
  24. static const char *TAG="serial_port";
  25. #define LOGI(fmt, args...) __android_log_print(ANDROID_LOG_INFO, TAG, fmt, ##args)
  26. #define LOGD(fmt, args...) __android_log_print(ANDROID_LOG_DEBUG, TAG, fmt, ##args)
  27. #define LOGE(fmt, args...) __android_log_print(ANDROID_LOG_ERROR, TAG, fmt, ##args)
  28. static speed_t getBaudrate(jint baudrate)
  29. {
  30. switch(baudrate) {
  31. case 0: return B0;
  32. case 50: return B50;
  33. case 75: return B75;
  34. case 110: return B110;
  35. case 134: return B134;
  36. case 150: return B150;
  37. case 200: return B200;
  38. case 300: return B300;
  39. case 600: return B600;
  40. case 1200: return B1200;
  41. case 1800: return B1800;
  42. case 2400: return B2400;
  43. case 4800: return B4800;
  44. case 9600: return B9600;
  45. case 19200: return B19200;
  46. case 38400: return B38400;
  47. case 57600: return B57600;
  48. case 115200: return B115200;
  49. case 230400: return B230400;
  50. case 460800: return B460800;
  51. case 500000: return B500000;
  52. case 576000: return B576000;
  53. case 921600: return B921600;
  54. case 1000000: return B1000000;
  55. case 1152000: return B1152000;
  56. case 1500000: return B1500000;
  57. case 2000000: return B2000000;
  58. case 2500000: return B2500000;
  59. case 3000000: return B3000000;
  60. case 3500000: return B3500000;
  61. case 4000000: return B4000000;
  62. default: return -1;
  63. }
  64. }
  65. /*
  66. * Class: cedric_serial_SerialPort
  67. * Method: open
  68. * Signature: (Ljava/lang/String;)V
  69. */
  70. JNIEXPORT jobject JNICALL Java_android_serialport_SerialPort_open
  71. (JNIEnv *env, jobject thiz, jstring path, jint baudrate)
  72. {
  73. int fd;
  74. speed_t speed;
  75. jobject mFileDescriptor;
  76. /* Check arguments */
  77. {
  78. speed = getBaudrate(baudrate);
  79. if (speed == -1) {
  80. /* TODO: throw an exception */
  81. LOGE("Invalid baudrate");
  82. return NULL;
  83. }
  84. }
  85. /* Opening device */
  86. {
  87. jboolean iscopy;
  88. const char *path_utf = (*env)->GetStringUTFChars(env, path, &iscopy);
  89. LOGD("Opening serial port %s", path_utf);
  90. fd = open(path_utf, O_RDWR | O_DIRECT | O_SYNC);
  91. LOGD("open() fd = %d", fd);
  92. (*env)->ReleaseStringUTFChars(env, path, path_utf);
  93. if (fd == -1)
  94. {
  95. /* Throw an exception */
  96. LOGE("Cannot open port");
  97. /* TODO: throw an exception */
  98. return NULL;
  99. }
  100. }
  101. /* Configure device */
  102. {
  103. struct termios cfg;
  104. LOGD("Configuring serial port");
  105. if (tcgetattr(fd, &cfg))
  106. {
  107. LOGE("tcgetattr() failed");
  108. close(fd);
  109. /* TODO: throw an exception */
  110. return NULL;
  111. }
  112. cfmakeraw(&cfg);
  113. cfsetispeed(&cfg, speed);
  114. cfsetospeed(&cfg, speed);
  115. if (tcsetattr(fd, TCSANOW, &cfg))
  116. {
  117. LOGE("tcsetattr() failed");
  118. close(fd);
  119. /* TODO: throw an exception */
  120. return NULL;
  121. }
  122. }
  123. /* Create a corresponding file descriptor */
  124. {
  125. jclass cFileDescriptor = (*env)->FindClass(env, "java/io/FileDescriptor");
  126. jmethodID iFileDescriptor = (*env)->GetMethodID(env, cFileDescriptor, "<init>", "()V");
  127. jfieldID descriptorID = (*env)->GetFieldID(env, cFileDescriptor, "descriptor", "I");
  128. mFileDescriptor = (*env)->NewObject(env, cFileDescriptor, iFileDescriptor);
  129. (*env)->SetIntField(env, mFileDescriptor, descriptorID, (jint)fd);
  130. }
  131. return mFileDescriptor;
  132. }
  133. /*
  134. * Class: cedric_serial_SerialPort
  135. * Method: close
  136. * Signature: ()V
  137. */
  138. JNIEXPORT void JNICALL Java_android_serialport_SerialPort_close
  139. (JNIEnv *env, jobject thiz)
  140. {
  141. jclass SerialPortClass = (*env)->GetObjectClass(env, thiz);
  142. jclass FileDescriptorClass = (*env)->FindClass(env, "java/io/FileDescriptor");
  143. jfieldID mFdID = (*env)->GetFieldID(env, SerialPortClass, "mFd", "Ljava/io/FileDescriptor;");
  144. jfieldID descriptorID = (*env)->GetFieldID(env, FileDescriptorClass, "descriptor", "I");
  145. jobject mFd = (*env)->GetObjectField(env, thiz, mFdID);
  146. jint descriptor = (*env)->GetIntField(env, mFd, descriptorID);
  147. LOGD("close(fd = %d)", descriptor);
  148. close(descriptor);
  149. }

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



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。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家小花儿/article/detail/225315
推荐阅读
相关标签
  

闽ICP备14008679号