Skip to content

Instantly share code, notes, and snippets.

@pavi2410
Last active April 29, 2020 15:51
Show Gist options
  • Save pavi2410/d6a9e11a99421dff430b394579e6834d to your computer and use it in GitHub Desktop.
Save pavi2410/d6a9e11a99421dff430b394579e6834d to your computer and use it in GitHub Desktop.
// Copyright 2017-2018 Pavitra, All rights reserved
// Released under the Apache License, Version 2.0
// http://www.apache.org/licenses/LICENSE-2.0
package com.pavitra;
import android.content.Context;
import android.util.Log;
import com.physicaloid.lib.*;
import com.google.appinventor.components.annotations.*;
import com.google.appinventor.components.runtime.*;
import com.google.appinventor.components.common.*;
import java.io.UnsupportedEncodingException;
@DesignerComponent(version = 6,
description = "Arduino USB Serial Extension by Pavitra.",
category = ComponentCategory.EXTENSION,
nonVisible = true,
iconName = "images/extension.png")
@SimpleObject(external = true)
@UsesLibraries(libraries = "physicaloid.jar")
public class Arduino extends AndroidNonvisibleComponent implements Component {
private static final String LOG_TAG = "Arduino USB Serial Extension";
private Context context;
Physicaloid mPhysicaloid;
private int baudRate = 9600;
public Arduino(ComponentContainer container) {
super(container.$form());
context = container.$context();
Log.d(LOG_TAG, "Created");
}
@SimpleFunction
public void Initialize() {
mPhysicaloid = new Physicaloid(context);
Log.d(LOG_TAG, "Initialized");
}
@SimpleFunction
public boolean Open() {
Log.d(LOG_TAG, "Opening connection");
return mPhysicaloid.open();
}
@SimpleFunction
public boolean Close() {
Log.d(LOG_TAG, "Closing connection");
return mPhysicaloid.close();
}
@SimpleFunction(description = "Default baud rate is 9600 bps")
public void BaudRate(int baudRate) {
this.baudRate = baudRate;
mPhysicaloid.setBaudrate(baudRate);
Log.d(LOG_TAG, "Baud Rate: " + baudRate);
}
@SimpleFunction(description = "Read from Serial")
public void Read() {
byte[] buf = new byte[256];
boolean success = true;
String data = "";
if (mPhysicaloid.read(buf) > 0) {
try {
data = new String(buf, "UTF-8");
} catch (UnsupportedEncodingException e) {
success = false;
Log.e(LOG_TAG, e.getMessage());
}
} else {
success = false;
}
AfterRead(success, data);
}
@SimpleFunction(description = "Write Data to Serial")
public void Write(String writeData) {
if (!writeData.isEmpty()) {
byte[] buf = writeData.getBytes();
mPhysicaloid.write(buf);
}
}
@SimpleFunction
public boolean IsOpened() {
return mPhysicaloid.isOpened();
}
@SimpleEvent
public void AfterRead(boolean success, String data) {
EventDispatcher.dispatchEvent(this, "AfterRead", success, data);
}
}
Copy link

ghost commented Mar 21, 2020

Hey, Trying to work on kodular with arduino but I don't get prompt to ask access to usb for serial.
Anything I miss?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment