Tuesday, June 25, 2013

Communication between Arduino and PC running Java, with JavaFX UI

Last posts "Setup RxTx for Arduino and Java example" and "Create Java project using librxtx-java in Netbeans, work with Arduino" describe basic setup to program Java with RxTx library in Netbeans, to receive data from Arduino Due. In this post, I will show bi-direction communication between Arduino Due and PC running Java, with JavaFX user interface.

Communication between Arduino and PC running Java, with JavaFX UI
Communication between Arduino and PC running Java, with JavaFX UI
User enter message in JavaFX and click the button, the message will be sent to Arduino via Serial. In Arduino side, it loop back the message to PC. Then, if received in PC side, it will be displayed in JavaFX.



It's a very simple code in Arduino side:
void setup() {
  Serial.begin(9600);
}

void loop() {
  if(Serial.available() > 0){
    Serial.print((char)Serial.read());
  }
}


In PC side, it's modified from last post, implement in JavaFX, with bi-direction communication.
package javafx_arduinotestserial;

import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;
import gnu.io.SerialPortEvent;
import gnu.io.SerialPortEventListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

/**
 * @web arduino-er.blogspot.com
 */
public class JavaFX_ArduinoTestSerial extends Application {

    MyRxTx myRxTx;
    Label textInfo, textIn;

    @Override
    public void start(Stage primaryStage) {

        final TextField textOut = new TextField();
        textOut.setText("Hello Arduino-er!");

        textInfo = new Label();
        textIn = new Label();

        Button btn = new Button();
        btn.setText("Say 'Hello World'");
        btn.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {
                String stringOut = textOut.getText() + "\r\n";

                try {
                    myRxTx.output.write(stringOut.getBytes());
                } catch (IOException ex) {
                    Logger.getLogger(
                            JavaFX_ArduinoTestSerial.class.getName())
                            .log(Level.SEVERE, null, ex);
                }
            }
        });

        VBox panel = new VBox(10);
        panel.setPadding(new Insets(10, 10, 10, 10));
        panel.getChildren().addAll(textInfo, textOut, btn, textIn);

        StackPane root = new StackPane();
        root.getChildren().add(panel);

        Scene scene = new Scene(root, 300, 250);

        primaryStage.setTitle("Hello World!");
        primaryStage.setScene(scene);
        primaryStage.show();

        myRxTx = new MyRxTx();
        myRxTx.initialize();
    }

    public static void main(String[] args) {
        launch(args);
    }

    class MyRxTx implements SerialPortEventListener {

        SerialPort serialPort;
        /**
         * The port we're normally going to use.
         */
        private final String PORT_NAMES[] = {
            "/dev/ttyACM0", //for Ubuntu
            "/dev/tty.usbserial-A9007UX1", // Mac OS X
            "/dev/ttyUSB0", // Linux
            "COM3", // Windows
        };
        private BufferedReader input;
        private OutputStream output;
        private static final int TIME_OUT = 2000;
        private static final int DATA_RATE = 9600;

        public void initialize() {
            CommPortIdentifier portId = null;
            Enumeration portEnum = CommPortIdentifier.getPortIdentifiers();

            //First, Find an instance of serial port as set in PORT_NAMES.
            while (portEnum.hasMoreElements()) {
                CommPortIdentifier currPortId =
                        (CommPortIdentifier) portEnum.nextElement();
                for (String portName : PORT_NAMES) {
                    if (currPortId.getName().equals(portName)) {
                        portId = currPortId;
                        break;
                    }
                }
            }
            if (portId == null) {
                System.out.println("Could not find COM port.");
                return;
            } else {
                textInfo.setText("Port Name: " + portId.getName() + "\n"
                        + "Current Owner: " + portId.getCurrentOwner() + "\n"
                        + "Port Type: " + portId.getPortType());
            }

            try {
                // open serial port, and use class name for the appName.
                serialPort = (SerialPort) portId.open(this.getClass().getName(),
                        TIME_OUT);

                // set port parameters
                serialPort.setSerialPortParams(DATA_RATE,
                        SerialPort.DATABITS_8,
                        SerialPort.STOPBITS_1,
                        SerialPort.PARITY_NONE);

                // open the streams
                input = new BufferedReader(
                        new InputStreamReader(serialPort.getInputStream()));
                output = serialPort.getOutputStream();

                // add event listeners
                serialPort.addEventListener(this);
                serialPort.notifyOnDataAvailable(true);
            } catch (Exception e) {
                System.err.println(e.toString());
            }
        }

        @Override
        public void serialEvent(SerialPortEvent spe) {
            if (spe.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
                try {
                    final String inputLine = input.readLine();

                    Platform.runLater(new Runnable() {
                        @Override
                        public void run() {
                            textIn.setText(inputLine);
                        }
                    });

                    System.out.println(inputLine);
                } catch (Exception e) {
                    System.err.println(e.toString());
                }
            }
        }

        /**
         * This should be called when you stop using the port. This will prevent
         * port locking on platforms like Linux.
         */
        public synchronized void close() {
            if (serialPort != null) {
                serialPort.removeEventListener();
                serialPort.close();
            }
        }
    }
}

Sunday, June 23, 2013

Create Java project using librxtx-java in Netbeans, work with Arduino

remark: This example work on Ubuntu.

Before create our Java project using librxtx-java, we have to setup something in our PC, refer to lastr post "Setup RxTx for Arduino and Java example".

Create Netbeans Java Project:

- Start Netbeans, Click File -> New Project..., to create a project of Java Application in Java categories.


- with Project Name of SerialTest


Modify the code:

Basically, it's same as the example code in Arduino Playground of Arduino and Java, except the package, and PORT_NAMES of "/dev/ttyACM0".

package serialtest;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import gnu.io.CommPortIdentifier; 
import gnu.io.SerialPort;
import gnu.io.SerialPortEvent; 
import gnu.io.SerialPortEventListener; 
import java.util.Enumeration;


public class SerialTest implements SerialPortEventListener {
 SerialPort serialPort;
        /** The port we're normally going to use. */
 private static final String PORT_NAMES[] = { 
                        "/dev/ttyACM0", //for Ubuntu
   "/dev/tty.usbserial-A9007UX1", // Mac OS X
   "/dev/ttyUSB0", // Linux
   "COM3", // Windows
 };
 /**
 * A BufferedReader which will be fed by a InputStreamReader 
 * converting the bytes into characters 
 * making the displayed results codepage independent
 */
 private BufferedReader input;
 /** The output stream to the port */
 private OutputStream output;
 /** Milliseconds to block while waiting for port open */
 private static final int TIME_OUT = 2000;
 /** Default bits per second for COM port. */
 private static final int DATA_RATE = 9600;

 public void initialize() {
  CommPortIdentifier portId = null;
  Enumeration portEnum = CommPortIdentifier.getPortIdentifiers();

  //First, Find an instance of serial port as set in PORT_NAMES.
  while (portEnum.hasMoreElements()) {
   CommPortIdentifier currPortId = (CommPortIdentifier) portEnum.nextElement();
   for (String portName : PORT_NAMES) {
    if (currPortId.getName().equals(portName)) {
     portId = currPortId;
     break;
    }
   }
  }
  if (portId == null) {
   System.out.println("Could not find COM port.");
   return;
  }

  try {
   // open serial port, and use class name for the appName.
   serialPort = (SerialPort) portId.open(this.getClass().getName(),
     TIME_OUT);

   // set port parameters
   serialPort.setSerialPortParams(DATA_RATE,
     SerialPort.DATABITS_8,
     SerialPort.STOPBITS_1,
     SerialPort.PARITY_NONE);

   // open the streams
   input = new BufferedReader(new InputStreamReader(serialPort.getInputStream()));
   output = serialPort.getOutputStream();

   // add event listeners
   serialPort.addEventListener(this);
   serialPort.notifyOnDataAvailable(true);
  } catch (Exception e) {
   System.err.println(e.toString());
  }
 }

 /**
  * This should be called when you stop using the port.
  * This will prevent port locking on platforms like Linux.
  */
 public synchronized void close() {
  if (serialPort != null) {
   serialPort.removeEventListener();
   serialPort.close();
  }
 }

 /**
  * Handle an event on the serial port. Read the data and print it.
  */
 public synchronized void serialEvent(SerialPortEvent oEvent) {
  if (oEvent.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
   try {
    String inputLine=input.readLine();
    System.out.println(inputLine);
   } catch (Exception e) {
    System.err.println(e.toString());
   }
  }
  // Ignore all the other eventTypes, but you should consider the other ones.
 }

 public static void main(String[] args) throws Exception {
  SerialTest main = new SerialTest();
  main.initialize();
  Thread t=new Thread() {
   public void run() {
    //the following line will keep this app alive for 1000 seconds,
    //waiting for events to occur and responding to them (printing incoming messages to console).
    try {Thread.sleep(1000000);} catch (InterruptedException ie) {}
   }
  };
  t.start();
  System.out.println("Started");
 }
}

In order to access Serial port in Ubuntu, you have to setup the right of the port. Refer to the post Fixed the problem of "No device found on COM1" for /dev/ttyACM0. You have to enter the following command before run the code:

$sudo chmod a+rw /dev/ttyACM0

If everything OK, you can run the program as shown below, the message "Hello world" will be printed every second in Output windows.



Next:
- Communication between Arduino and PC running Java, with JavaFX UI

Setup RxTx for Arduino and Java example

Refer to the post "Arduino and Java", Arduino Playground provide a example of Java code work with Arduino with RxTx library. I will create it work in Netbeans in next post, "Create Java project using librxtx-java in Netbeans, work with Arduino".

In Arduino side, you can 100% copy the provided sample and download to Arduino board, tested on Arduino Due.

List here:
void setup(){
  Serial.begin(9600);
}

void loop(){
  Serial.println("Hello world");
  delay(1000);
}


In PC side, you have to install librxtx-java, setup JAR in Netbeans, and copy librxtxSerial.so to your java library path. Refer to the post of "Install RXTX on Ubuntu" and "Setup RxTx jar and .so for Ubuntu".

The steps to build java program with NetBeans will be in next post. Finally, it will run as shown below.

running


Next:
- Create Java project using librxtx-java in Netbeans, work with Arduino
- Communication between Arduino and PC running Java, with JavaFX UI


Tuesday, June 18, 2013

Practical Raspberry Pi

Practical Raspberry Pi
Practical Raspberry Pi
Practical Raspberry Pi takes you quickly through the hardware and software basics of the Raspberry Pi. Author Brendan Horan then gets you started on a series of fun and practical projects, including a simple temperature sensor, a media center, a real-time clock, and even a security monitoring device, all of which require minimal programming experience.

Along with these projects, you'll learn all about the Raspberry Pi hardware, including how it can be so powerful and still so small and inexpensive, why it's so suitable as a video player, and how you can customize it for different tasks, including running different operating systems on it, including Android and RISC OS.

The Raspberry Pi is an inexpensive but relatively powerful little computer. It was designed to get kids interested in computing and programming, but it's also a great platform for hardware hackery. The projects in this book will get you deep into the hardware to show you what the Raspberry Pi can really do.

What you’ll learn

  • An overview of Raspberry Pi hardware
  • How to get your Pi up and running with Linux
  • How to use your Pi for sensing temperature and driving a simple character LCD
  • How to create a media player with your Raspberry Pi
  • How to use your Pi as a serial console server
  • How to set up your Pi to be a security monitoring device 
  • Other operating systems for your Pi, including Gentoo, Android, and RISC OS 

Who this book is for


Electronics enthusiasts who want to try out the Raspberry Pi, Linux fans who want to create useful projects with the Pi, or anyone interested in learning more about computing, electronics, and networking with this inexpensive and fun little computer.

Table of Contents


Introduction 
Power and power sources
Electronics overview
Tools you'll need

Chapter 1: Raspberry Pi Hardware
Inputs and Outputs
Overview of the ARM11 CPU
Overview of the Broadcom VideoCore IV GPU
Headers and pin out schematics
Notes on unusable headers

Chapter 2: Software Overview and Installing Linux
Why hard-float vs. soft-float is important
Installing Fedora
Optimizing Fedora to run from the SD

Chapter 3: Using GPIO: A Simple Temperature Sensor
Overview and warnings about Pi's GPIO
Connecting the sensor
Writing the code to read the temperature

Chapter 4: Driving a Simple Character LCD
Using an LCD controller and GPIO
Writing to and controlling the LCD

Chapter 5: Security Monitoring Device

Chapter 6: Cross-compiling Applications for the Pi
Why cross-compiling is a good idea
Setting up a cross-compile environment on your desktop
GCC tips and tricks 

Chapter 7: Media Center with Raspberry Pi
Installing XBMC
Setting up HDMI audio and video

Chapter 8: Building a Real-time Clock
Add an independent RTC to your Raspberry Pi

Chapter 9: Embedded, IP-enabled Serial Console Server
Accessing the Pi's UART and building a line-level converter
Linux serial port server set-up

Chapter 10: Appliance Automation
Mains voltage warnings
Building the hardware
Writing the code to turn the appliance on and off

Chapter 11: Other Operating Systems for the Pi
Android
RISC OS
Plan9
Gentoo

Monday, June 17, 2013

Import and setup Android ADK terminal emulator, to work with Arduino ADKTerminalTest example

Last post introduced "Modified ADKTerminalTest example of Arduino 1.5.2", it work with "http://labs.arduino.cc/uploads/ADK/ArduinoTerminal/ThibaultTerminal_ICS_0001.apk" in default. Alternatively, Circuits@Home provide a project "Android ADK terminal emulator for Arduino" with source code, it can work with the modified ADKTerminalTest. This post descript how to import and setup in Eclipse of Android Developer Tools.

Prepare:

- It's assumed you have Android SDK installed on your PC.

- Download and unzip source code of ArduinoTerminalSrc.zip from "Android ADK terminal emulator for Arduino page", it can also be download here directly.

- Make sure Android 2.3.3 (API 10) and associated Google APIs are installed in your Android Developer Tools. In Eclipse, select Window in menu bar, -> Android SDK Manager.


Import downloaded ArduinoTerminalSrc:

- Click File -> Import...


-  Select "Existing Android Code into Workspace" under Android section.



- Browse to select downloaded and unziped folder.


- Optionally check "Copy projects into workspace" and click Finish.


- After a moment of auto-build, many error of something like "The import com.android.future cannot be resolved" will be reported.


- Right click your project - > Properties.


- Select Target Google APIs of Platform 2.3.3, and click OK.


- After finished and re-built, you can download it to your Android device. It can work with the modified ADKTerminalTest.

remark:
- Tested on Nexus One with Android 2.3.6. But not work on HTC One X with Android 4.1.1, dur to issues of Theme!


Test ADKTerminalTest example of Arduino 1.5.2, with Android ADK terminal emulator for Arduino

Arduino 1.5.2 provide a ADKTerminalTest example to demonstrates USB Host connectivity between an Android phone and an Arduino Due. It provide source code in Arduino Due side, and url to load Android APK from "http://labs.arduino.cc/uploads/ADK/ArduinoTerminal/ThibaultTerminal_ICS_0001.apk". But I can't find the source code of ThibaultTerminal_ICS_0001. Alternatively, I found "Android ADK terminal emulator for Arduino (ArduinoTerminal)" with source code provided.

In this post, I will describe how to make ADKTerminalTest example work with ArduinoTerminal. In next post, I will show how to import and setup ArduinoTerminalSrc in Android Developer Tools. After finished, you can connect and send text between Arduino Due and Nexus One running Android 2.3.6.

Arduino Due work with Nexus One
Arduino Due work with Nexus One
To load ADKTerminalTest example of Arduino 1.5.2, select File -> Examples -> USBHost -> ADKTerminalTest.

ADKTerminalTest example in Arduino 1.5.2
ADKTerminalTest example in Arduino 1.5.2

Modify on Arduino code:
  • Modify adk() parameters to match with Android side. To acknowledge the originator of Android ADK terminal emulator for Arduino, I use the original counter part.
  • Add the code Serial.begin(9600) in setup() method.
/*

 ADK Terminal Test

 This demonstrates USB Host connectivity between an 
 Android phone and an Arduino Due.

 The ADK for the Arduino Due is a work in progress
 For additional information on the Arduino ADK visit 
 http://labs.arduino.cc/ADK/Index

 created 27 June 2012
 by Cristian Maglie

*/

#include "variant.h"
#include <stdio.h>
#include <adk.h>
/*
// Accessory descriptor. It's how Arduino identifies itself to Android.
char applicationName[] = "Arduino_Terminal"; // the app on your phone
char accessoryName[] = "Arduino Due"; // your Arduino board
char companyName[] = "Arduino SA";

// Make up anything you want for these
char versionNumber[] = "1.0";
char serialNumber[] = "1";
char url[] = "http://labs.arduino.cc/uploads/ADK/ArduinoTerminal/ThibaultTerminal_ICS_0001.apk";
*/

USBHost Usb;
//ADK adk(&Usb, companyName, applicationName, accessoryName,versionNumber,url,serialNumber);

ADK adk(&Usb,"Circuits@Home, ltd.",
            "USB Host Shield",
            "Arduino Terminal for Android",
            "1.0",
            "http://www.circuitsathome.com",
            "0000000000000001");

void setup()
{
  
      Serial.begin(9600);  //<-- need to add
      
 cpu_irq_enable();
 printf("\r\nADK demo start\r\n");
 delay(200);
}

#define RCVSIZE 128

