UsbSerial


Source link: https://github.com/felHR85/UsbSerial

UsbSerial

Usb serial controller for Android. For more information, there is a more complete description.

A brief list of Apps and projects using UsbSerial

Devices Supported

CP210X devices Default: 9600,8,1,None,flow off

CDC devices Default 115200,8,1,None,flow off

FTDI devices Default: 9600,8,1,None,flow off

PL2303 devices Default 9600,8,1,None,flow off

CH34x devices Default 9600,8,1,None,flow off

CP2130 SPI-USB

How to use it?

Instantiate a new object of the UsbSerialDevice class

UsbDevice device; UsbDeviceConnection usbConnection; ... UsbSerialDevice serial = UsbSerialDevice.createUsbSerialDevice(device, usbConnection);
 

Open the device and set it up as desired

serial.open();
 serial.setBaudRate(115200);
 serial.setDataBits(UsbSerialInterface.DATA_BITS_8);
 serial.setParity(UsbSerialInterface.PARITY_ODD);
 serial.setFlowControl(UsbSerialInterface.FLOW_CONTROL_OFF);
 

If flow control is needed (currently only supported in CP201x and FTDI devices)

/** Values: 
 UsbSerialInterface.FLOW_CONTROL_OFF 
 UsbSerialInterface.FLOW_CONTROL_RTS_CTS  
 UsbSerialInterface.FLOW_CONTROL_DSR_DTR **/ serial.setFlowControl(UsbSerialInterface.FLOW_CONTROL_RTS_CTS);

There is no need to be polling if you want to perform a bulk transaction to a IN endpoint. Define a simply callback

private UsbSerialInterface.UsbReadCallback mCallback = new UsbSerialInterface.UsbReadCallback() {

 @Override
public void onReceivedData(byte[] arg0)
 {

 // Code here :)

}

 
}
;

And pass a reference of it

serial.read(mCallback);

Changes in the CTS and DSR lines will be received in the same manner. Define a callback and pass a reference of it.

private UsbSerialInterface.UsbCTSCallback ctsCallback = new UsbSerialInterface.UsbCTSCallback() {

@Override

public void onCTSChanged(boolean state) {

// Code here :)

}

  
}
;

private UsbSerialInterface.UsbDSRCallback dsrCallback = new UsbSerialInterface.UsbDSRCallback() {

@Override

public void onDSRChanged(boolean state) {

// Code here :)

}

  
}
;

serial.getCTS(ctsCallback);
 //serial.getDSR(dsrCallback);

Write something

serial.write("DATA".getBytes());
 // Async-like operation now! :)

Raise the state of the RTS or DTR lines

serial.setRTS(true);
 // Raised serial.setRTS(false);
 // Not Raised serial.setDTR(true);
 // Raised serial.setDTR(false);
 // Not Raised

Close the device:

serial.close();

I recommend using UsbSerial as shown above but if you want to perform write and read operations in synchronous way it is possible using these methods:

public boolean syncOpen();
 public int syncWrite(byte[] buffer, int timeout) public int syncRead(byte[] buffer, int timeout) public void syncClose();

In Android usb api, when a usb device has been close it must be reopened

UsbDevice device; ... UsbManager manager = (UsbManager) getSystemService(Context.USB_SERVICE);
 manager.openDevice(UsbDevice device)

How to use the SPI interface (BETA)

Support for USB to SPI devices was added recently but it is still in beta. Although I tried to keep the api as close to standard UsbSerial api as possible, be aware because the beta nature of this feature this api may change in the future. Only CP2130 chipset is supported at the moment.

UsbSpiDevice spi = UsbSpiDevice.createUsbSerialDevice(device, connection);
 spi.connectSPI();
 spi.selectSlave(0);
 spi.setClock(CP2130SpiDevice.CLOCK_3MHz);

Define the usual callback

private UsbSpiInterface.UsbMISOCallback misoCallback = new UsbSpiInterface.UsbMISOCallback()
  {

@Override

public int onReceivedData(byte[] data) {

  // Your code here :)

}

  
}
; //... spi.setMISOCallback(misoCallback);
spi.writeMOSI("Hola!".getBytes());
 // Write "Hola!" to the selected slave through MOSI (MASTER OUTPUT SLAVE INPUT) spi.readMISO(5);
 // Read 5 bytes from the MISO (MASTER INPUT SLAVE OUTPUT) line. Data will be received through UsbMISOCallback spi.writeRead("Hola!".getBytes(), 15);
 // Write "Hola!" and read 15 bytes synchronously

