如何从串口接收android中的数据

时间:2015-05-22 11:29:21

标签: android embedded serial-communication

我正在创建一个用于串行通信的Android应用程序。在这里,我使用FTDI电缆进行Android设备和PC之间的串行通信。要在我的电脑中显示数据,我正在使用超级终端。我使用FTDI在android和我的电脑之间创建了一个成功的连接,我用Android设备成功地将数据发送到我的电脑,波特率为19200.但是在这里我想要接收数据是通过pc发送到Android使用串行电缆双向通信。任何人告诉我如何做到这一点。我做了一些代码,但它不会工作,请帮助我...

这是我的USB驱动程序

package com.example.democomm;

import java.util.HashMap;
import java.util.Iterator;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.usb.UsbConstants;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbDeviceConnection;
import android.hardware.usb.UsbEndpoint;
import android.hardware.usb.UsbInterface;
import android.hardware.usb.UsbManager;
import android.util.Log;
public class UsbDriver
{

    private final Context mApplicationContext;
    private final UsbManager mUsbManager;
    @SuppressWarnings("unused")
    private final UsbConnectionHandler mConnectionHandler;
    private final int VID;
    private final int PID;
    protected static final String ACTION_USB_PERMISSION = "ch.serverbox.android.USB";
    public static int Device_Exception;
    public static UsbDevice Device_Details;
    public static UsbEndpoint Data_In_End_Point = null;
    public static UsbEndpoint Data_Out_End_Point = null;
    public static UsbDeviceConnection USB_Device_Connection;

    public UsbDriver(Activity parentActivity,UsbConnectionHandler connectionHandler, int vid, int pid) 
    {
        mApplicationContext = parentActivity.getApplicationContext();
        mConnectionHandler = connectionHandler;
        mUsbManager = (UsbManager) mApplicationContext.getSystemService(Context.USB_SERVICE);
        VID = 6790;
        PID = 29987;
        Device_Exception = 0;
    //  init();
        Check_Devices();
    }

    private void Check_Devices() 
    {
        @SuppressWarnings("unused")
        int j=0;
        HashMap<String, UsbDevice> devlist = mUsbManager.getDeviceList();
        Iterator<UsbDevice> deviter = devlist.values().iterator();
        Device_Details = null;
        if (devlist.size() != 0) 
        {

            while (deviter.hasNext()) 
            {
                Device_Details = deviter.next();

                if (Device_Details.getVendorId() == VID && Device_Details.getProductId() == PID)
                {
                    if (!mUsbManager.hasPermission(Device_Details))
                    {
                        onPermissionDenied(Device_Details);
                    }
                    else 
                    {
                        UsbDeviceConnection conn = mUsbManager.openDevice(Device_Details);
                        if (!conn.claimInterface(Device_Details.getInterface(0), true))
                        {
                            return;
                        }

                        conn.controlTransfer(0x40, 0, 0, 0, null, 0, 0);// reset
                        conn.controlTransfer(0x40, 0, 1, 0, null, 0, 0);// clear Rx
                        conn.controlTransfer(0x40, 0, 2, 0, null, 0, 0);// clear Tx
                        conn.controlTransfer(0x40, 0x03, 0x809C, 0, null, 0, 0);
                        USB_Device_Connection=conn; 
                        Data_In_End_Point = null;
                        Data_Out_End_Point = null;

                        UsbInterface usbIf = Device_Details.getInterface(0);
                        for (int i = 0; i < usbIf.getEndpointCount(); i++) 
                        {
                            if (usbIf.getEndpoint(i).getType() == UsbConstants.USB_ENDPOINT_XFER_BULK) 
                            {
                                if (usbIf.getEndpoint(i).getDirection() == UsbConstants.USB_DIR_IN)

                                    Data_In_End_Point = usbIf.getEndpoint(i);
                                else
                                    Data_Out_End_Point = usbIf.getEndpoint(i);
                            }
                        }
                        if (Data_In_End_Point == null || Data_Out_End_Point == null)

                            Device_Exception = 2;
                    }
                    break;
                }j++;
            }
            if (Device_Details == null)
            {
                Device_Exception = 3;
                return;
            }
        }
        else 
        {
            Device_Exception = 1;
            return;
        }

    }
    public void onPermissionDenied(UsbDevice d) 
    {
        UsbManager usbman = (UsbManager) mApplicationContext.getSystemService(Context.USB_SERVICE);

        PendingIntent pi = PendingIntent.getBroadcast(mApplicationContext, 0, new Intent(ACTION_USB_PERMISSION), 0);

        mApplicationContext.registerReceiver(mPermissionReceiver,new IntentFilter(ACTION_USB_PERMISSION));

        usbman.requestPermission(d, pi);
    }


