Skip to content

Instantly share code, notes, and snippets.

@sabas1080
Forked from pavi2410/Arduino.java
Created February 23, 2019 17:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sabas1080/f73f9c8d07880b8cd82ea1e2f7ef8ce0 to your computer and use it in GitHub Desktop.
Save sabas1080/f73f9c8d07880b8cd82ea1e2f7ef8ce0 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);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment