无网不进  
软硬件开发

实验目的:

STM32通过USB转串口向Android Device持续发送数据,并让其显示在Android DeviceEditview界面上

 

manifest.xml

 

[html] view plain copy
 
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     package="com.example.dai.usb_test">  
  4.   
  5.     <uses-feature android:name="android.hardware.usb.host"></uses-feature>  
  6.   
  7.     <application  
  8.         android:allowBackup="true"  
  9.         android:icon="@mipmap/ic_launcher"  
  10.         android:label="@string/app_name"  
  11.         android:supportsRtl="true"  
  12.         android:theme="@style/AppTheme">  
  13.         <activity  
  14.             android:name=".UsbTestActivity"  
  15.             android:label="@string/app_name"  
  16.             android:theme="@style/AppTheme.NoActionBar">  
  17.             <intent-filter>  
  18.                 <action android:name="android.intent.action.MAIN" />  
  19.                 <category android:name="android.intent.category.LAUNCHER" />  
  20.             </intent-filter>  
  21.             <intent-filter>  
  22.                 <action android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED" />  
  23.             </intent-filter>  
  24.             <meta-data android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED"  
  25.                 android:resource="@xml/usb_device_filter" />  
  26.         </activity>  
  27.     </application>  
  28.   
  29. </manifest><strong>  
  30. </strong>  



 

xml/usb_device_filter.xml:

 

[html] view plain copy
 
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <resources>  
  3.     <usb-device  vendor-id="6790" product-id="29987"  />  
  4. </resources>  


注:vendor-id和product-id都为十进制数值;

 

 

 

USB_Admin:

 

