Sunday, March 31, 2013

Android code sending command to Arduino Due to turn LED On/Off

It's the coding in Android side to send command to Arduino Due to control LED On/Off.


Modify AndroidManifest.xml to add <uses-feature> of "android.hardware.usb.accessory", <intent-filter> of "android.hardware.usb.action.USB_ACCESSORY_ATTACHED", and <meta-data> of resource="@xml/myfilter".
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.androidadkled"
    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" >
        <activity
            android:name="com.example.androidadkled.MainActivity"
            android:label="@string/app_name" >
            <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>


Create file /res/xml/myfilter.xml
<?xml version="1.0" encoding="UTF-8"?>
<resources>
    <usb-accessory
        manufacturer="Arduino-er"
        model="HelloADKLED"
        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:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:orientation="vertical"
    tools:context=".MainActivity" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Arduino LED Control" />
    <TextView
        android:id="@+id/textin"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
    <RadioGroup
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">
        <RadioButton
            android:id="@+id/LedOn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="LED On" />
        <RadioButton
            android:id="@+id/LedOff"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="LED Off" />
    </RadioGroup>

</LinearLayout>


Create a abstract class AbstractAdkActivity.java to extend Activity, implement the function of ADK; such that we can easy re-use it in furture and reduce the ADK related job in MainActivity.java.
/*
 * abstract class for Activities have to read ADK
 * for android:minSdkVersion="12"
 * 
 */

package com.example.androidadkled;

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); 
 
 @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();
   } 
  }
 }
 
 @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;
   byte[] buffer = new byte[255];
   
   while(numberOfByteRead >= 0){
    
    try {
     numberOfByteRead = myAdkInputStream.read(buffer, 0, buffer.length);
     final StringBuilder stringBuilder = new StringBuilder();
     for(int i=0; i<numberOfByteRead; i++){
      stringBuilder.append((char)buffer[i]);
     }
     
     runOnUiThread(new Runnable(){

      @Override
      public void run() {
       doAdkRead(stringBuilder.toString());
      }});
     
     
    } 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;
 }
}


Modify MainActivity.java to extend AbstractAdkActivity, and extend Activity in-turn. With AbstractAdkActivity handle most of the ADK related job, we only have to override the methods doOnCreate()(called in onCreate() method) and doAdkRead()(called after command read from ADK). To send command to ADK, call WriteAdk() method.
package com.example.androidadkled;

import android.os.Bundle;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AbstractAdkActivity {
 
 TextView textIn;
 RadioButton ledOn, ledOff;

 @Override
 protected void doOnCreate(Bundle savedInstanceState) {
  setContentView(R.layout.activity_main);
  textIn = (TextView)findViewById(R.id.textin);
  ledOn = (RadioButton)findViewById(R.id.LedOn);
  ledOff = (RadioButton)findViewById(R.id.LedOff);
  
  ledOn.setOnCheckedChangeListener(new OnCheckedChangeListener(){

   @Override
   public void onCheckedChanged(CompoundButton buttonView,
     boolean isChecked) {
    if(isChecked){
     WriteAdk("LEDON");
     Toast.makeText(getApplicationContext(), 
       "LEDON", Toast.LENGTH_LONG).show();
    }
   }});
  
  ledOff.setOnCheckedChangeListener(new OnCheckedChangeListener(){

   @Override
   public void onCheckedChanged(CompoundButton buttonView,
     boolean isChecked) {
    if(isChecked){
     WriteAdk("LEDOFF");
     Toast.makeText(getApplicationContext(), 
       "LEDOFF", Toast.LENGTH_SHORT).show();
    }
   }});

 }

 @Override
 protected void doAdkRead(String stringIn) {
  textIn.setText(stringIn);
 }

}


download filesDownload the files.

Refer the another post for the code in Arduino Due side.


Updated@2015-10-15Android control Arduino Due LED, using ADK (Accessory Development Kit)

Saturday, March 30, 2013

Atmel Software Framework (ASF)




The Atmel® Software Framework (ASF) is a MCU software library providing a large collection of embedded software for Atmel flash MCUs: megaAVR, AVR XMEGA, AVR UC3 and SAM devices, include the SAM3X used on Arduino Due.
  • It simplifies the usage of microcontrollers, providing an abstraction to the hardware and high-value middlewares
  • ASF is designed to be used for evaluation, prototyping, design and production phases
  • ASF is integrated in the Atmel Studio IDE with a graphical user interface or available as standalone for GCC, IAR compilers
  • ASF can be downloaded for free

Link:

Thursday, March 28, 2013

Read analog input of Arduino Due board

The Arduino Due Board has 12 analog inputs (pins from A0 to A11), each of which can provide 12 bits of resolution (i.e. 4096 different values). By default, the resolution of the readings is set at 10 bits, for compatibility with other Arduino boards. It is possible to change the resolution of the ADC with analogReadResolution(). The Due’s analog inputs pins measure from ground to a maximum value of 3.3V.

Applying more then 3.3V on the Due’s pins will damage the SAM3X chip. The analogReference() function is ignored on the Due.

Analog input pins on Arduino Due Board
Analog input pins on Arduino Due Board

Example to read from Analog Input:

int analogInputA0 = A0;
int varA0;

void setup() {
  Serial.begin(9600);
  analogReadResolution(12);  //set ADC resolution to 12 bits

}

void loop() {
  varA0 = analogRead(analogInputA0);  //read ADC input
  Serial.println(varA0, HEX);         //print as HEX
  delay(1000);
}

Read Analog Input on Arduino Due
Read Analog Input on Arduino Due


If the code compiled with error: 'analogReadResolution' was not declared in this scope.
Check if you select the correct Tools -> Board.

Firmata: a generic communicating protocol between microcontrollers and host computer

Firmata is a generic protocol for communicating with microcontrollers from software on a host computer. It is intended to work with any host computer software package. Right now there is a matching object in a number of languages. It is easy to add objects for other software to use this protocol. Basically, this firmware establishes a protocol for talking to the Arduino from the host software. The aim is to allow people to completely control the Arduino from software on the host computer.

Firmata
Firmata

Remark: Currently Firmata library not included in Arduino IDE 1.5.1 yet ...

Link:



Tuesday, March 26, 2013

Control Arduino LED using Python with GUI

This example demonstrate how to control Arduino LED using Python with GUI, using tkinter library.


#tkinter for Python 3.x
#Tkinter for Python 2.x

import serial
import time
import tkinter

def quit():
    global tkTop
    tkTop.destroy()

def setCheckButtonText():
    if varCheckButton.get():
        varLabel.set("LED ON")
        ser.write(bytes('H', 'UTF-8'))
    else:
        varLabel.set("LED OFF")
        ser.write(bytes('L', 'UTF-8'))

ser = serial.Serial('/dev/ttyACM1', 9600)
print("Reset Arduino")
time.sleep(3)
ser.write(bytes('L', 'UTF-8'))

tkTop = tkinter.Tk()
tkTop.geometry('300x200')

varLabel = tkinter.StringVar()
tkLabel = tkinter.Label(textvariable=varLabel)
tkLabel.pack()

varCheckButton = tkinter.IntVar()
tkCheckButton = tkinter.Checkbutton(
    tkTop,
    text="Control Arduino LED",
    variable=varCheckButton,
    command=setCheckButtonText)
tkCheckButton.pack(anchor=tkinter.CENTER)

tkButtonQuit = tkinter.Button(
    tkTop,
    text="Quit",
    command=quit)
tkButtonQuit.pack()

tkinter.mainloop()

For the code in Arduino side, refer to the post "Communicate with Arduino in Python programmatically".

Monday, March 25, 2013

Communicate with Arduino in Python programmatically

The previous post demonstrate "Talk with Arduino Due in Python Shell". It will be implement programmatically in module.

note:
  • After open the port, the Arduino will reset. So I insert delay for 3 seconds after serial.Serial('/dev/ttyACM1', 9600).
  • In my board, 115200 seem not too stable. I modify the baud rate to 9600.

Python code:
import serial
import time

# assign your port and speed
ser = serial.Serial('/dev/ttyACM1', 9600)
print("Reset Arduino")
time.sleep(3)
ser.write(bytes('L', 'UTF-8'))

print('Enter 1 to Turn Arduino LED ON')
print('Enter 0 to Turn Arduino LED OFF')
print('Enter Q/q to quit:')

char_in = ''
print(char_in)
while char_in not in ['Q', 'q']:
    char_in = input()

    if char_in == '0':
        print("LED OFF")
        ser.write(bytes('L', 'UTF-8'))
    if char_in == '1':
        print("LED ON")
        ser.write(bytes('H', 'UTF-8'))

Arduino code:
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!");
        }
      
    }
}

Communicate with Arduino with Python programmatically
Communicate with Arduino with Python programmatically


Next:
- Control Arduino LED using Python with GUI


serial.serialutil.SerialException: could not open port /dev/ttyACM0

If you try the steps in the post "Talk with Arduino Due in Python Shell" in Linux (Ubuntu in my setup). May be you will be complained with the error of:

