felHR85 / UsbSerial

Usb serial controller for Android
MIT License
1.81k stars 589 forks source link

syncWrite and then syncRead doesn't work #325

Open ptrczajka opened 3 years ago

ptrczajka commented 3 years ago

Hi, I am working with ESP32 (CP2102 USB to UART Bridge Controller). I need to send text command to this device and then immediately read response synchronously in the same function to return data. I am using baud rate 11520 but with lower values the same issue. I checked also on Arduino Uno Rev 3 and the same issue.

if (serialPort.syncOpen()) {
  Log.d(TAG, "port opened successfully!")
  serialPort.setBaudRate(SERIAL_BAUD_RATE)
  serialPort.setDataBits(UsbSerialInterface.DATA_BITS_8)
  serialPort.setStopBits(UsbSerialInterface.STOP_BITS_1)
  serialPort.setParity(UsbSerialInterface.PARITY_NONE)
  /**
   * Current flow control Options:
   * UsbSerialInterface.FLOW_CONTROL_OFF
   * UsbSerialInterface.FLOW_CONTROL_RTS_CTS only for CP2102 and FT232
   * UsbSerialInterface.FLOW_CONTROL_DSR_DTR only for CP2102 and FT232
   */
  serialPort.setFlowControl(UsbSerialInterface.FLOW_CONTROL_OFF)
  //....
 }

//.....
//.....

private fun requestData(textMessage: String): String {
        send(textMessage)
        return read()
}

private fun send(textMessage: String) {
        val messageByteArray = "$textMessage$NEW_LINE".toByteArray()
        val writeResult = serialPort.syncWrite(messageByteArray, USB_WRITE_TIMEOUT)
}
fun read(): String {
        val messageByteArray = ByteArray(1024)  //16384   multiply of 64
        val readDataLength = serialPort.syncRead(messageByteArray, USB_READ_TIMEOUT)
        return messageByteArray.decodeToString()
}

const val SERIAL_BAUD_RATE = 115200 //57600 //115200
const val VENDOR_ID = 4292 // ESP32 4292   //arduino 9025
const val PRODUCT_ID = 60000 // ESP32 60000  //arduino 67
const val USB_READ_TIMEOUT = 3000
const val USB_WRITE_TIMEOUT = 1000
const val NEW_LINE = "\n"

syncWrite is returning result > 0 but messageByteArray from syncRead is empty or sometimes contains not cut and messy data. What I'm doing wrong ? :)

Code from ESP32 / Arduino

#include <Wire.h>

void setup() {
  Serial.begin(115200);
  while (!Serial) {
    delay (100);
  }
}

void loop() {
  String serialANDROID = "";
  if (Serial.available() ) {
    serialANDROID = Serial.readStringUntil('\n');
    if (serialANDROID == "command1") {
      Serial.println ("someData = [123456789123456]/nEND/n/n");
    }
    else if (serialANDROID == "command2"){
      Serial.println("OK/nEND/n/n"); 
    }
    else if (serialANDROID == "command3"){
      Serial.println("test=true/nEND/n/n");
    }
    else if (serialANDROID == "command4") {
      Serial.println ("someExtraData = [1234567891234568685645334354]/nEND/n/n");
    }
    else {
      Serial.println("error"); 
    }
  }
}
ishdemon commented 2 years ago

Use Serial.write from Arduino/ESP32 instead of println