        private class PermissionReceiver extends BroadcastReceiver 
        {
            private final IPermissionListener mPermissionListener;

            public PermissionReceiver(IPermissionListener permissionListener) 
            {
                mPermissionListener = permissionListener;
            }

        @Override
        public void onReceive(Context context, Intent intent) 
        {
            mApplicationContext.unregisterReceiver(this);

            if (intent.getAction().equals(ACTION_USB_PERMISSION)) 
            {
                if (!intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) 
                {
                    mPermissionListener.onPermissionDenied((UsbDevice) intent.getParcelableExtra(UsbManager.EXTRA_DEVICE));
                } 
                else 
                {
                    l("Permission granted");
                    UsbDevice dev = (UsbDevice) intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
                    if (dev != null)
                    {
                        if (dev.getVendorId() == VID && dev.getProductId() == PID) 
                        {
                            Check_Devices() ;
                        }
                    }
                    else
                    {
                        e("device not present!");
                    }
                }
            }
        }

    }

    // MAIN LOOP

    // END MAIN LOOP
    private BroadcastReceiver mPermissionReceiver = new PermissionReceiver(new IPermissionListener() 
    {
                @Override
                public void onPermissionDenied(UsbDevice d) 
                {
                    l("Permission denied on " + d.getDeviceId());
                }
            });

    private static interface IPermissionListener 
    {
        void onPermissionDenied(UsbDevice d);
    }

    public final static String TAG = "USBController";

    private void l(Object msg) 
    {
        Log.d(TAG, ">==<" + msg.toString() + " >==<");
    }

    private void e(Object msg) 
    {
        Log.e(TAG, ">==< " + msg.toString() + " >==<");
    }
}

这是我的主要活动

package com.example.democomm;

import java.nio.ByteBuffer;
import java.util.HashMap;
import android.app.ActionBar;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Typeface;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbDeviceConnection;
import android.hardware.usb.UsbEndpoint;
import android.hardware.usb.UsbInterface;
import android.hardware.usb.UsbManager;
import android.hardware.usb.UsbRequest;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity
{

    public static final int targetVendorID = 6790;      
    public static final int targetProductID = 29987;
    public  UsbManager manager;
    public  UsbDeviceConnection usbDeviceConnection;
    public  UsbInterface usbInterfaceFound = null;
    public  UsbEndpoint endpointOut = null;
    public  UsbEndpoint endpointIn = null;
    public  UsbDevice usbdevice,device_details;
    public  UsbEndpoint listusbendpoint;

    public static final String PREFS_NAME = "LoginPrefs";
    HashMap<String, UsbDevice> devicelist= null;
    int selectedendpoint; 
    static int Coil_No;
    private static final int VID = 6790;
    private static final int PID = 29987;
    private static UsbDriver Usb_Driver_class;
    ActionBar actionbar;
    UsbConnectionHandler connectionHandler;
    public static UsbDriver USB_Driver_Child;
    public static boolean Communication_Failed,Frame_Ok,Total_Frame_Decoded;
    static byte[] Communication_Byte;
    public SharedPreferences loginpreferences;
    public SharedPreferences.Editor loginpreferenceseditor;
    public boolean savelogin;
    public String Password;
    Button sample_button;
    public EditText receive_Data;
    CheckBox remember_me;
    Typeface custom_font;
    String i = "";
    Intent i2;
    CheckBox show_password;
    String ProcID;
    String User_Name_string,password_string;
    TextView title,username_txt,password_txt,company_name;
    ByteBuffer buffer;
    Button signin;
    EditText dialog_username,dialog_password,dialog_confirm;

    static byte[] sample;
    static boolean Communication_Ok;
    public static float []Wave_Form_Data=new float[1500];
    public static float []Wave_Form_Data_1=new float[1500];
    public static float Respsonse_Time,Drive_Voltage;
    static int Sequence_No,Response_Time;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        receive_Data = (EditText)findViewById(R.id.edit_receive);
        signin = (Button)findViewById(R.id.button1);
        signin.setOnClickListener(new View.OnClickListener() 
        {

            @SuppressWarnings("static-access")
            @Override
            public void onClick(View v) 
            {
                    Communication_Byte=new byte[1];


                        if(Check_Devices_Available()==true)
                        {   
                            int Packet_Size = USB_Driver_Child.Data_In_End_Point.getMaxPacketSize();
                            Toast.makeText(MainActivity.this,""+Packet_Size, Toast.LENGTH_LONG).show();
                            Receive.start();
                            Communication_Ok=false;
                            for(int i=0;(i<5 && Communication_Ok!=true);i++)    
                            Send_Communication_Check_Command();

                            if(Communication_Ok)
                                Toast.makeText(MainActivity.this, "Communication Successfully Established", 1000).show();
                            else
                                Toast.makeText(MainActivity.this, "Communication Failure", 10000).show();
                        }
                    }
                });
            }





    public boolean  Check_Devices_Available() 
    {
        Usb_Driver_class = new UsbDriver(this, connectionHandler, VID, PID);

        if(USB_Driver_Child.Device_Exception==0)
        {

            if(USB_Driver_Child.USB_Device_Connection==null || USB_Driver_Child.Data_Out_End_Point==null)
            return false;   

            Toast.makeText(MainActivity.this,"Device Found", 1000).show();  
            return true;
        }
        else if(USB_Driver_Child.Device_Exception==1)
        {
            Toast.makeText(MainActivity.this,"No Devices Attached ", Toast.LENGTH_LONG).show(); 
            return false;
        }
        else if(USB_Driver_Child.Device_Exception==2)
        {
            Toast.makeText(MainActivity.this,"Device Found,But No End Points", Toast.LENGTH_LONG).show();   
            return false;
        }
        else if(USB_Driver_Child.Device_Exception==3)
        {
            Toast.makeText(MainActivity.this,"Unable to Open Device", Toast.LENGTH_LONG).show();    
            return false;
        }
        return false;   //un known exception
    }