serial.serialutil.SerialException: could not open port /dev/ttyACM0: [Errno 13] Permission denied: '/dev/ttyACM0'

Because your user account have no right to access the /dev/ttyACM0 port. You have to add your user account to the dialout group. Enter the command in Terminal:

$sudo usermod -a -G dialout <username>

After you plug in the usb cable, run the command (it need to be run every time plug-in):

$sudo chmod a+rw /dev/ttyACM0

serial.serialutil.SerialException
serial.serialutil.SerialException

Saturday, March 23, 2013

Learn Raspberry Pi with Linux (Learn Apress)


Learn Raspberry Pi with Linux
Learn Raspberry Pi with Linux (Learn Apress)

Learn Raspberry Pi with Linux will tell you everything you need to know about the Raspberry Pi's GUI and command line so you can get started doing amazing things. You'll learn how to set up your new Raspberry Pi with a monitor, keyboard and mouse, and you'll discover that what may look unfamiliar in Linux is really very familiar. You'll find out how to connect to the internet, change your desktop settings, and you'll get a tour of installed applications.

Next, you'll take your first steps toward being a Raspberry Pi expert by learning how to get around at the Linux command line. You'll learn about different shells, including the bash shell, and commands that will make you a true power user.

Finally, you'll learn how to create your first Raspberry Pi projects:
  • Making a Pi web server: run LAMP on your own network 
  • Making your Pi wireless: remove all the cables and retain all the functionality  
  • Making a Raspberry Pi-based security cam and messenger service: find out who's dropping by
  • Making a Pi media center: stream videos and music from your Pi
Raspberry Pi is awesome, and it's Linux. And it's awesome because it's Linux. But if you've never used Linux or worked at the Linux command line before, it can be a bit daunting. Raspberry Pi is an amazing little computer with tons of potential. And Learn Raspberry Pi with Linux can be your first step in unlocking that potential. 

What you’ll learn

  • How to get online with Raspberry Pi
  • How to customize your Pi's desktop environment
  • Essential commands for putting your Pi to work
  • Basic network services - the power behind what Pi can do
  • How to make your Pi totally wireless by removing all the cables
  • How to turn your Pi into your own personal web server
  • How to turn your Pi into a spy
  • How to turn your Pi into a media center

Who this book is for


Raspberry Pi users who are new to Linux and the Linux command line.


Arduino Adventures: Escape from Gemini Station

Arduino Adventures: Escape from Gemini Station
Arduino Adventures: Escape from Gemini Station
Arduino Adventures: Escape from Gemini Station provides a fun introduction to the Arduino microcontroller by putting you (the reader) into the action of a science fiction adventure story.  You'll find yourself following along as Cade and Elle explore Gemini Station—an orbiting museum dedicated to preserving and sharing technology throughout the centuries.

Trouble ensues. The station is evacuated, including Cade and Elle's class that was visiting the station on a field trip. Cade and Elle don’t make it aboard their shuttle and are trapped on the station along with a friendly artificial intelligence named Andrew who wants to help them get off the damaged station. Using some old hardware, a laptop, and some toolboxes full of electronics parts, you will follow along and build eight gizmos with Cade and Elle that will help them escape from Gemini Station.

The hardware is Arduino. Each new challenge opens a new area of Arduino and basic electronics knowledge. You’ll be taken incrementally from a simple task such as turning on a light through to a complex combination of microcontroller, electronic components, and software programming. By the end of the book you’ll be well on your way towards being able to create and implement any sort of electronically controlled device you can imagine, using the stunningly popular Arduino microcontroller.
  • Provides eight challenges, each challenge increasing in complexity
  • Builds around a fictional storyline that keeps the learning fun
  • Leaves you on a solid foundation of electronic skills and knowledge


What you’ll learn

  • Install and configure Arduino’s programming environment
  • Build understanding of LEDs, Resisters, capacitors, and other basic components
  • Build and test electronic circuits involving breadboarding and basic wiring
  • Program behavior using the Arduino Programming Language
  • Interface and influence the physical world through motors and sensors

Who this book is for



Escape from Gemini Station: An Arduino Hands-On Adventure is suitable for ages 8 and up. No experience is required, and complete instructions are provided on using the Arduino microcontroller. Teachers will find the book useful for the downloadable teacher handouts available from the authors' website. The book is perfect for anyone learning Arduino, or preparing to teach it to first-time users. 


Thursday, March 21, 2013

Talk with Arduino Due in Python Shell

With pySerial installed, it's easy to communicate with Arduino board in Python Shell.

