摘要
无需root权限,Android使用串口与esp32通信控制小灯开关;开启Android摄像头预览.
平台信息
- Android Studio: Electric Eel | 2022.1.1 Patch 2
- Gradle:distributionUrl=https://services.gradle.org/distributions/gradle-7.5-bin.zip
- jvmTarget = '1.8'
- minSdk 21
- targetSdk 33
- compileSdk 33
- 开发语言:Kotlin,Java
- ndkVersion = '25.2.9519653'
Android串口及其使用方式简介
[https://gitcode.net/mirrors/mik3y/usb-serial-for-android]
[https://github.com/mik3y/usb-serial-for-android]
[https://zhuanlan.zhihu.com/p/358212044]
usb-serial-for-android
库支持的usb芯片如下:
This library supports USB to serial converter chips:
FTDI FT232R, FT232H, FT2232H, FT4232H, FT230X, FT231X, FT234XD
Prolific PL2303
Silabs CP2102 and all other CP210x
Qinheng CH340, CH341A, CH9102
and devices implementing the CDC/ACM protocol like
Arduino using ATmega32U4
Digispark using V-USB software USB
BBC micro:bit using ARM mbed DAPLink firmware
使用串口库的示例工程为[https://gitcode.net/mirrors/mik3y/usb-serial-for-android/-/tree/master/usbSerialExamples].
This is a driver library for communication with Arduinos and other USB serial hardware on
Android, using the
Android USB Host Mode (OTG)
available since Android 3.1 and working reliably since Android 4.2.
No root access, ADK, or special kernel drivers are required; all drivers are implemented in
Java. You get a raw serial port with read(), write(), and other functions for use with your own protocols.
Android摄像头使用方式
[https://developer.android.google.cn/training/camerax?hl=zh-cn]
[https://developer.android.google.cn/training/camerax/preview?hl=zh-cn]
- 使用CameraX库
CameraX 是一个 Jetpack 库,旨在帮助您更轻松地开发相机应用。如果您要开发新应用,我们建议您从 CameraX 开始。它提供了一个一致且易于使用的 API,该 API 适用于绝大多数 Android 设备,并向后兼容 Android 5.0(API 级别 21)。如果您要将应用从 Camera1 迁移到 CameraX,请参阅从 Camera1 迁移到 CameraX 的迁移指南。
在向应用添加预览时,请使用 PreviewView,这是一种可以剪裁、缩放和旋转以确保正确显示的 View。
当相机处于活动状态时,图片预览会流式传输到 PreviewView 中的 Surface。
如需使用 PreviewView 实现 CameraX 预览,请按以下步骤操作(稍后将对这些步骤进行说明):
- (可选)配置 CameraXConfig.Provider。
- 将 PreviewView 添加到布局。
- 请求 ProcessCameraProvider。
- 在创建 View 时,请检查 ProcessCameraProvider。
- 选择相机并绑定生命周期和用例。
实现
步骤
- esp32实现串口收发及命令解析
- Android实现串口收发
Android设备接入typeC-typeA集线器可以扩展出USB接口,然后接入带有CH340(USB转TTL)芯片的esp32即可实现串口通信.
Android关键代码
[https://gitcode.net/mirrors/mik3y/usb-serial-for-android]
- 在
settings.gradle
引入串口库依赖jitpack.io
dependencyResolutionManagement {
repositories {
//省略
maven { url 'https://jitpack.io' }
}
}
- 在
build.gradle(app)
引入串口库及CameraX库;
dependencies {
//省略
//串口库
implementation 'com.github.mik3y:usb-serial-for-android:3.5.1'
//CameraX库
def camerax_version = "1.1.0-beta03"
// CameraX core library
implementation "androidx.camera:camera-core:$camerax_version"
// CameraX Camera2 extensions[可选]拓展库可实现人像、HDR、夜间和美颜、滤镜但依赖于OEM
implementation "androidx.camera:camera-camera2:$camerax_version"
// CameraX Lifecycle library[可选]避免手动在生命周期释放和销毁数据
implementation "androidx.camera:camera-lifecycle:$camerax_version"
// CameraX View class[可选]最佳实践,最好用里面的PreviewView,它会自行判断用SurfaceView还是TextureView来实现
implementation 'androidx.camera:camera-view:1.1.0-beta03'
}
- MainActivity.kt
//APP包名
package com.mbeddev.androidkotlinvirtualjoystick
//蓝牙:Rxble库
//串口:usb-serial-for-android库
//摄像头:CameraX库
import android.Manifest
import android.app.PendingIntent
import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothManager
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.hardware.usb.UsbDevice
import android.hardware.usb.UsbManager
import android.os.Bundle
import android.os.Handler
import android.text.Spannable
import android.text.SpannableStringBuilder
import android.text.style.ForegroundColorSpan
import android.util.Log
import android.widget.LinearLayout
import android.widget.TextView
import android.widget.Toast
import android_serialport_api.SerialPortFinder
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.AppCompatButton
import androidx.appcompat.widget.AppCompatTextView
import androidx.camera.core.CameraSelector
import androidx.camera.core.Preview
import androidx.camera.lifecycle.ProcessCameraProvider
import androidx.camera.view.PreviewView
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.constraintlayout.widget.ConstraintSet
import androidx.core.app.ActivityCompat
import androidx.core.content.ContentProviderCompat.requireContext
import androidx.core.content.ContextCompat
import androidx.core.view.doOnLayout
import androidx.lifecycle.LifecycleOwner
import com.billin.www.rxble.ble.BluetoothClient
import com.billin.www.rxble.ble.BluetoothClientBLEV2Adapter
import com.billin.www.rxble.ble.bean.BLEDevice
import com.billin.www.rxble.ble.callback.BaseResultCallback
import com.billin.www.rxble.ble.originV2.BluetoothLeInitialization
import com.google.common.util.concurrent.ListenableFuture
import com.hoho.android.usbserial.driver.UsbSerialDriver
import com.hoho.android.usbserial.driver.UsbSerialPort
import com.hoho.android.usbserial.driver.UsbSerialProber
import com.hoho.android.usbserial.util.HexDump
import io.reactivex.Observer
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import java.io.IOException
import java.nio.charset.Charset
import java.text.SimpleDateFormat
import java.util.*
import java.util.concurrent.Executors
import kotlin.properties.Delegates
/*
串口相关:
- USB-VID:0x1A86
- USB-PID:0x55D3
- 波特率:115200
- 字符编码:us-ascii
*/
class MainActivity : AppCompatActivity(), JoystickView.JoyStickListener,BluetoothActivity.BluetoothActivityListener{
//时间戳显示
private lateinit var logArea: TextView
private lateinit var enterTime: String
//手柄消抖
private var joystickLastResponseTime by Delegates.notNull<Long>()
private var joystickDebounceInterval by Delegates.notNull<Long>() // 1秒
init {
joystickLastResponseTime = 0
joystickDebounceInterval = 1000
}
//动态申请权限
private var permission = false
//start 摄像头相关
private val CAMERA_PERMISSION_CODE = 101
private lateinit var cameraProviderFuture : ListenableFuture<ProcessCameraProvider>
//end 摄像头相关
//start 串口相关
private val WRITE_EXTERNAL_STORAGE_CODE: Int = 100
private val USB_PERMISSION_CODE = 2
private val ACTION_USB_PERMISSION = "cn.qsbye.USB_PERMISSION"
private val serial_connected = false //串口连接标志
lateinit var usbIoManager: SerialInputOutputManager //串口io管理器
//end 串口相关
//start 串口命令相关
val cmd_serial_led_on="<led on;>"//开灯
val cmd_serial_led_off="<led off;>"//关灯
//end 串口命令相关
//可供外部访问
companion object {
// Global screen dimensions.
var screenHeight: Int = 0
var screenWidth: Int = 0
const val REQUEST_PERMISSION = 1
private const val PERMISSION_REQUEST_CODE = 123
}
var joystickId = -1
private fun getCurrentTime(): String {
val currentTime = SimpleDateFormat("HH:mm:ss").format(Date())
return currentTime
}
private fun displayTimestamp(timestamp: String): String {
val inputFormat = SimpleDateFormat("HH:mm:ss")
val outputFormat = SimpleDateFormat("hh:mm:ss a")
val date = inputFormat.parse(timestamp)
return outputFormat.format(date)
}
private fun displayLogMessage(logText: String) {
val logArea = findViewById<TextView>(R.id.log_area_text)
val time = this.getCurrentTime()
val logMessage = "$time $logText"
val newText = "${logArea.text}\n$logMessage"
// 设置日志区最大行数
val maxLines = 25
val lines = newText.lines()
val trimmedLines = lines.takeLast(maxLines)
val trimmedText = trimmedLines.joinToString("\n")
logArea.text = trimmedText
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
//start 串口相关
val serialPortFinder = SerialPortFinder()
val serial_list=serialPortFinder.allDevicesPath;//列出串口列表
//end 串口相关
//start 摄像头相关
cameraProviderFuture = ProcessCameraProvider.getInstance(this)//请求 CameraProvider
cameraProviderFuture.addListener(Runnable {
val cameraProvider = cameraProviderFuture.get()
bindPreview(cameraProvider)//调用自定义函数bindPreview
}, ContextCompat.getMainExecutor(this))
//end 摄像头相关
//日志区显示进入
displayLogMessage("
标签:displayLogMessage,USB,val,esp32,串口,import,Android,android
From: https://www.cnblogs.com/qsbye/p/17724532.html