[java] view plain copy
 
  1. package com.example.dai.usb_test;  
  2.   
  3. import android.content.BroadcastReceiver;  
  4. import android.content.Context;  
  5. import android.content.Intent;  
  6. import android.hardware.usb.UsbDevice;  
  7. import android.hardware.usb.UsbDeviceConnection;  
  8. import android.hardware.usb.UsbEndpoint;  
  9. import android.hardware.usb.UsbInterface;  
  10. import android.hardware.usb.UsbManager;  
  11. import android.util.Log;  
  12. import android.widget.Toast;  
  13.   
  14. /** 
  15.  * Created by DAI on 2016/1/23. 
  16.  * Author:Will Smith 
  17.  * Email:15997135562@163.com 
  18.  * 
  19.  * Tip: 
  20.  *before developing USB on Android,you should configure manifests 
  21.  * accoriding to Android Developer 
  22.  */  
  23. public class USB_Admin {  
  24.   
  25.     private UsbManager usbManager;  
  26.     private UsbDevice usbDevice;  
  27.     private UsbInterface usbInterface;  
  28.     private UsbEndpoint usbEndpointIn;  
  29.     private UsbEndpoint usbEndpointOut;  
  30.     private UsbDeviceConnection usbDeviceConnection;  
  31.   
  32.     private static int TIMEOUT = 5000;  
  33.   
  34.     /*自己编写的USB管理类的构造函数*/  
  35.     public USB_Admin(Context context){  
  36.   
  37.         usbManager = (UsbManager) context.getSystemService(Context.USB_SERVICE);  
  38.         Log.v("USBManager:","" + usbManager);  
  39.     }  
  40.   
  41.     /*****************************USB相关的操作**********************************/  
  42.   
  43.     /*获得USB的usbManager*/  
  44.     public UsbManager get_UsbManager(){  
  45.   
  46.         return usbManager;  
  47.     }  
  48.   
  49.   
  50.     /*获得USB设备*/  
  51.   
  52.     public UsbDevice get_UsbDevice(Intent intent){   //这个USBDevice还有问题,暂时还得不到;  
  53.   
  54.         /*使用意图过滤器的方法*/  
  55.         if (intent != null) {  
  56.             Log.d("intent: ", "" + intent.toString());  
  57.             if (intent.getAction().equals(UsbManager.ACTION_USB_DEVICE_ATTACHED)) {    //说明没有进入到这个if语句中  
  58.                 usbDevice = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);        //待查找;  
  59.                 Log.v("USBDevice ","" + usbDevice);  
  60.                 if (usbDevice != null) {  
  61.                     Log.d("USB device attached: ", "" + usbDevice.getDeviceName());  
  62.                 }  
  63.             }  
  64.         }  
  65.   
  66.         /*使用枚举的方法做一下*/  
  67.   
  68.         return usbDevice;  
  69.     }  
  70.   
  71.   
  72.     /*获得访问USB设备的权限*/  
  73.     /*若没有在清单文件中配置USB的意图过滤器,那么就需要手动通过这一步去获取权限*/  
  74.     /* 
  75.     public void getPermission(){ 
  76.  
  77.  
  78.  
  79.     } 
  80.     */  
  81.   
  82.     /*获取USB设备的UsbInterface*/  
  83.     /*和系统提供的函数名有冲突*/  
  84.     public UsbInterface get_Interface(Context context){  
  85.   
  86.         usbInterface = usbDevice.getInterface(0);  
  87.         Log.v("USBInterface:", "" + usbInterface);  
  88.         if(usbInterface == null){  
  89.             Toast.makeText(context,"can't get usbInterface",Toast.LENGTH_SHORT);  
  90.             return null;  
  91.         }  
  92.   
  93.         return usbInterface;  
  94.     }  
  95.   
  96.     /* 
  97.     作用:获取USB设备UsbEndpoint 
  98.     参数: 
  99.     0:表示获取输入端点 
  100.     1:表示获取输出端点 
  101.  
  102.     */  
  103.   
  104.     /*和系统提供的函数名有冲突*/  
  105.     public UsbEndpoint get_Endpoint(int i,Context context){  
  106.   
  107.   
  108.         //获取输入端点  
  109.         if(i == 0){  
  110.   
  111.             if((usbEndpointIn = usbInterface.getEndpoint(0)) != null){  
  112.   
  113.                 Log.v("USBEndpointIn:","" + usbEndpointIn);  
  114.                 return usbEndpointIn;  
  115.   
  116.             }  
  117.             Toast.makeText(context,"can't get usbEndpointIn",Toast.LENGTH_SHORT);  
  118.   
  119.   
  120.         }else if(i == 1){     //获取输出端点  
  121.   
  122.             if((usbEndpointOut = usbInterface.getEndpoint(1)) != null){  
  123.   
  124.                 Log.v("USBEndpointOut:","" + usbEndpointOut);  
  125.                 return usbEndpointOut;  
  126.   
  127.             }  
  128.             Toast.makeText(context,"can't get usbEndpointOut",Toast.LENGTH_SHORT);  
  129.   
  130.         }  
  131.         Toast.makeText(context,"can't get any usbEndpoint",Toast.LENGTH_SHORT);  
  132.         return null;  
  133.   
  134.     }  
  135.   
  136.     /*获得USB设备的UsbDeviceConnection*/  
  137.     public UsbDeviceConnection get_usbDeviceConnection(Context context){  
  138.   
  139.         if(usbManager.hasPermission(usbDevice)){  
  140.   
  141.             usbDeviceConnection = usbManager.openDevice(usbDevice);  
  142.             Log.v("USBDeviceConnection:","" + usbDeviceConnection);  
  143.   
  144.   
  145.             return usbDeviceConnection;  
  146.   
  147.         }  
  148.         Toast.makeText(context,"can't get usbDeviceConnection",Toast.LENGTH_SHORT);  
  149.         return null;  
  150.   
  151.     }  
  152.   
  153.   
  154.     /*接收数据*/  
  155.     public  int receive_Message(byte[] receiveBytes){  
  156.   
  157.         int ret = -1;  
  158.         if(usbEndpointIn != null){  
  159.             ret = usbDeviceConnection.bulkTransfer(usbEndpointIn, receiveBytes, receiveBytes.length, TIMEOUT);  
  160.   
  161.         }else {  
  162.   
  163.             Log.v("receiveBytes: ", "failed");  
  164.   
  165.         }  
  166.   
  167.         return ret;  
  168.     }  
  169.   
  170.   
  171.     /*发送数据*/  
  172.     public int send_Message(byte[] sendBytes){  
  173.         int ret = -1;  
  174.         if(usbEndpointOut != null){  
  175.   
  176.             ret = usbDeviceConnection.bulkTransfer(usbEndpointOut, sendBytes, sendBytes.length, TIMEOUT);  
  177.   
  178.         }else {  
  179.   
  180.             Log.v("Send: ","failed");  
  181.   
  182.         }  
  183.   
  184.         return ret;  
  185.   
  186.     }  
  187.   
  188.   
  189.     /*断开已连接的USB设备*/  
  190.     public void disconnect_USB(Context context){  
  191.   
  192.         BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {  
  193.             public void onReceive(Context context, Intent intent) {  
  194.                 String action = intent.getAction();  
  195.   
  196.                 if (UsbManager.ACTION_USB_DEVICE_DETACHED.equals(action)) {  
  197.                     UsbDevice device = (UsbDevice)intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);  
  198.                     if (device != null) {  
  199.                         usbDeviceConnection.releaseInterface(get_Interface(context));  
  200.                         usbDeviceConnection.close();  
  201.                     }  
  202.                 }  
  203.             }  
  204.         };  
  205.   
  206.   
  207.     }  
  208.   
  209.     /*获得设备的product-id和vendor-id*/  
  210.     public int get_ProductId(){  
  211.   
  212.         return usbDevice.getProductId();  
  213.   
  214.     }  
  215.   
  216.     /*获得设备的vendor-id*/  
  217.     public int get_VendorId(){  
  218.   
  219.         return usbDevice.getVendorId();  
  220.   
  221.     }  
  222.   
  223.     /*获得设备的getSerialNumber*/  
  224.     /* 
  225.     public String get_SerialNumber(){ 
  226.  
  227.  
  228.         return null; 
  229.     } 
  230.     */  
  231.   
  232.   
  233.   
  234. }  



 

 

UsbTestActivity:

 

[java] view plain copy
 
  1. package com.example.dai.usb_test;  
  2.   
  3. import android.content.Intent;  
  4. import android.hardware.usb.UsbDevice;  
  5. import android.hardware.usb.UsbDeviceConnection;  
  6. import android.hardware.usb.UsbEndpoint;  
  7. import android.hardware.usb.UsbInterface;  
  8. import android.hardware.usb.UsbManager;  
  9. import android.os.Bundle;  
  10. import android.os.Message;  
  11. import android.support.design.widget.FloatingActionButton;  
  12. import android.support.design.widget.Snackbar;  
  13. import android.support.v7.app.AppCompatActivity;  
  14. import android.support.v7.widget.Toolbar;  
  15. import android.util.Log;  
  16. import android.view.Menu;  
  17. import android.view.MenuItem;  
  18. import android.view.View;  
  19. import android.widget.EditText;  
  20.   
  21. import java.io.UnsupportedEncodingException;  
  22.   
  23. /*Purpose: 
  24. * test USB on Android by receiving data from stm32 board, 
  25. * then display on X4418 board 
  26. * */  
  27.   
  28. public class UsbTestActivity extends AppCompatActivity {  
  29.   
  30.     private USB_Admin usb_admin;  
  31.     private UsbManager usbManager;  
  32.     private UsbDevice usbDevice;  
  33.     private UsbInterface usbInterface;  
  34.     private UsbDeviceConnection usbDeviceConnection;  
  35.     private UsbEndpoint usbEndpointIn;  
  36.     private UsbEndpoint usbEndpointOut;  
  37.   
  38.     protected final Object mReadBufferLock = new Object();  
  39.     protected final Object mWriteBufferLock = new Object();  
  40.   
  41.   
  42.     byte[] receiveBytes = new  byte[32];  
  43.     byte[] sendBytes = new  byte[32];  
  44.   
  45.     private StringBuffer stringBuffer = new StringBuffer();  
  46.   
  47.     EditText editText;  
  48.   
  49.   
  50.     @Override  
  51.     protected void onCreate(Bundle savedInstanceState) {  
  52.         super.onCreate(savedInstanceState);  
  53.         setContentView(R.layout.activity_usb_test);  
  54.         Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);  
  55.         setSupportActionBar(toolbar);  
  56.   
  57.         FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);  
  58.         fab.setOnClickListener(new View.OnClickListener() {  
  59.             @Override  
  60.             public void onClick(View view) {  
  61.                 Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)  
  62.                         .setAction("Action", null).show();  
  63.             }  
  64.         });  
  65.   
  66.   
  67.         editText = (EditText)findViewById(R.id.editText);  
  68.   
  69.         usb_Init();  
  70.   
  71.         usb_receiveData();  
  72.   
  73.         usb_sendData();  
  74.   
  75.     }  
  76.   
  77.     public void usb_Init(){  
  78.   
  79.         Intent intent = getIntent();  
  80.         usb_admin = new USB_Admin(this);  
  81.         Log.v("usb_admin: ", "" + usb_admin);  
  82.         usbManager = usb_admin.get_UsbManager();  
  83.         Log.v("usbManager: ","" + usbManager);  
  84.         usbDevice = usb_admin.get_UsbDevice(intent);  
  85.         Log.v("usbDevice: ", "" + usbDevice);  
  86.         Log.v("interfaceCount: ",""+usbDevice.getInterfaceCount());  
  87.         usbInterface = usb_admin.get_Interface(this);  
  88.         Log.v("usbInterface: ", "" + usbInterface);    //1个;  
  89.         Log.v("usbEndpointCount: ", "" + usbInterface.getEndpointCount());  
  90.   
  91.         usbEndpointIn = usb_admin.get_Endpoint(0, this);  
  92.         Log.v("usbEndpointIn: ", "" + usbEndpointIn);  
  93.         Log.v("usbEndpointDirection: ", "" + usbEndpointIn.getDirection());  
  94.   
  95.         usbEndpointOut = usb_admin.get_Endpoint(1, this);  
  96.         Log.v("usbEndpointOut: ", "" + usbEndpointOut);  
  97.         Log.v("usbEndpointDirection: ", "" + usbEndpointOut.getDirection());  
  98.   
  99.         usbDeviceConnection = usb_admin.get_usbDeviceConnection(this);  
  100.         Log.v("usbDeviceConnection: ", "" + usbDeviceConnection);  
  101.         configUsb340(115200);  
  102.   
  103.     }  
  104.   
  105.     public void usb_receiveData(){  
  106.   
  107.   
  108.         ReceiveThread receiveThread = new ReceiveThread();  
  109.         Thread thread = new Thread(receiveThread);  
  110.         thread.start();  
  111.   
  112.     }  
  113.   
  114.   
  115.   
  116.     public void usb_sendData(){  
  117.   
  118.         SendThread sendThread = new SendThread();  
  119.         Thread send = new Thread(sendThread);  
  120.         send.start();  
  121.   
  122.     }  
  123.   
  124.     class ReceiveThread implements Runnable{  
  125.   
  126.         @Override  
  127.         public void run() {  
  128.             synchronized(mReadBufferLock){  
  129.                 while (!Thread.currentThread().isInterrupted()){  
  130.                     if(usbDeviceConnection.claimInterface(usbInterface, true)){  
  131.   
  132.                         if((usb_admin.receive_Message(receiveBytes)) >= 0){  
  133.   
  134.                         /* 
  135.                         for(int i=0;i<receiveBytes.length;i++){ 
  136.  
  137.                             Log.v("Data: ",""+receiveBytes[i]);   //为什么这里得到的数据大部分都为0呢? 
  138.  
  139.                         } 
  140.                         */  
  141.                             Log.v("length: ",""+usb_admin.receive_Message(receiveBytes));  
  142.                             String string = null;  
  143.                             Log.v("receiveBytes: ","" + receiveBytes.toString());  
  144.                             Log.v("receiveBytes: ","is OK ");  
  145.                             try {  
  146.                                 string = new String(receiveBytes,"UTF-8");  
  147.                                 stringBuffer.append(string);  
  148.                                 Log.v("3D DATA", string);  
  149.                             } catch (UnsupportedEncodingException e) {  
  150.                                 e.printStackTrace();  
  151.                             }  
  152.                             Message message = handler.obtainMessage();  
  153.                             message.obj = stringBuffer;  
  154.                             message.what = 1;  
  155.                             handler.sendMessage(message);  
  156.   
  157.                         }else {  
  158.   
  159.                             Log.v("Receive Data: ","failed");  
  160.   
  161.                         }  
  162.   
  163.                     }else {  
  164.   
  165.                         Log.v("claimInterface: ","failed");  
  166.                     }  
  167.   
  168.                     try {  
  169.                         Thread.sleep(3000);  
  170.                     } catch (InterruptedException e) {  
  171.                         e.printStackTrace();  
  172.                     }  
  173.   
  174.                 }  
  175.             }  
  176.   
  177.   
  178.         }  
  179.     }  
  180.   
  181.     class SendThread implements Runnable{  
  182.   
  183.         @Override  
  184.         public void run() {  
  185.   
  186.             synchronized(mWriteBufferLock){  
  187.   
  188.                 while (!Thread.currentThread().isInterrupted()){  
  189.   
  190.                     if(usbDeviceConnection.claimInterface(usbInterface, true)){  
  191.   
  192.                         String string = " Android USB Test ";  
  193.                         sendBytes = string.getBytes();  
  194.                         if((usb_admin.send_Message(sendBytes)) >= 0){  
  195.   
  196.                             Log.v("sendBytes: ","is OK ");  
  197.   
  198.                         }else {  
  199.   
  200.                             Log.v("Send Data: ","failed");  
  201.   
  202.                         }  
  203.   
  204.                     }else {  
  205.   
  206.                         Log.v("claimInterface: ","failed");  
  207.                     }  
  208.   
  209.                     try {  
  210.                         Thread.sleep(3000);  
  211.                     } catch (InterruptedException e) {  
  212.                         e.printStackTrace();  
  213.                     }  
  214.   
  215.                 }  
  216.   
  217.             }  
  218.   
  219.   
  220.         }  
  221.     }  
  222.   
  223.   
  224.     private android.os.Handler handler = new android.os.Handler(){  
  225.   
  226.         @Override  
  227.         public void handleMessage(Message msg) {  
  228.             super.handleMessage(msg);  
  229.             switch (msg.what){  
  230.   
  231.                 case 1:  
  232.                     editText.setText((StringBuffer)msg.obj);  
  233.                     break;  
  234.   
  235.                 default:  
  236.                     break;  
  237.   
  238.             }  
  239.   
  240.   
  241.         }  
  242.     };  
  243.   
  244.     @Override  
  245.     public boolean onCreateOptionsMenu(Menu menu) {  
  246.         // Inflate the menu; this adds items to the action bar if it is present.  
  247.         getMenuInflater().inflate(R.menu.menu_usb_test, menu);  
  248.         return true;  
  249.     }  
  250.   
  251.     @Override  
  252.     public boolean onOptionsItemSelected(MenuItem item) {  
  253.         // Handle action bar item clicks here. The action bar will  
  254.         // automatically handle clicks on the Home/Up button, so long  
  255.         // as you specify a parent activity in AndroidManifest.xml.  
  256.         int id = item.getItemId();  
  257.   
  258.         //noinspection SimplifiableIfStatement  
  259.         if (id == R.id.action_settings) {  
  260.             return true;  
  261.         }  
  262.   
  263.         return super.onOptionsItemSelected(item);  
  264.     }  
  265.   
  266.   
  267.     private boolean configUsb340(int paramInt)  
  268.     {  
  269.         byte[] arrayOfByte = new byte[8];  
  270.         usbDeviceConnection.controlTransfer(192, 95, 0, 0, arrayOfByte, 8, 1000);  
  271.         usbDeviceConnection.controlTransfer(64, 161, 0, 0, null, 0, 1000);  
  272.         long l1 = 1532620800 / paramInt;  
  273.         for (int i = 3; ; i--)  
  274.         {  
  275.             if ((l1 <= 65520L) || (i <= 0))  
  276.             {  
  277.                 long l2 = 65536L - l1;  
  278.                 int j = (short)(int)(0xFF00 & l2 | i);  
  279.                 int k = (short)(int)(0xFF & l2);  
  280.                 usbDeviceConnection.controlTransfer(64, 154, 4882, j, null, 0, 1000);  
  281.                 usbDeviceConnection.controlTransfer(64, 154, 3884, k, null, 0, 1000);  
  282.                 usbDeviceConnection.controlTransfer(192, 149, 9496, 0, arrayOfByte, 8, 1000);  
  283.                 usbDeviceConnection.controlTransfer(64, 154, 1304, 80, null, 0, 1000);  
  284.                 usbDeviceConnection.controlTransfer(64, 161, 20511, 55562, null, 0, 1000);  
  285.                 usbDeviceConnection.controlTransfer(64, 154, 4882, j, null, 0, 1000);  
  286.                 usbDeviceConnection.controlTransfer(64, 154, 3884, k, null, 0, 1000);  
  287.                 usbDeviceConnection.controlTransfer(64, 164, 0, 0, null, 0, 1000);  
  288.                 return true;  
  289.             }  
  290.             l1 >>= 3;  
  291.         }  
  292.     }  
  293.   
  294.   
  295.   
  296.   
  297. }  

 

 

 