Connect Arduino Due with sketch of former post downloaded.

For Python 2.x, enter the commands in Python Shell to turn ON/OFF LED on Arduino Due Board

>>>import serial
>>>ser = serial.Serial('/dev/ttyACM0', 115200)
>>>ser.write('H')
>>>ser.write('L')


For Python 3.x, the String in write() have to be casted to bytes.

>>>import serial
>>>ser = serial.Serial('/dev/ttyACM0', 115200)
>>>ser.write(bytes('H', 'UTF-8'))
>>>ser.write(bytes('L', 'UTF-8'))





Related:


Install pySerial on Ubuntu

To check if pySerial installed, open Python Shell, type the command:

>>>import serial

if error message returned, means pySerial not installed.

pySerial not installed
pySerial not installed with error

- To install pySerial on Ubuntu, download and unpack pyserial, open Terminal and change to the unpacked folder.

- To install for Python 2.x, type the command:

$sudo python setup.py install


- To install for Python 3.x, type the command:

$sudo python3 setup.py install

(To install the module for all users on the system, administrator rights (root) is required, run with sudo.)


pySerial installed
import serial with pySerial installed


Read byte from Serial port and set pin

This code run on Arduino Due, read byte from Serial port, and set LED pin HIGH/LOW according.


int led = 13;
int incomingByte = 0;

void setup() {
    pinMode(led, OUTPUT);
    
    //Setup Serial Port with baud rate of 115200
    Serial.begin(115200);
    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!");
        }
      
    }
}


Wednesday, March 13, 2013

Request Permission to access USB accessory

In the post "Hello World ADK: Android code", as mentioned we have not requested permission from user to use USB. If user click Cancel to open HelloADK when plug in, and then start this app manually, it will be stopped.

In this version, myUsbManager.requestPermission() will be called if have no permission for USB. And also implement BroadcastReceiver myUsbPermissionReceiver to handle user action. Such that another dialog will be open to ask user to allow accessing the USB accessory.

Request Permission to access USB accessory
requestPermission() dialog


The MainActivity.java code in Android side
/*
 * manufacturer="Arduino-er"
 * model="HelloADK"
 * version="0.2"
 */

package com.example.helloadk;

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

import com.android.future.usb.UsbAccessory;
import com.android.future.usb.UsbManager;

import android.os.Bundle;
import android.os.ParcelFileDescriptor;
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.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {
 
 EditText textOut;
 TextView textIn;
 Button btnSend;
 
 private UsbManager myUsbManager;
 private UsbAccessory myUsbAccessory;
 private ParcelFileDescriptor myParcelFileDescriptor;
 private FileInputStream myFileInputStream;
 private FileOutputStream myFileOutputStream;
 
 private static int RQS_USB_PERMISSION = 0;
 private static final String ACTION_USB_PERMISSION = "com.example.helloadk.usb_permission";
 private PendingIntent PendingIntent_UsbPermission;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  
  textOut = (EditText)findViewById(R.id.textout);
  textIn = (TextView)findViewById(R.id.textin);
  btnSend = (Button)findViewById(R.id.btnsend);
  
  myUsbManager = UsbManager.getInstance(this);
  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);
  
  btnSend.setOnClickListener(new OnClickListener() {
   
   @Override
   public void onClick(View v) {
    
    String textToSend = textOut.getEditableText().toString();
    if(!textToSend.equals("")){
     sendText(textToSend);
    }
   }
  });
  
 }

 @Override
 protected void onResume() {
  super.onResume();
  
  if(myFileInputStream == null || myFileOutputStream == 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{
      //request permission
      Toast.makeText(MainActivity.this, 
        "ask for permission", 
        Toast.LENGTH_LONG).show();
      
      synchronized(myUsbReceiver){
       myUsbManager.requestPermission(usbAccessory, 
         PendingIntent_UsbPermission);
      }
     }
    }
   }
  }
 }
 
 Runnable myRunnable = new Runnable(){

  @Override
  public void run() {
   int numberOfByteRead = 0;
   byte[] buffer = new byte[255];
   
   while(numberOfByteRead >= 0){
    
    try {
     numberOfByteRead = myFileInputStream.read(buffer, 0, buffer.length);
     final StringBuilder stringBuilder = new StringBuilder();
     for(int i=0; i<numberOfByteRead; i++){
      stringBuilder.append((char)buffer[i]);
     }
     
     runOnUiThread(new Runnable(){

      @Override
      public void run() {
       textIn.setText(stringBuilder.toString());
      }});
     
     
    } catch (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
     break;
    }
   }
  }
  
 };
 
 private void OpenUsbAccessory(UsbAccessory acc){
  myParcelFileDescriptor = myUsbManager.openAccessory(acc);
  if(myParcelFileDescriptor != null){
   
   myUsbAccessory = acc;
   FileDescriptor fileDescriptor = myParcelFileDescriptor.getFileDescriptor();
   myFileInputStream = new FileInputStream(fileDescriptor);
   myFileOutputStream = new FileOutputStream(fileDescriptor);
   
   Thread thread = new Thread(myRunnable);
   thread.start();
  }
 }
 
 private void closeUsbAccessory(){
  
  if(myParcelFileDescriptor != null){
   try {
    myParcelFileDescriptor.close();
   } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
  }
  
  myParcelFileDescriptor = null;
  myUsbAccessory = null;
 }

 @Override
 protected void onPause() {
  super.onPause();
  closeUsbAccessory();
 }

 @Override
 protected void onDestroy() {
  super.onDestroy();
  unregisterReceiver(myUsbReceiver);
  unregisterReceiver(myUsbPermissionReceiver);
 }
 
 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)){
    
    Toast.makeText(MainActivity.this, 
      "onReceive: ACTION_USB_ACCESSORY_DETACHED", 
      Toast.LENGTH_LONG).show();
    
    UsbAccessory usbAccessory = UsbManager.getAccessory(intent);
    
    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 = UsbManager.getAccessory(intent);
     
     if(intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)){
      OpenUsbAccessory(usbAccessory);
      
      Toast.makeText(MainActivity.this, 
        "ACTION_USB_PERMISSION accepted", 
        Toast.LENGTH_LONG).show();
     }else{
      Toast.makeText(MainActivity.this, 
        "ACTION_USB_PERMISSION rejected", 
        Toast.LENGTH_LONG).show();
      finish();
     }
    }
   }
  }
  
 };

 private void sendText(String text){

  byte[] buffer = text.getBytes();

  if(myFileOutputStream != null){
   
   try {
    myFileOutputStream.write(buffer);
   } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   } 
  }
 }

}