void loop()
{
 uint8_t buf[RCVSIZE];
 uint32_t nbread = 0;
 char helloworld[] = "Hello World!\r\n";

 Usb.Task();

 if (adk.isReady())
 {
  /* Write hello string to ADK */
  adk.write(strlen(helloworld), (uint8_t *)helloworld);

  delay(1000);

  /* Read data from ADK and print to UART */
  adk.read(&nbread, RCVSIZE, buf);
  if (nbread > 0)
  {
   printf("RCV: ");
   for (uint32_t i = 0; i < nbread; ++i)
   {
    printf("%c", (char)buf[i]);
   }
   printf("\r\n");
  }
 }
}


Next:
- Import and setup Android ADK terminal emulator, to work with Arduino ADKTerminalTest example

Sunday, June 16, 2013

RXTX Java library


RXTX is the Java library Arduino IDE used to communicate to the serial. It can be used by developers to develop applications communicating with Arduino board.

Visit RXTX home page

Arduino and Java


The Arduino IDE itself is written in Java, and it can communicate to the serial port via the RXTX Java library. That library is very similar to the Java Communications API extension.

The document "Arduino Playground - Arduino and Java" provide set up and sample java code to develop Java application working with Arduino.

Processing 2.0 read ADC of Arduino Due via serial

Processing 2.0 read ADC of Arduino Due via serial
Processing 2.0 read ADC of Arduino Due via serial
This exercise of Processing 2.0 code read ADC of Arduino Due via serial. The code in Arduino Due listed in last post.

Code in Processing 2.0 side:
import processing.serial.*;

Serial myArduinoPort;
int data;
int index;

int MAX_INDEX = 400;

void setup(){
  size(400, 300);
  background(255);
   
  //Get serial port for Arduino
  String arduinoPort = Serial.list()[0];
  println(arduinoPort);
  myArduinoPort = new Serial(this, arduinoPort, 19200);
  
  index = 0;
}

void draw(){
  
  while(myArduinoPort.available() > 0){
    data = myArduinoPort.read();
    stroke(0);
    line(index, 300, index, 300-data);
    stroke(255);
    line(index, 0, index, 300-data+1);
    print(data);
    print(".");
    
    index++;
    if(index==MAX_INDEX){
      index = 0;
    }
  }
  println("");
}



download filesDownload the files.

Read ADC of Arduino Due with Processing 2.0

This exercise demonstrate reading ADC in Arduino Due board, and send to PC running Processing 2.0 via serial port, then display in PC.



Code in PC side running Processing 2.0 is in next post.

Code in Arduino Due board.
int led = 13;
boolean ledon;

int analogInputA1 = A1;

const int MAX_INDEX = 400;
int var[MAX_INDEX];
int varIndex;

volatile boolean dataReady;

int FREQ_1KHz = 1000;

void TC3_Handler(){
    TC_GetStatus(TC1, 0);
    
    digitalWrite(led, ledon = !ledon);
    
    if(!dataReady){
      var[varIndex] = analogRead(analogInputA1);  //read ADC input
      varIndex++;
      if(varIndex == MAX_INDEX){
        varIndex = 0;
        dataReady = true;
      }
    }
    
}

void startTimer(Tc *tc, uint32_t channel, IRQn_Type irq, uint32_t frequency){
  
    //Enable or disable write protect of PMC registers.
    pmc_set_writeprotect(false);
    //Enable the specified peripheral clock.
    pmc_enable_periph_clk((uint32_t)irq);  
    
    TC_Configure(tc, channel, TC_CMR_WAVE|TC_CMR_WAVSEL_UP_RC|TC_CMR_TCCLKS_TIMER_CLOCK4);
    uint32_t rc = VARIANT_MCK/128/frequency;
    
    TC_SetRA(tc, channel, rc/2);
    TC_SetRC(tc, channel, rc);
    TC_Start(tc, channel);
    
    tc->TC_CHANNEL[channel].TC_IER = TC_IER_CPCS;
    tc->TC_CHANNEL[channel].TC_IDR = ~TC_IER_CPCS;
    NVIC_EnableIRQ(irq);
}

void setup() {
  pinMode(led, OUTPUT);
  
  Serial.begin(19200);
  analogReadResolution(8);  //set ADC resolution to 8 bits
  dataReady = false;
  varIndex = 0;
  startTimer(TC1, 0, TC3_IRQn, FREQ_1KHz);
}

void loop() {
  
  if(dataReady){  
    for(int i = 0; i < MAX_INDEX; i++)
    {
      Serial.write(var[i]);
    }
    dataReady = false;
  }
}


download filesDownload the files.

Saturday, June 15, 2013

Processing code sample: draw Text with Fonts

Example to draw text with installed fonts.

draw Text with Fonts
draw Text with Fonts


PFont fontBitstreamCharter20;
PFont fontBitstreamCharterBoldItalic20;
PFont fontDejaVuSans16;

void setup() {
  size(600, 300);
  background(255);
  
  //Create fonts
  fontBitstreamCharter20 = createFont("Bitstream Charter", 20, true);  //name, size, smooth
  fontBitstreamCharterBoldItalic20 = createFont("Bitstream Charter Bold Italic", 20);    //name, size
  fontDejaVuSans16 = createFont("DejaVu Sans", 16);          //name, size
  
  fill(0); 
  
  textFont(fontBitstreamCharter20);
  text("fontBitstreamCharter20", 10, 25);
  textFont(fontBitstreamCharter20, 16);
  text("fontBitstreamCharter20, 16", 10, 50);
  
  textFont(fontBitstreamCharterBoldItalic20);
  text("fontBitstreamCharterBoldItalic20", 10, 75);
  textFont(fontBitstreamCharterBoldItalic20, 32);
  text("fontBitstreamCharterBoldItalic20, 32", 10, 100);
  
  textFont(fontDejaVuSans16);
  text("fontDejaVuSans16", 10, 125);
  textFont(fontDejaVuSans16, 32);
  text("fontDejaVuSans16, 32", 10, 150);
}

void draw() {
}

Processing code sample: list available fonts

To list installed fonts in Processing, call the function PFont.list().

list installed fonts in Processing
list installed fonts in Processing