Close the device when done

spi.closeSPI();

Gradle

Add the jitpack repo to your your project's build.gradle at the end of repositories

/build.gradle

allprojects {
  repositories {

jcenter()
maven {
 url "https://jitpack.io" 
}
  
}
 
}

Then add the dependency to your module's build.gradle:

/app/build.gradle

compile 'com.github.felHR85:UsbSerial:4.5'

TO-DO

  • RTS/CTS and DSR/DTR implementations for PL2303 and CDC

Resources

Make random object fly on your screen.

TextView with pictures wrapping and other effects.

Tool which allows to quickly try the demo project of any Android Library

Dexposed is a powerful yet non-invasive runtime AOP (Aspect-oriented Programming) framework for Android app development, based on the work of open-source Xposed framework project.

A method call logging based on dexposed.

A gallery used to host an array of images.

Topics


2D Engines   3D Engines   9-Patch   Action Bars   Activities   ADB   Advertisements   Analytics   Animations   ANR   AOP   API   APK   APT   Architecture   Audio   Autocomplete   Background Processing   Backward Compatibility   Badges   Bar Codes   Benchmarking   Bitmaps   Bluetooth   Blur Effects   Bread Crumbs   BRMS   Browser Extensions   Build Systems   Bundles   Buttons   Caching   Camera   Canvas   Cards   Carousels   Changelog   Checkboxes   Cloud Storages   Color Analysis   Color Pickers   Colors   Comet/Push   Compass Sensors   Conferences   Content Providers   Continuous Integration   Crash Reports   Credit Cards   Credits   CSV   Curl/Flip   Data Binding   Data Generators   Data Structures   Database   Database Browsers   Date &   Debugging   Decompilers   Deep Links   Dependency Injections   Design   Design Patterns   Dex   Dialogs   Distributed Computing   Distribution Platforms   Download Managers   Drawables   Emoji   Emulators   EPUB   Equalizers &   Event Buses   Exception Handling   Face Recognition   Feedback &   File System   File/Directory   Fingerprint   Floating Action   Fonts   Forms   Fragments   FRP   FSM   Functional Programming   Gamepads   Games   Geocaching   Gestures   GIF   Glow Pad   Gradle Plugins   Graphics   Grid Views   Highlighting   HTML   HTTP Mocking   Icons   IDE   IDE Plugins   Image Croppers   Image Loaders   Image Pickers   Image Processing   Image Views   Instrumentation   Intents   Job Schedulers   JSON   Keyboard   Kotlin   Layouts   Library Demos   List View   List Views   Localization   Location   Lock Patterns   Logcat   Logging   Mails   Maps   Markdown   Mathematics   Maven Plugins   MBaaS   Media   Menus   Messaging   MIME   Mobile Web   Native Image   Navigation   NDK   Networking   NFC   NoSQL   Number Pickers   OAuth   Object Mocking   OCR Engines   OpenGL   ORM   Other Pickers   Parallax List   Parcelables   Particle Systems   Password Inputs   PDF   Permissions   Physics Engines   Platforms   Plugin Frameworks   Preferences   Progress Indicators   ProGuard   Properties   Protocol Buffer   Pull To   Purchases   Push/Pull   QR Codes   Quick Return   Radio Buttons   Range Bars   Ratings   Recycler Views   Resources   REST   Ripple Effects   RSS   Screenshots   Scripting   Scroll Views   SDK   Search Inputs   Security   Sensors   Services   Showcase Views   Signatures   Sliding Panels   Snackbars   SOAP   Social Networks   Spannable   Spinners   Splash Screens   SSH   Static Analysis   Status Bars   Styling   SVG   System   Tags   Task Managers   TDD &   Template Engines   Testing   Testing Tools   Text Formatting   Text Views   Text Watchers   Text-to   Toasts   Toolkits For   Tools   Tooltips   Trainings   TV   Twitter   Updaters   USB   User Stories   Utils   Validation   Video   View Adapters   View Pagers   Views   Watch Face   Wearable Data   Wearables   Weather   Web Tools   Web Views   WebRTC   WebSockets   Wheel Widgets   Wi-Fi   Widgets   Windows   Wizards   XML   XMPP   YAML   ZIP Codes