Update version="0.2" in /res/xml/myfilter.xml.
<?xml version="1.0" encoding="UTF-8"?>
<resources>
    <usb-accessory
        manufacturer="Arduino-er"
        model="HelloADK"
        version="0.2"/>
</resources>


AndroidManifest.xml and the layout file keep no change as in the post "Hello World ADK: Android code".


Modify the code in Arduino side to update versionNumber and download url.
#include "variant.h"
#include <stdio.h>
#include <adk.h>


// Accessory descriptor. It's how Arduino identifies itself to Android.
char applicationName[] = "HelloADK"; // 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.2";
char serialNumber[] = "1";
char url[] = "https://sites.google.com/site/arduinosite/exercise/helloadk/HelloADK_0.2.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;

void setup() {
    Serial.begin(9600);
    cpu_irq_enable();
  
    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() {
  
    char helloworld[] = "Hello World!\r\n";
  
    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);
    }
    
}


Next:
- Improved Hello World ADK


Tuesday, March 12, 2013

Arduino GSM Shield



Arduino GSM Shield - Trailer

The Arduino GSM Shield allows an Arduino board to connect to the internet, make/receive voice calls and send/receive SMS messages.

Continue on:
http://arduino.cc/blog/2013/03/11/dive-into-the-new-arduino-gsm-shield/


FREE download: Raspberry Pi Educational Manual

A Creative Commons licensed teaching manual for the Raspberry Pi, made by a team of UK teachers from Computing at School (CAS), with recognition and encouragement from the Raspberry Pi Foundation is now available at the Pi Store (which you’ll find on your Raspberry Pi’s desktop). If you’re not a Pi owner, you can download here.

Raspberry Pi Educational Manual
Raspberry Pi Educational Manual


Details: http://www.raspberrypi.org/archives/2965

Monday, March 11, 2013

Hello World ADK: Android code

Last post demonstrate my Hello World ADK, with sample code in Arduino Due side. Here is the sample code in Android side.

Hello World ADK: Communication between Arduino Due and Android device
Check last post to view demo video and sample code in Arduino Due side



- Modify AndroidManifest.xml to <uses-festure>, <uses-library>, <intent-filter>, and <meta-data>.

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

    <uses-sdk
        android:minSdkVersion="10"
        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.helloadk.MainActivity"
            android:label="@string/app_name" >
            <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>


- Craete /res/xml/myfilter.xml to to define resource of usb-accessory (update version="0.1" to match latest versionNumber in HelloADK Arduino code).

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