void setup() {
  size(400, 300);
  background(255);

  String[] fontList = PFont.list();
  println(fontList);
}

void draw() {
}

Friday, June 14, 2013

Make: Analog Synthesizers


Make: Analog Synthesizers


Dive hands-on into the tools, techniques, and information for making your own analog synthesizer. If you’re a musician or a hobbyist with experience in building electronic projects from kits or schematics, this do-it-yourself guide will walk you through the parts and schematics you need, and how to tailor them for your needs. Author Ray Wilson shares his decades of experience in synth-DIY, including the popular Music From Outer Space (MFOS) website and analog synth community.

At the end of the book, you’ll apply everything you’ve learned by building an analog synthesizer, using the MFOS Noise Toaster kit. You’ll also learn what it takes to create synth-DIY electronic music studio. Get started in the fun and engaging hobby of synth-DIY without delay.

With this book, you’ll learn:
  • The differences between analog and digital synthesizers
  • Analog synthesizer building blocks, including VCOs, VCFs, VCAs, and LFOs
  • How to tool up for synth-DIY, including electronic instruments and suggestions for home-made equipment
  • Foundational circuits for amplification, biasing, and signal mixing
  • How to work with the MFOS Noise Toaster kit
  • Setting up a synth-DIY electronic music studio on a budget

Download ADK Source in Ubuntu

The document "Downloading the ADK Source" describe how to obtain the source material for the ADK. Before that, we have to install curl, git and repo. The steps below show how to install the tools and also ADK source in Ubuntu (13.04).

- Open Terminal.

- Install curl
$sudo apt-get install curl

- Install git
$sudo apt-get install git

- Then create bin/ directory in home directory, and include it in your path.
$mkdir ~/bin
$PATH=~/bin:$PATH

- Install Repo
$curl https://dl-ssl.google.com/dl/googlesource/git-repo/repo > ~/bin/repo
$chmod a+x ~/bin/repo

- Finally, create a new directory for the downloaded ADK source files, initialize and synchronize a local repository:
$mkdir android-accessories
$cd android-accessories
$repo init -u https://android.googlesource.com/accessories/manifest
$repo sync

After successfully completing this process, you should have the source code and tools for working with the ADK 2012:

adk2012/board - Source code and hardware design files for the ADK 2012
adk2012/app - Source code for the ADK 2012 Android companion application
external/ide - Source code for the ADK 2012 Integrated Development Environment (IDE)
external/toolchain - The toolchain used by the ADK 2012 IDE

Wednesday, June 12, 2013

Amarino: new interface between Android And Arduino





Amarino is a toolkit, basically consisting of an Android application and an Arduino library which will help you to interface with your phone in a new dimension. You can build your own interfaces almost without any programming experience.


Processing 2.0 communication with Arduino via serial

This example demonstrate how to send date via serial with Processing 2.0. It work with Arduino Due with code in last post, to send command from PC running Processing 2.0, to Arduino Due.

Processing 2.0 communication with Arduino via serial
Processing 2.0 communication with Arduino via serial


import processing.serial.*;

Serial myArduinoPort;

int buttonA_x = 300;
int buttonA_y = 50;
int buttonA_width = 50;
int buttonA_height = 50;
int buttonA_colorR = 0xff;
int buttonA_colorG = 0x00;
int buttonA_colorB = 0x00;
 
int buttonB_x = 300;
int buttonB_y = 150;
int buttonB_width = 50;
int buttonB_height = 50;
int buttonB_r = 10;
int buttonB_color = 200;
 
int defaultColor = 150;
 
boolean buttonA_clicked = false;
boolean buttonB_clicked = false;
 
void setup() {  // setup() runs once
  size(400, 300);
  background(255);
  
  //Get serial port for Arduino
  String arduinoPort = Serial.list()[0];
  println(arduinoPort);
  myArduinoPort = new Serial(this, arduinoPort, 9600);
  
}
  
void draw() {
   
  if(buttonA_clicked){
    fill(buttonA_colorR, buttonA_colorG, buttonA_colorB);
  }else if(buttonB_clicked){
    fill(buttonB_color);
  }else{
    fill(defaultColor);
  }
  ellipse(width/2, height/2, 100, 100);
 
  fill(buttonA_colorR, buttonA_colorG, buttonA_colorB);
  rect(buttonA_x, buttonA_y, buttonA_width, buttonA_height);
   
  fill(buttonB_color);
  rect(buttonB_x, buttonB_y, buttonB_width, buttonB_height, buttonB_r);
}
 
/* The mouseClicked() function is called once after a mouse button 
 * has been pressed and then released.
 */
void mouseClicked(){
  // mouseX = x of mouse click position
  // mouseY = y of mouse click position
   
  if (mouseX >= buttonA_x && mouseX <= buttonA_x + buttonA_width && 
      mouseY >= buttonA_y && mouseY <= buttonA_y + buttonA_height) {
     buttonA_clicked = true;
     
     myArduinoPort.write("H");
   } else {
     buttonA_clicked = false;
   }
    
   if (mouseX >= buttonB_x && mouseX <= buttonB_x + buttonB_width && 
       mouseY >= buttonB_y && mouseY <= buttonB_y + buttonB_height) {
     buttonB_clicked = true;
     
     myArduinoPort.write("L");
   } else {
     buttonB_clicked = false;
   }
}


Arduino Due communication with PC running Processing 2.0

Similar to the example "Read byte from Serial port and set pin", this example demonstrate how to control LED on Arduino Due board with PC running Processing 2.0.


It's the code in the Arduino Due side, the PC side Processing code will be in next post.

int led = 13;
int incomingByte = 0;
 
void setup() {
    pinMode(led, OUTPUT);
     
    //Setup Serial Port with baud rate of 9600
    Serial.begin(9600);
    Serial.println("Press H to turn LED ON");
    Serial.println("Press L to turn LED OFF");
}
 