Thread Receive  = new Thread(new Runnable()
    {

    @SuppressWarnings("unused")
    @Override
    public void run() 
    {
        //Sequence_No=0;
        buffer = ByteBuffer.allocate(64);
        sample = new byte[64];

        UsbRequest request = new UsbRequest();
        int i,j;
        byte [] datarx=new byte[1]; 

        char q;
        while (true) 
        {
        request.initialize(USB_Driver_Child.USB_Device_Connection, USB_Driver_Child.Data_In_End_Point);
        request.queue(buffer, 64);
        if (USB_Driver_Child.USB_Device_Connection.requestWait() == request) 
        {

            //UsbDriver.USB_Device_Connection.bulkTransfer(UsbDriver.Data_In_End_Point,datarx, datarx.length, 0);   
            sample=buffer.array();
                for(i=0;i<64;i++)
                {
                    receive_Data.setText(sample.toString());
                    if(sample[i]=='&')
                        {
                            Communication_Ok=true;
                            break;
                        }
                }


        }
      }




    }
  });


private static void Send_Communication_Check_Command() 
{
    long i,j;

    Communication_Byte[0]='&';
    UsbDriver.USB_Device_Connection.bulkTransfer(UsbDriver.Data_Out_End_Point,Communication_Byte, 1, 0);
    for(i=0;(i<1000 && Communication_Ok!=true) ;i++)    
    for(j=0;(j<1000 && Communication_Ok!=true);j++);
}





 }

在线程中,我编写了用于接收无法正常工作的数据的代码

1 个答案:

答案 0 :(得分:2)

太棒了..我正在回答我自己的问题。经过大量的搜索,我找到了答案link 我曾经在编辑文本字段中显示接收数据 这是我在接收线程中所做的:

ByteBuffer buffer = ByteBuffer.allocate(1);
UsbRequest mUsbrequest = new UsbRequest();
mUsbrequest.initialize(Usb_Driver_class.USB_Device_Connection, Usb_Driver_class.Data_In_End_Point);
while(true){
    mUsbrequest.queue(buffer, 1);
    if(Usb_Driver_class.USB_Device_Connection.requestWait() == mUsbrequest){
        byte dataReceive = buffer.get(0);
        Log.d("Message", "Data to receive:"+dataReceive);
        if(dataReceive != 0x00){//if data is null
            string_to_receive += (char)dataReceive;

            runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    receive_Data.setText(string_to_receive);

                }
            });
        }
    }
}