从STM32发送数据那段的程序如下:

 

[cpp] view plain copy
 
  1. #include "sys.h"  
  2. #include "delay.h"  
  3. #include "uart.h"  
  4. #include "led.h"  
  5.   
  6.   
  7. int main(void){  
  8.       
  9.     int i = 0;  
  10.     char res[10] = {'0','1','2','3','4','5','6','7','8','9'};   //ASCII:49-57  
  11.       
  12.     Stm32_Clock_Init(336,8,2,7);//ʨ׃ʱד,168Mhz    
  13.     delay_init(168);          
  14.     USART_Init();  
  15.       
  16.       
  17.     while(1){  
  18.           
  19.         for(i=0;i<10;i++){  
  20.               
  21.             USART1->DR = res[i];  
  22.             while(((USART1->SR)&(0x80)) != 0x80);   
  23.           
  24.         }  
  25.         delay_ms(3000);  
  26.   
  27.     }  
  28.       
  29. }  



 

 

效果图如下:

 

 

 

注:针对不同的USB转串口芯片,USB部分的配置代码不一样;本程序只针对CH340芯片可用;

具体的USB转串口程序可参考Github上的开源项目https://github.com/ksksue/PhysicaloidLibrary 

或者 https://github.com/mik3y/usb-serial-for-android 

posted on 2018-01-10 18:06  无网不进  阅读(986)  评论(0编辑  收藏  举报