工程代码下载地址:

//download.csdn.net/download/mm13420109325/12018905

连线如下:

参考:https://www.cnblogs.com/xqxacm/p/8966430.html

遇到的问题(上面的工程打开报错)的解决方法:

*******************************************************************

********************************************************************

(未测试)驱动的官方下载地址:http://www.wch.cn/download/CH341SER_ANDROID_ZIP.html

目录结构如下:(将 CH34xUARTDriver.jar 文件放在目录 : app --> libs 文件下,右击它,选择Add Ad Library

核心源码如下:

MainActivity.java文件

package com.example.usb_to_ttl;import androidx.appcompat.app.AppCompatActivity;import android.content.Context;import android.widget.Toast;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.os.Handler;import android.os.Message;import android.app.AlertDialog;import android.app.Dialog;import android.content.DialogInterface;import android.hardware.usb.UsbManager;import android.view.WindowManager;import cn.wch.ch34xuartdriver.CH34xUARTDriver;public class MainActivity extends AppCompatActivity implements View.OnClickListener{    private Button connect;    //number 0-9    private Button n_0;    private Button n_1;    private Button n_2;    private Button n_3;    private Button n_4;    private Button n_5;    private Button n_6;    private Button n_7;    private Button n_8;    private Button n_9;    //other symbol    private Button clear_all;    private Button equal;    boolean clean;    private EditText editText_table;    private EditText editText_ele;    private Context context;    private String usbNumber;    private static final String ACTION_USB_PERMISSION = "cn.wch.wchusbdriver.USB_PERMISSION";    private boolean isOpen = false;    private Handler handler;    private int retval;    private MainActivity activity;    public byte[] writeBuffer;    public byte[] readBuffer;    public int baudRate;    public byte stopBit;    public byte dataBit;    public byte parity;    public byte flowControl;    public int totalrecv;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        //usb-ttl        MyApp.driver = new CH34xUARTDriver(                (UsbManager) getSystemService(Context.USB_SERVICE), this,                ACTION_USB_PERMISSION);        baudRate = 9600;        stopBit = 1;        dataBit = 8;        parity = 0;        flowControl = 0;        if (!MyApp.driver.UsbFeatureSupported())// 判断系统是否支持USB HOST        {            Dialog dialog = new AlertDialog.Builder(MainActivity.this)                    .setTitle("提示")                    .setMessage("您的手机不支持USB HOST,请更换其他手机再试!")                    .setPositiveButton("确认",                            new DialogInterface.OnClickListener() {                                @Override                                public void onClick(DialogInterface arg0,                                                    int arg1) {                                    System.exit(0);                                }                            }).create();            dialog.setCanceledOnTouchOutside(false);            dialog.show();        }        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);//keep screen always on        writeBuffer = new byte[512];        readBuffer = new byte[512];        isOpen = false;        activity = this;        connect = findViewById(R.id.button10);        //the instantiation of number 0-9        n_0 = findViewById(R.id.button0);        n_1 = findViewById(R.id.button1);        n_2 = findViewById(R.id.button2);        n_3 = findViewById(R.id.button3);        n_4 = findViewById(R.id.button4);        n_5 = findViewById(R.id.button5);        n_6 = findViewById(R.id.button6);        n_7 = findViewById(R.id.button7);        n_8 = findViewById(R.id.button8);        n_9 = findViewById(R.id.button9);        //the instantiation of others        clear_all = findViewById(R.id.button11);        equal = findViewById(R.id.button12);        editText_table = findViewById(R.id.editText);        editText_ele = findViewById(R.id.editText2);        //unable to edit        editText_ele.setFocusable(false);        editText_ele.setFocusableInTouchMode(false);        editText_table.setFocusable(false);        editText_table.setFocusableInTouchMode(false);        //click        n_0.setOnClickListener(this);        n_1.setOnClickListener(this);        n_2.setOnClickListener(this);        n_3.setOnClickListener(this);        n_4.setOnClickListener(this);        n_5.setOnClickListener(this);        n_6.setOnClickListener(this);        n_7.setOnClickListener(this);        n_8.setOnClickListener(this);        n_9.setOnClickListener(this);        connect.setOnClickListener(this);       // sb = new StringBuilder();//usb        clear_all.setOnClickListener(this);        equal.setOnClickListener(this);        context = this;        handler = new Handler() {            public void handleMessage(Message msg) {                editText_ele.setText((String) msg.obj);            }        };    }    public void onClick(View view){        //get the input        String input = editText_table.getText().toString();        //Determine which key is being pressed        switch (view.getId()){            case R.id.button0:            case R.id.button1:            case R.id.button2:            case R.id.button3:            case R.id.button4:            case R.id.button5:            case R.id.button6:            case R.id.button7:            case R.id.button8:            case R.id.button9:                if(clean){                    clean = false;                    editText_table.setText("");                }                editText_table.setText(input+((Button)view).getText()+"");                break;            //clean            case R.id.button11:                if(clean){                    clean = false;                    input = "";                    editText_table.setText("");                }                if(!input.equals("")){                    editText_table.setText(input.substring(0,input.length() - 1));                    break;                }                break;            case R.id.button12:                sendToUSB();                break;            case R.id.button10:                openUSB();                configUSB();                break;        }    }    private class readThread extends Thread {        public void run() {            byte[] buffer = new byte[4096];            while (true) {                Message msg = Message.obtain();                if (!isOpen) {                    break;                }                int length = MyApp.driver.ReadData(buffer, buffer.length);                if (length > 0) {//String recv = toHexString(buffer, length);//String recv = new String(buffer, 0, length);                    totalrecv += length;//                    String content = String.valueOf(totalrecv);                    String content = new String(buffer);                    //String content = hexStringToString(toHexString(buffer,length));                    //String content = toHexString(buffer,length*2);                    msg.obj = content+"";                    handler.sendMessage(msg);                }            }        }    }    private String toHexString(byte[] arg, int length) {        String result = new String();        if (arg != null) {            for (int i = 0; i < length; i++) {                result = result                        + (Integer.toHexString(                        arg[i] < 0 ? arg[i] + 256 : arg[i]).length() == 1 ? "0"                        + Integer.toHexString(arg[i] < 0 ? arg[i] + 256                        : arg[i])                        : Integer.toHexString(arg[i] < 0 ? arg[i] + 256                        : arg[i])) + " ";            }            return result;        }        return "";    }    /*    private byte[] toByteArray(String arg) {        if (arg != null) {            // 1.先去除String中的' ',然后将String转换为char数组            char[] NewArray = new char[1000];            char[] array = arg.toCharArray();            int length = 0;            for (int i = 0; i < array.length; i++) {                if (array[i] != ' ') {                    NewArray[length] = array[i];                    length++;                }            }            // 将char数组中的值转成一个实际的十进制数组            int EvenLength = (length % 2 == 0) ? length : length + 1;            if (EvenLength != 0) {                int[] data = new int[EvenLength];                data[EvenLength - 1] = 0;                for (int i = 0; i < length; i++) {                    if (NewArray[i] >= '0' && NewArray[i] <= '9') {                        data[i] = NewArray[i] - '0';                    } else if (NewArray[i] >= 'a' && NewArray[i] <= 'f') {                        data[i] = NewArray[i] - 'a' + 10;                    } else if (NewArray[i] >= 'A' && NewArray[i] <= 'F') {                        data[i] = NewArray[i] - 'A' + 10;                    }                }                //将 每个char的值每两个组成一个16进制数据                byte[] byteArray = new byte[EvenLength / 2];                for (int i = 0; i < EvenLength / 2; i++) {                    byteArray[i] = (byte) (data[i * 2] * 16 + data[i * 2 + 1]);                }                return byteArray;            }        }        return new byte[] {};    }    */    private byte[] toByteArray2(String arg) {        if (arg != null) {            /* 1.先去除String中的' ',然后将String转换为char数组 */            char[] NewArray = new char[1000];            char[] array = arg.toCharArray();            int length = 0;            for (int i = 0; i < array.length; i++) {                if (array[i] != ' ') {                    NewArray[length] = array[i];                    length++;                }            }            NewArray[length] = 0x0D;            NewArray[length + 1] = 0x0A;            length += 2;            byte[] byteArray = new byte[length];            for (int i = 0; i < length; i++) {                byteArray[i] = (byte)NewArray[i];            }            return byteArray;        }        return new byte[] {};    }    private void openUSB(){        if (!isOpen) {            retval = MyApp.driver.ResumeUsbList();            if (retval == -1)// ResumeUsbList方法用于枚举CH34X设备以及打开相关设备            {                Toast.makeText(MainActivity.this, "打开设备失败!",                        Toast.LENGTH_SHORT).show();                MyApp.driver.CloseDevice();            } else if (retval == 0){                if (!MyApp.driver.UartInit()) {//对串口设备进行初始化操作                    Toast.makeText(MainActivity.this, "设备初始化失败!",                            Toast.LENGTH_SHORT).show();                    Toast.makeText(MainActivity.this, "打开" +                                    "设备失败!",                            Toast.LENGTH_SHORT).show();                    return;                }                Toast.makeText(MainActivity.this, "打开设备成功!",                        Toast.LENGTH_SHORT).show();                isOpen = true;                connect.setText("Close");                new readThread().start();//开启读线程读取串口接收的数据            } else {                AlertDialog.Builder builder = new AlertDialog.Builder(activity);                builder.setIcon(R.mipmap.ic_launcher);                builder.setTitle("未授权限");                builder.setMessage("确认退出吗?");                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {                    @Override                    public void onClick(DialogInterface dialog, int which) {                        // TODO Auto-generated method stub//MainFragmentActivity.this.finish();                        System.exit(0);                    }                });                builder.setNegativeButton("返回", new DialogInterface.OnClickListener() {                    @Override                    public void onClick(DialogInterface dialog, int which) {                        // TODO Auto-generated method stub                    }                });                builder.show();            }        } else {            connect.setText("Open");            isOpen = false;            try {                Thread.sleep(200);            } catch (InterruptedException e) {                // TODO Auto-generated catch block                e.printStackTrace();            }            MyApp.driver.CloseDevice();            totalrecv = 0;        }    }    private  void configUSB(){        if(isOpen) {            if (MyApp.driver.SetConfig(baudRate, dataBit, stopBit, parity,//配置串口波特率,函数说明可参照编程手册                    flowControl)) {                Toast.makeText(MainActivity.this, "串口设置成功!",                        Toast.LENGTH_SHORT).show();            } else {                Toast.makeText(MainActivity.this, "串口设置失败!",                        Toast.LENGTH_SHORT).show();            }        }    }    private void sendToUSB() {        usbNumber = editText_table.getText().toString();        //byte[] to_send = toByteArray(usbNumber);        byte[] to_send2 = toByteArray2(usbNumber);        //txtContent.setText(new String(to_send)+"---"+new String(to_send2));        int retval = MyApp.driver.WriteData(to_send2, to_send2.length);//写数据,第一个参数为需要发送的字节数组,第二个参数为需要发送的字节长度,返回实际发送的字节长度        if (retval < 0)            Toast.makeText(MainActivity.this, "写失败!", Toast.LENGTH_SHORT).show();        Toast t = Toast.makeText(context, "Succeed to send " + usbNumber, Toast.LENGTH_LONG);        t.show();    }}

activity_main.xml文件

<?xml version="1.0" encoding="utf-8"?>                                                                                

AndroidManifest.xml文件

<?xml version="1.0" encoding="utf-8"?>                                                                                                                                                                                                                                                

MyApp.java文件

package com.example.usb_to_ttl;import android.app.Application;import cn.wch.ch34xuartdriver.CH34xUARTDriver;public class MyApp extends Application {public static CH34xUARTDriver driver;         //需要将CH34x的驱动类写在APP类下面,使得帮助类的生命周期与整个应用程序的生命周期是相同的}

 

更多相关文章

  1. android studio基础教程:3.美化按钮
  2. Android(安卓)-BLE蓝牙小DEMO
  3. 译:Android(安卓)N不再支持通过Intent传递“file://”scheme
  4. Android:在Eclipse下开发android应用产生的问题及解决方法
  5. uiautomatorviewer.bat的使用
  6. android获取应用基本信息
  7. Android下获取设备唯一标识(UDID, DeviceID...)
  8. android 发布时去除Log
  9. Android(安卓)DEX安全攻防战

随机推荐

  1. Android Q AppCompactor and LowMemDetec
  2. Failed to fectch URl https://dl-ssl.go
  3. android 获取root修改系统时间
  4. Android(安卓)Unparsed aapt error(s)! C
  5. android开发常用问题总结
  6. Android常用URI收藏
  7. android唤醒屏幕/保持屏幕唤醒
  8. RN 打包流程
  9. android activity 设置为单点触摸
  10. android 使图片显示 圆角