void loop() {
    if (Serial.available() > 0) {
        // read the incoming byte:
        incomingByte = Serial.read();
     
        if(incomingByte == 'H'){
            digitalWrite(led, HIGH);
            Serial.println("LED ON");
        }else if(incomingByte == 'L'){
            digitalWrite(led, LOW);
            Serial.println("LED OFF");
        }else{
            Serial.println("invalid!");
        }
       
    }
}

Saturday, June 8, 2013

Processing code sample: detect mouse event

To detect mouse event implement mouse related callback function; mouseClicked(), mouseDragged(), mouseMoved(), mousePressed() and mouseReleased(). The system variable mouseX and mouseY contain the current X and Y coordinate of the mouse.

void setup(){
  size(400, 300);
  background(255);
}

void draw(){
}

// The mouseClicked() function is called once after a 
// mouse button has been pressed and then released.
void mouseClicked(){
  fill(0xFF, 0x00, 0x00);
  ellipse(mouseX, mouseY, 50, 50);
}

// The mouseDragged() function is called once every 
// time the mouse moves and a mouse button is pressed.
void mouseDragged(){
  fill(0x00, 0xFF, 0x00);
  ellipse(mouseX, mouseY, 50, 50);
}

// The mouseMoved() function is called every time the 
// mouse moves and a mouse button is not pressed.
void mouseMoved(){
  fill(0xFF, 0xFF, 0xFF);
  ellipse(mouseX, mouseY, 50, 50);
}

// The mousePressed() function is called once after 
// every time a mouse button is pressed. The mouseButton 
// variable (see the related reference entry) can be used 
// to determine which button has been pressed.
void mousePressed(){
  fill(0xFF, 0x00, 0xFF);
  rect(mouseX, mouseY, 50, 50);
}

// The mouseReleased() function is called every time a 
// mouse button is released.
void mouseReleased(){
  fill(0x00, 0xFF, 0xFF);
  rect(mouseX, mouseY, 50, 50);
}

detect mouse event in Processing
detect mouse event in Processing


Friday, June 7, 2013

Processing code: implement button

The example implement two rect as button, and fill the circle with corresponding color.

implement button in Processing
implement button in Processing


int buttonA_x = 300;
int buttonA_y = 50;
int buttonA_width = 50;
int buttonA_height = 50;
int buttonA_colorR = 0xff;
int buttonA_colorG = 0x00;
int buttonA_colorB = 0x00;

int buttonB_x = 300;
int buttonB_y = 150;
int buttonB_width = 50;
int buttonB_height = 50;
int buttonB_r = 10;
int buttonB_color = 200;

int defaultColor = 150;

boolean buttonA_clicked = false;
boolean buttonB_clicked = false;

void setup() {  // setup() runs once
  size(400, 300);
  background(255);
}
 
void draw() {
  
  if(buttonA_clicked){
    fill(buttonA_colorR, buttonA_colorG, buttonA_colorB);
  }else if(buttonB_clicked){
    fill(buttonB_color);
  }else{
    fill(defaultColor);
  }
  ellipse(width/2, height/2, 100, 100);

  fill(buttonA_colorR, buttonA_colorG, buttonA_colorB);
  rect(buttonA_x, buttonA_y, buttonA_width, buttonA_height);
  
  fill(buttonB_color);
  rect(buttonB_x, buttonB_y, buttonB_width, buttonB_height, buttonB_r);
}

/* The mouseClicked() function is called once after a mouse button 
 * has been pressed and then released.
 */
void mouseClicked(){
  // mouseX = x of mouse click position
  // mouseY = y of mouse click position
  
  if (mouseX >= buttonA_x && mouseX <= buttonA_x + buttonA_width && 
      mouseY >= buttonA_y && mouseY <= buttonA_y + buttonA_height) {
     buttonA_clicked = true;
   } else {
     buttonA_clicked = false;
   }
   
   if (mouseX >= buttonB_x && mouseX <= buttonB_x + buttonB_width && 
       mouseY >= buttonB_y && mouseY <= buttonB_y + buttonB_height) {
     buttonB_clicked = true;
   } else {
     buttonB_clicked = false;
   }
}

Processing code: fill shapes with color, using fill() method

Example to fill shapes with color in Processing 2.0+, using fill() method:

fill shapes with color in Processing
fill shapes with color in Processing


int buttonA_x = 300;
int buttonA_y = 50;
int buttonA_width = 50;
int buttonA_height = 50;
int buttonA_colorR = 0xff;
int buttonA_colorG = 0x00;
int buttonA_colorB = 0x00;

int buttonB_x = 300;
int buttonB_y = 150;
int buttonB_width = 50;
int buttonB_height = 50;
int buttonB_r = 10;
int buttonB_color = 200;

int defaultColor = 150;

void setup() {  // setup() runs once
  size(400, 300);
  background(255);
}
 
void draw() {
  
  line(0, 0, width, height);
  
  fill(defaultColor);
  ellipse(width/2, height/2, 100, 100);
  
  fill(buttonA_colorR, buttonA_colorG, buttonA_colorB);
  rect(buttonA_x, buttonA_y, buttonA_width, buttonA_height);
  
  fill(buttonB_color);
  rect(buttonB_x, buttonB_y, buttonB_width, buttonB_height, buttonB_r);
}

MagPi June available for download now

MagPi issue 13 June available for download now, PDF provided.

http://www.themagpi.com/en/issue/13

Thursday, June 6, 2013

Hello Processing 2.0 - draw something

It's my first try of using Processing 2.0, to draw something.

draw something in Processing

draw something in Processing


void setup() {  // setup() runs once
  size(400, 300);
  background(200);
}
 
void draw() {
  line(0, 0, width, height);
  ellipse(width/2, height/2, 100, 100);
  rect(300, 50, 50, 50);
  rect(300, 150, 50, 50, 10);
}

Wednesday, June 5, 2013

Processing 2.0 released


The Processing 2.0 release focuses on faster graphics, new infrastructure for working with data, and enhanced video playback and capture. It also expands the potential of the programming environment. The new Modes feature allows other programming systems, such as JavaScript and Android, to be easily used from within the development environment. The new Contributions Manager makes it simple to distribute and install extensions developed by the community. The P2D and P3D renderers are now built using modern OpenGL, and programs can now utilize custom GLSL shaders.

Website: http://processing.org/

Tuesday, June 4, 2013

write failed: ENODEV (No such device)



In this previous exercise "Android code for Communication between Android and Arduino Due", it work as expected after plug in Android device into Arduino Due board.



The problem is:

Once I switch out and back the app, and perform onResume()... The app can get fileDescriptor, myAdkInputStream and myAdkOutputStream. But when it try to write to myAdkOutputStream in WriteAdk(String text) method, IOException of "write failed: ENODEV (No such device)" thrown!

Anybody can advise?

Monday, June 3, 2013

Android code for Communication between Android and Arduino Due

It's the code in Android side for the example "Communication between Android and Arduino Due".

Communication between Android and Arduino Due
Communication between Android and Arduino Due


AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.androidadkcommunication"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="12"
        android:targetSdkVersion="17" />
    
    <uses-feature android:name="android.hardware.usb.accessory"/>

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <uses-library android:name="com.android.future.usb.accessory"/>
        <activity
            android:name="com.example.androidadkcommunication.MainActivity"
            android:label="@string/app_name" 
            android:screenOrientation="portrait" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
            <intent-filter>
                <action android:name="android.hardware.usb.action.USB_ACCESSORY_ATTACHED" />
            </intent-filter>
            <meta-data android:name="android.hardware.usb.action.USB_ACCESSORY_ATTACHED"
                android:resource="@xml/myfilter"/>
        </activity>
    </application>

</manifest>


/res/xml/myfilter.xml
<?xml version="1.0" encoding="UTF-8"?>
<resources>
    <usb-accessory
        manufacturer="Arduino-er"
        model="AndroidADKCommunication"
        version="0.1"/>
</resources>


Layout file, /res/layout/activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity" >

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:background="#E0E0E0"
        >       
        <TextView
            android:id="@+id/panelin"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>
    </ScrollView>

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:background="#D0D0D0">
        <Button 
            android:id="@+id/send"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:text="Send to Arduino"/>
        <EditText 
            android:id="@+id/textout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_above="@id/send"/>
    </RelativeLayout>

</LinearLayout>


Create a abstract class AbstractAdkActivity.java.
/*
 * abstract class for Activities have to read ADK
 * for android:minSdkVersion="12"
 * 
 */

package com.example.androidadkcommunication;

import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.usb.UsbAccessory;
import android.hardware.usb.UsbManager;
import android.os.Bundle;
import android.os.ParcelFileDescriptor;

public abstract class AbstractAdkActivity extends Activity {
 
 private static int RQS_USB_PERMISSION = 0;
 private static final String ACTION_USB_PERMISSION = "arduino-er.usb_permission";
 private PendingIntent PendingIntent_UsbPermission;
 
 private UsbManager myUsbManager;
 private UsbAccessory myUsbAccessory;
 private ParcelFileDescriptor myAdkParcelFileDescriptor;
 private FileInputStream myAdkInputStream;
 private FileOutputStream myAdkOutputStream;
 boolean firstRqsPermission;

 //do something in onCreate()
 protected abstract void doOnCreate(Bundle savedInstanceState);
 //do something after adk read
 //protected abstract void doAdkRead(String stringIn);
 protected abstract void doAdkRead_inBackGroundThread(int length, byte[] bfr);
 
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  //setContentView(R.layout.activity_main);
  
  myUsbManager = (UsbManager)getSystemService(Context.USB_SERVICE);
  IntentFilter intentFilter = new IntentFilter();
  intentFilter.addAction(UsbManager.ACTION_USB_ACCESSORY_DETACHED);
  registerReceiver(myUsbReceiver, intentFilter);
  
  //Ask USB Permission from user
  Intent intent_UsbPermission = new Intent(ACTION_USB_PERMISSION);
  PendingIntent_UsbPermission = PendingIntent.getBroadcast(
    this,      //context
    RQS_USB_PERMISSION,  //request code
    intent_UsbPermission, //intent 
    0);      //flags
  IntentFilter intentFilter_UsbPermission = new IntentFilter(ACTION_USB_PERMISSION);
  registerReceiver(myUsbPermissionReceiver, intentFilter_UsbPermission);
  
  firstRqsPermission = true;
  doOnCreate(savedInstanceState);
 }
 
 @Override
 protected void onResume() {
  super.onResume();
  
  if(myAdkInputStream == null || myAdkOutputStream == null){
   
   UsbAccessory[] usbAccessoryList = myUsbManager.getAccessoryList();
   UsbAccessory usbAccessory = null;
   if(usbAccessoryList != null){
    usbAccessory = usbAccessoryList[0];
    
    if(usbAccessory != null){
     if(myUsbManager.hasPermission(usbAccessory)){
      //already have permission
      OpenUsbAccessory(usbAccessory);
     }else{
      
      if(firstRqsPermission){
       
       firstRqsPermission = false;
       
       synchronized(myUsbReceiver){
        myUsbManager.requestPermission(usbAccessory, 
          PendingIntent_UsbPermission);
       }
      }
      
     }
    }
   }
  }
 }
 
 //Write String to Adk
 void WriteAdk(String text){

  byte[] buffer = text.getBytes();

  if(myAdkOutputStream != null){
   
   try {
    myAdkOutputStream.write(buffer);
   } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   } 
  }
 }
 
 //Write a single byte to Adk
 void WriteByteAdk(byte oneByte){
  if(myAdkOutputStream != null){
   try {
    myAdkOutputStream.write(oneByte);
   } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
  }
 }
 
 @Override
 protected void onPause() {
  super.onPause();
  closeUsbAccessory();
 }

 @Override
 protected void onDestroy() {
  super.onDestroy();
  unregisterReceiver(myUsbReceiver);
  unregisterReceiver(myUsbPermissionReceiver);
 }
 
 Runnable runnableReadAdk = new Runnable(){

  @Override
  public void run() {
   int numberOfByteRead = 0;
   final byte[] buffer = new byte[255];
   
   while(numberOfByteRead >= 0){
    
    try {
     
     numberOfByteRead = myAdkInputStream.read(buffer, 0, buffer.length);
     if(numberOfByteRead > 0){
      doAdkRead_inBackGroundThread(numberOfByteRead, buffer);
     }

    } catch (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
     break;
    }
   }
  }
  
 };
 
 private BroadcastReceiver myUsbReceiver = new BroadcastReceiver(){
  
  @Override
  public void onReceive(Context context, Intent intent) {

   String action = intent.getAction();
   if(action.equals(UsbManager.ACTION_USB_ACCESSORY_DETACHED)){

    UsbAccessory usbAccessory = 
      (UsbAccessory)intent.getParcelableExtra(UsbManager.EXTRA_ACCESSORY);
    
    if(usbAccessory!=null && usbAccessory.equals(myUsbAccessory)){
     closeUsbAccessory();
    }
   }
  }
 };
 
 private BroadcastReceiver myUsbPermissionReceiver = new BroadcastReceiver(){

  @Override
  public void onReceive(Context context, Intent intent) {
   String action = intent.getAction();
   if(action.equals(ACTION_USB_PERMISSION)){

    synchronized(this){
     
     UsbAccessory usbAccessory = 
       (UsbAccessory)intent.getParcelableExtra(UsbManager.EXTRA_ACCESSORY);
     
     if(intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)){
      OpenUsbAccessory(usbAccessory);
     }else{
      finish();
     }
    }
   }
  }
  
 };
 
 private void OpenUsbAccessory(UsbAccessory acc){
  myAdkParcelFileDescriptor = myUsbManager.openAccessory(acc);
  if(myAdkParcelFileDescriptor != null){
   
   myUsbAccessory = acc;
   FileDescriptor fileDescriptor = myAdkParcelFileDescriptor.getFileDescriptor();
   myAdkInputStream = new FileInputStream(fileDescriptor);
   myAdkOutputStream = new FileOutputStream(fileDescriptor);
   
   Thread thread = new Thread(runnableReadAdk);
   thread.start();
  }
 }
 
 private void closeUsbAccessory(){
  
  if(myAdkParcelFileDescriptor != null){
   try {
    myAdkParcelFileDescriptor.close();
   } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
  }
  
  myAdkParcelFileDescriptor = null;
  myUsbAccessory = null;
 }
}


MainActivity.java
package com.example.androidadkcommunication;

import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends AbstractAdkActivity {

 TextView textIn;
 EditText editOut;
 Button buttonSend;
 
 @Override
 protected void doOnCreate(Bundle savedInstanceState) {
  setContentView(R.layout.activity_main);
  textIn = (TextView)findViewById(R.id.panelin);
  editOut = (EditText)findViewById(R.id.textout);
  buttonSend = (Button)findViewById(R.id.send);
  buttonSend.setOnClickListener(buttonSendOnClickListener);
  
 }
 
 OnClickListener buttonSendOnClickListener =
   new OnClickListener(){

    @Override
    public void onClick(View arg0) {
     WriteAdk(editOut.getText().toString());
     editOut.setText("");
    }
 };

 @Override
 protected void doAdkRead_inBackGroundThread(int length, byte[] bfr) {

  final String bfrIn = new String(bfr);
  
  runOnUiThread(new Runnable(){

   @Override
   public void run() {
    textIn.setText(bfrIn);
   }});
 }

}


Download Project files.

Look for help: write failed: ENODEV (No such device)

Communication between Android and Arduino Due

This example demonstrate how to send String as byte[] between Android and Arduino Due, with ADK.

Communication between Android and Arduino Due
Communication between Android and Arduino Due

- In Android side (code will be available in next post):
User enter text on EditText on low part of the Android App and tap on the "Send to Arduino" button, the input text will be converted to byte[] and sent out. Any data received will be displayed on upper TextView.

- In Arduino side:
The data received from Android ADK will be sent back to Android.


#include "variant.h"
#include <stdio.h>
#include <adk.h>
#include <stdlib.h>

 
// Accessory descriptor. It's how Arduino identifies itself to Android.
char applicationName[] = "AndroidADKCommunication"; // the app on your phone
char accessoryName[] = "Arduino Due"; // your Arduino board
char companyName[] = "Arduino-er";

// Make up anything you want for these
char versionNumber[] = "0.1";
char serialNumber[] = "1";
char url[] = "https://sites.google.com/site/arduinosite/exercise/androidadkcommunication/AndroidADKCommunication_0.1.apk";
 
USBHost Usb;
ADK adk(&Usb, companyName, applicationName, accessoryName,versionNumber,url,serialNumber);
 
// Pin 13 has an LED connected on most Arduino boards.
int led = 13;
int analogInputA0 = A0;   //ADC input
int analogOutput0 = DAC0;  //DAC output
int analogOutput1 = DAC1;  //DAC output

int varA0;
uint8_t adkVarA0[4];
 
void setup() {
    Serial.begin(9600);
    cpu_irq_enable();
    
    analogReadResolution(12);  //set ADC resolution to 12 bits
   
    pinMode(led, OUTPUT);
    //Indicate start of program
    digitalWrite(led, LOW);
    delay(2000);
    digitalWrite(led, HIGH);
    for(int i = 0; i <= 2; i++){
        digitalWrite(led, HIGH);
        delay(250);
        digitalWrite(led, LOW);
        delay(250);
    }
}
 
#define RCVSIZE 128
 
void loop() {

    uint8_t buf[RCVSIZE];
    uint32_t nbread = 0;
   
    Usb.Task();
     
    if (adk.isReady()){
        digitalWrite(led, HIGH);
         
        adk.read(&nbread, RCVSIZE, buf);
        if (nbread > 0){
            adk.write(nbread, buf);
        }
         
    }else{
        digitalWrite(led, LOW);
    }    
}

Download>>

Related: Android side code for Communication between Android and Arduino Due