Main Java code, MainActivity.java.

/*
 * manufacturer="Arduino-er"
 * model="HelloADK"
 * version="0.1"
 */

package com.example.helloadk;

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

import com.android.future.usb.UsbAccessory;
import com.android.future.usb.UsbManager;

import android.os.Bundle;
import android.os.ParcelFileDescriptor;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {
 
 EditText textOut;
 TextView textIn;
 Button btnSend;
 
 private UsbManager myUsbManager;
 private UsbAccessory myUsbAccessory;
 private ParcelFileDescriptor myParcelFileDescriptor;
 private FileInputStream myFileInputStream;
 private FileOutputStream myFileOutputStream;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  
  textOut = (EditText)findViewById(R.id.textout);
  textIn = (TextView)findViewById(R.id.textin);
  btnSend = (Button)findViewById(R.id.btnsend);
  
  myUsbManager = UsbManager.getInstance(this);
  IntentFilter intentFilter = new IntentFilter();
  intentFilter.addAction(UsbManager.ACTION_USB_ACCESSORY_DETACHED);
  registerReceiver(myUsbReceiver, intentFilter);
  
  btnSend.setOnClickListener(new OnClickListener() {
   
   @Override
   public void onClick(View v) {
    
    String textToSend = textOut.getEditableText().toString();
    if(!textToSend.equals("")){
     sendText(textToSend);
    }
   }
  });
  
 }

 @Override
 protected void onResume() {
  super.onResume();
  
  if(myFileInputStream == null || myFileOutputStream == null){
   
   UsbAccessory[] usbAccessoryList = myUsbManager.getAccessoryList();
   UsbAccessory usbAccessory = null;
   if(usbAccessoryList != null){
    usbAccessory = usbAccessoryList[0];
    OpenUsbAccessory(usbAccessory);
   }
  }
 }
 
 Runnable myRunnable = new Runnable(){

  @Override
  public void run() {
   int numberOfByteRead = 0;
   byte[] buffer = new byte[255];
   
   while(numberOfByteRead >= 0){
    
    try {
     numberOfByteRead = myFileInputStream.read(buffer, 0, buffer.length);
     final StringBuilder stringBuilder = new StringBuilder();
     for(int i=0; i<numberOfByteRead; i++){
      stringBuilder.append((char)buffer[i]);
     }
     
     runOnUiThread(new Runnable(){

      @Override
      public void run() {
       textIn.setText(stringBuilder.toString());
      }});
     
     
    } catch (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
     break;
    }
   }
  }
  
 };
 
 private void OpenUsbAccessory(UsbAccessory acc){
  myParcelFileDescriptor = myUsbManager.openAccessory(acc);
  if(myParcelFileDescriptor != null){
   
   myUsbAccessory = acc;
   FileDescriptor fileDescriptor = myParcelFileDescriptor.getFileDescriptor();
   myFileInputStream = new FileInputStream(fileDescriptor);
   myFileOutputStream = new FileOutputStream(fileDescriptor);
   
   Thread thread = new Thread(myRunnable);
   thread.start();
  }
 }
 
 private void closeUsbAccessory(){
  
  if(myParcelFileDescriptor != null){
   try {
    myParcelFileDescriptor.close();
   } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
  }
  
  myParcelFileDescriptor = null;
  myUsbAccessory = null;
 }

 @Override
 protected void onPause() {
  super.onPause();
  closeUsbAccessory();
 }

 @Override
 protected void onDestroy() {
  super.onDestroy();
  unregisterReceiver(myUsbReceiver);
 }
 
 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)){
    
    Toast.makeText(MainActivity.this, "onReceive: ACTION_USB_ACCESSORY_DETACHED", Toast.LENGTH_LONG).show();
    
    UsbAccessory usbAccessory = UsbManager.getAccessory(intent);
    
    if(usbAccessory!=null && usbAccessory.equals(myUsbAccessory)){
     closeUsbAccessory();
    }
   }
  }
 };

 private void sendText(String text){

  byte[] buffer = text.getBytes();

  if(myFileOutputStream != null){
   
   try {
    myFileOutputStream.write(buffer);
   } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   } 
  }
 }

}


<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:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:orientation="vertical"
    tools:context=".MainActivity" >

    <EditText
        android:id="@+id/textout"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"/>
    <Button
        android:id="@+id/btnsend"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Send"/>
    <TextView
        android:id="@+id/textin"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"/>

</LinearLayout>


Please notice that this example have no permission obtained to communicating with the USB device in Java code, but include <intent-filter> of "android.hardware.usb.action.USB_DEVICE_ATTACHED" in AndroidManifest.xml. The result is: When the Android device plus in Arduino Due board, and user click OK to start this App in confirm dialog, it work as expected. If user click Cancel, and then start this app manually, it will be stopped. Permission obtaining feature will be improved in next post, "Request Permission to access USB accessory".



Saturday, March 9, 2013

Hello World ADK: Communication between Arduino Due and Android device

The former post demonstrate half "Pre-Hello World for ADK". It's further implemented to include communication between Arduino Due and Android Device.



  • In Arduino Due side: it monitor any incoming data from accessory, and send it back.
  • In Android side, it will send out the text when Send button clicked. And display the text received from USB.
It implement the function of bi-direction communication between Arduino Due and Android Device.

The code in Arduino side is listed here:
#include "variant.h"
#include <stdio.h>
#include <adk.h>


// Accessory descriptor. It's how Arduino identifies itself to Android.
char applicationName[] = "HelloADK"; // 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/helloadk/HelloADK_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;

void setup() {
    Serial.begin(9600);
    cpu_irq_enable();
  
    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() {
  
    char helloworld[] = "Hello World!\r\n";
  
    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);
    }
    
}

The Android side code will be shown in next post "Hello World ADK: Android code".

Remark: The example tested run on HTC One with Android 4.1.1, but NOT work on Nexus One with Android 2.3.6.

Wednesday, March 6, 2013

LCD Demo: Arduino DUE vs Mega 2560

Arduino DUE and Mega 2560 with CTE 3.2" TFT LCD Module with Font IC Demo

Up: Arduino DUE w/TFT Shield
Down: Mega 2560 w/TFT Shield

Running the same demo code with Coldtears electronics 3.2" TFT LCD Module with font and icon IC

The first part is demo of the displaying text and icons from the module. The module is a 3.2" LCD module with fonts of 10 sizes and some commonly used icon for application development.

The second part is the famous UTFT demo by Henning Karlson. DUE runs at 84Mhz with SPI DMA, mega runs at 16Mhz, As seen due is incredibly faster when loading data from flash and drawing to the LCD

Tuesday, March 5, 2013

Pre-Hello World for ADK

It's a very simple incomplete "Hello World" for ADK, working on Arduino Due with Android Device.



In Arduino Due side, it simple loop to detect if adk isReady(). If adk ready turn on L led, if not turn it off. Also define the URL to download the app if not installed.

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

// Accessory descriptor. It's how Arduino identifies itself to Android.
char applicationName[] = "HelloADK"; // 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.0";
char serialNumber[] = "1";
char url[] = "https://sites.google.com/site/arduinosite/exercise/helloadk/HelloADK_0.0.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;

void setup() {
    Serial.begin(9600);
    cpu_irq_enable();
  
    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);
    }
}

void loop() {
  
    Usb.Task();
    
    if (adk.isReady()){
        digitalWrite(led, HIGH);
    }else{
        digitalWrite(led, LOW);
    }
    
}

In the Android side, it only prepare itself as a usb accessory and declare intent-filter of "android.hardware.usb.action.USB_ACCESSORY_ATTACHED". Such that when a matched Arduino connected, it will be pop-up. That's all it done.

New a Android Application Project, Compiler With Google APIs.

Modify AndroidManifest.xml

- add <uses-festure> of "android.hardware.usb.accessory".
- add <uses-library> of "com.android.future.usb.accessory".
- add <intent-filter> to define register action of "android.hardware.usb.action.USB_ACCESSORY_ATTACHED".
- add <meta-data> link to resource of "@xml/myfilter".

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

    <uses-sdk
        android:minSdkVersion="8"
        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.helloadk.MainActivity"
            android:label="@string/app_name" >
            <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>


Create /res/xml/myfilter.xml to define resource of usb-accessory. Notice that manufacturer of "Arduino-er" match with companyName, model of "HelloADK" match with applicationName, and version of "0.0" match with versionNumber in Arduino side.

<?xml version="1.0" encoding="UTF-8"?>
<resources>
    <usb-accessory
        manufacturer="Arduino-er"
        model="HelloADK"
        version="0.0"/>
</resources>


Next:
- Hello World ADK: Communication between Arduino Due and Android device


Monday, March 4, 2013

Fixed the problem of "No device found on COM1" for /dev/ttyACM0

As mentioned in the post: when run Arduino IDE on Ubuntu as su (sudo ./arduino), the serial port can be recognized as /dev/ttyACM0, but cannot be recognized if run as normal user.

To make it work as normal user:

Enter the command in Terminal:

$sudo usermod -a -G dialout <username>

After you plug in the usb cable, run the command (it need to be run every time plug-in):

$sudo chmod a+rw /dev/ttyACM0

Then, you can run Arduino IDE as normal user.

/dev/ttyACM0 recognized
/dev/ttyACM0 recognized


Sunday, March 3, 2013

Test Code Syntax Highlight on Blogger Dynamic View

Just to test embed Code Syntax Highlight on Blogger Dynamic View. I follow the instruction in the post.

Test Code Syntax Highlight on Blogger Dynamic View
Test Code Syntax Highlight on Blogger Dynamic View


Java Code:
package com.example.hello;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;

public class MainActivity extends Activity {

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
 }

 @Override
 public boolean onCreateOptionsMenu(Menu menu) {
  // Inflate the menu; this adds items to the action bar if it is present.
  getMenuInflater().inflate(R.menu.main, menu);
  return true;
 }

}


xml
<RelativeLayout 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:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

</RelativeLayout>


C, but brush of C/C++ is not working. So I use brush:java instead.
/*

 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);

void setup()
{
 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");
  }
 }
}

View on Firefox for Android Phone
View on Firefox for Android Phone


Downloading the ADK 2012 Source


Google ADK 2012 board

The Android Accessory Development Kit (ADK) for 2012 is the latest reference implementation of an Android Open Accessory device, designed to help Android hardware accessory builders and software developers create accessories for Android. The ADK 2012 is based on the Arduino open source electronics prototyping platform, with some hardware and software extensions that allow it to communicate with Android devices.

A limited number of these kits were produced and distributed at the Google I/O 2012 developer conference. If you did not receive one of these kits, fear not! The specifications and design files for the hardware were also released for use by manufacturers and hobbyists. You should expect to see kits with similar features available for purchase, or you can build one yourself!

Downloading the ADK Source on Ubuntu

The support software and hardware specifications for the ADK 2012 are available from the Android source repository. Follow the instructions below to obtain the source material for the ADK.

Before download the source, you have to install curl, git and repo. Refer here.

Then you can download the ADK 2012 Source, enter the commands in Terminal.

$mkdir android-accessories
$cd android-accessories
$repo init -u https://android.googlesource.com/accessories/manifest
$repo sync

Source: http://developer.android.com/tools/adk/adk2.html

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

Google I/O 2012 - ADK 2.0

Introducing the new APIs and capabilities in ADK 2.0, with demos.



Know more: Accessory Development Kit 2012 Guide

Saturday, March 2, 2013

USB OTG



USB OTG (On-The-Go), often abbreviated USB OTG or just OTG, is a specification that allows USB devices such as digital audio players or mobile phones to act as a host, allowing other USB devices like a USB flash drive, mouse, or keyboard to be attached to them. Unlike conventional USB systems, USB OTG systems can drop the hosting role and act as normal USB devices when attached to another host. This can be used to allow a mobile phone to act as host for a flash drive and read its contents, downloading music for instance, but then act as a flash drive when plugged into a host computer and allow the host to read off the new content.

Read more:


Friday, March 1, 2013

Test code for ADK on Arduino Due

Arduino 1.5 BETA come with a ADK Terminal Test example to 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.

To load the ADK Terminal Test example, select File in Arduino IDE -> Examples -> USBHost -> ADKTerminalTest.

Open ADK Terminal Test
Open ADK Terminal Test

BUT...it not work in my case! The function Serial.begin(9600) have to be called at the beginning of setup(). After then, it work as expected (view the video). From the thread http://arduino.cc/forum/index.php?PHPSESSID=13eedea106bcfa79b016f120f99a8f34&topic=129390.0

ADKTerminalTest
ADKTerminalTest

/*

 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);

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");
  }
 }
}





update@2013-06-17:

Similar Android example with source code found, refer:


Cabling to connect Arduino Due with Android device

In order to connect Arduino Due with Android device to achieve ADK function, a Micro USB OTG Cable is needed, connected to Native USB Port of Arduino Due. Another normal USB cable is used to connect the USB OTG Cable and Android device. In such connection, the Arduino Due act as host, the Android act as accessory.

Connect Arduino Due and Android device with OTG USB Cable
Connect Arduino Due and Android device with OTG USB Cable

ADK running on Arduino Due

After two day of try and test, I finally get the Arduino Due ADK sample sketch Arduino 1.5 BETA work on Arduino Due Board, link with HTC One X.


In coming post, I will explain about:

Related:
- My own Hello World ADK: Communication between Arduino Due and Android device