Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package id.unej.demoarduinosm
- import android.hardware.usb.UsbManager
- import android.os.Bundle
- import android.util.Log
- import androidx.appcompat.app.AppCompatActivity
- import com.hoho.android.usbserial.driver.UsbSerialDriver
- import com.hoho.android.usbserial.driver.UsbSerialPort
- import com.hoho.android.usbserial.driver.UsbSerialProber
- import id.unej.demoarduinosm.databinding.ActivityDemoBinding
- import java.io.IOException
- class DemoActivity : AppCompatActivity() {
- private lateinit var binding: ActivityDemoBinding
- private lateinit var usbManager: UsbManager
- private var usbSerialPort: UsbSerialPort? = null
- companion object {
- private const val TAG = "SAPI"
- }
- override fun onCreate(savedInstanceState: Bundle?) {
- super.onCreate(savedInstanceState)
- binding = ActivityDemoBinding.inflate(layoutInflater)
- setContentView(binding.root)
- usbManager = getSystemService(USB_SERVICE) as UsbManager
- // Tombol untuk mengirim data
- binding.buttonArdu.setOnClickListener {
- sendDataAndReadResponse("A")
- }
- }
- private fun sendDataAndReadResponse(data: String) {
- // Mencari driver USB serial yang terhubung
- val availableDrivers: List<UsbSerialDriver> = UsbSerialProber.getDefaultProber().findAllDrivers(usbManager)
- if (availableDrivers.isEmpty()) {
- Log.e(TAG, "No USB serial device found.")
- return
- }
- // Ambil driver pertama (misalnya, driver untuk Arduino)
- val driver: UsbSerialDriver = availableDrivers[0]
- val connection = usbManager.openDevice(driver.device)
- if (connection == null) {
- Log.e(TAG, "Unable to open device.")
- return
- }
- usbSerialPort = driver.ports[0] // Ambil port pertama dari driver
- try {
- // Set koneksi serial
- usbSerialPort?.open(connection)
- usbSerialPort?.setParameters(115200, 8, UsbSerialPort.STOPBITS_1, UsbSerialPort.PARITY_NONE)
- } catch (e: IOException) {
- Log.e(TAG, "Error with USB serial connection", e)
- }
- if (usbSerialPort == null) {
- Log.e(TAG, "USB serial port is not initialized.")
- return
- }
- try {
- // Kirim data ke Arduino
- val dataToSend = data.toByteArray()
- usbSerialPort?.write(dataToSend, 1000)
- // Baca respons dari Arduino
- val buffer = ByteArray(1024)
- val bytesRead = usbSerialPort?.read(buffer, 1000)
- Log.e(TAG, "sendDataAndReadResponse: $bytesRead", )
- if (bytesRead != null && bytesRead > 0) {
- val response = String(buffer, 0, bytesRead)
- Log.d(TAG, "Response from Arduino: $response")
- binding.tvResult.append("\n$response")
- } else {
- Log.e(TAG, "No response received.")
- }
- } catch (e: IOException) {
- Log.e(TAG, "Error during communication", e)
- }
- }
- override fun onDestroy() {
- super.onDestroy()
- try {
- usbSerialPort?.close()
- } catch (e: IOException) {
- Log.e(TAG, "Error closing USB serial port", e)
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement