Monday, April 29, 2013

Eric Schmidt & Jared Cohen - The New Digital Age


The New Digital Age is a book coming April 23, 2013 and is written by Eric Schmidt and Jared Cohen. Eric Schmidt is the Executive Chairman of Google and Jared Cohen is an international security advisor, founder and director of Google Ideas. There are 5 BILLION people coming online in the next 10 years. This amazing book explores the implications this explosion will have in reshaping the future of people, nations and business.




Wednesday, April 24, 2013

ARM Releases Development Tools For Its Embedded Linux Community


The ARM Development Studio 5 (DS-5™) Community Edition is a free professional quality toolchain developed by ARM to accelerate the development of native (C/C++) embedded Linux and Android™ applications. Based on DS-5 Professional Edition, this toolkit offers essential debug and system analysis for you to create robust and highly optimized applications for ARM processor-based devices, without the fuss and inefficiencies usually attached to fragmented open source tools.

April 23, 2013 -- ARM® has extended the scope of the ARM Development Studio 5 (DS-5™) Community Edition (CE) to provide a fully featured, industry standard, and free-to-use software development environment for ARM Embedded Linux applications.

DS-5 CE provides an integrated solution including an Eclipse IDE, GNU cross-compiler, DS-5 Debugger, Streamline™ performance analyzer, online help and software examples. This level of integration enables developers to get up and running with their projects in virtually no time. In addition, DS-5 CE runs on Linux, Windows and Mac OS hosts, making it ideal for microcontroller users moving into the world of Linux.

...

More information on DS-5 CE is available on http://ds.arm.com/ds-5-community-edition/.

DS-5 CE is available now. New users can benefit from all the components in DS-5 CE by doing a standard DS-5 installation and registering an activation code from http://ds.arm.com/ds-5-community-edition/getting-started/ Developers with an existing Eclipse IDE and Linux compiler can install the DS-5 Debugger and Streamline components of DS-5 CE as Eclipse plug-ins from http://ds.arm.com/ds-5-community-edition/getting-started-update-site/.

~ more details: ARM Releases Free Industry Standard Development Tools For Its Embedded Linux Community

Friday, April 19, 2013

FREE eBook: WOSPi - a Weather Observation System for the Raspberry Pi

The ebook, WOSPi - a Weather Observation System for the Raspberry Pi, describes a weather observation system for the Raspberry Pi,utilizing the Davis Vantage Pro2 Plus weather station as observation platform. The weather station is connected directly to the Raspberry Pi without using a Davis Instruments data logger. All necessary details, part numbers and Python/PowerBASIC code samples are provided. The WOSPi software is implemented using the Python programming language.

WOSPi - a Weather Observation System for the Raspberry Pi
WOSPi - a Weather Observation System for the Raspberry Pi


Download HERE.

Monday, April 15, 2013

Android Apps for Arduino: Arduino Examples

Arduino Examples: A lot of Arduino examples with code,diagrams and images for arduino beginners
Arduino Examples
and programmers.

Contains Examples from
- Basics
- Digital
- Analog
- Communication
- Control Structures
- Sensors
- Core Functions
- Digital
- Display
- Strings
- USB (Leonardo, Micro, and Due specific examples)
- Keyboard,Mouse

More will be updated daily or weekly.


Arduino Examples
Arduino Examples

Android Apps for Arduino: Arduino Companion

Arduino Companion
Arduino Companion is an app for designed to help anyone getting into Arduino and electronics. The app contains the full Arduino Reference for offline use, as well as a handy resistor calculator. The Reference contains all of the basic Arduino reference, but it also covers all the included classes for controlling Ethernet, Servos, Serial Communication, LCD Displays, SD cards, Keyboard and Mouse (Leonardo) and more.

Arduino Companion
Arduino Companion


Friday, April 12, 2013

UDOO = 4 Raspberry PI + Arduino DUE

UDOO is a mini PC that could run either Android or Linux, with an Arduino-compatible board embedded.

UDOO = 4 Raspberry PI + Arduino DUE
UDOO = 4 Raspberry PI + Arduino DUE

UDOO is a powerful prototyping board for software development and design, it's easy to use and with a few steps you can start using it and creating your projects with minimum knowledge.

UDOO merges different computing worlds in one; each world has its strengths and weaknesses, and all of them are useful today in education as well as Do-It-Yourself (DIY) and rapid prototyping endeavours.

UDOO is an open hardware, low-cost computer equipped with an ARM i.MX6 Freescale processor for Android and Linux, alongside Arduino DUE's ARM SAM3X, both CPU integrated on the same board!

UDOO's size is 4.33 inch x 3.35 inch (11 cm x 8.5 cm) and it has low power consumption.

Support us on Kickstarter: http://kck.st/XBthCV


Wednesday, April 10, 2013

Implement Timer Interrupt for Arduino Due

The code implement Timer Interrupt for Arduino Due, to toggle LED every second and send the duration in millisecond to PC via Serial port.

int led = 13;

volatile boolean ledon;
volatile unsigned long lasttime;
volatile unsigned long now;

int FREQ_1Hz = 1;

void TC3_Handler(){
    TC_GetStatus(TC1, 0);
    
    now = millis();
    
    digitalWrite(led, ledon = !ledon);
    
    Serial.println(now - lasttime);
    lasttime = now;
    
}

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(9600);
    startTimer(TC1, 0, TC3_IRQn, FREQ_1Hz);
    lasttime = 0;
}

void loop() {

}

Implement Timer Interrupt for Arduino Due
Implement Timer Interrupt for Arduino Due


Saturday, April 6, 2013

Raspberry Pi Home Automation with Arduino

Raspberry Pi Home Automation with Arduino
Raspberry Pi Home Automation with Arduino

Raspberry Pi Home Automation with Arduino

Automate your home with a set of exciting projects for the Raspberry Pi!
Overview
  • Learn how to dynamically adjust your living environment with detailed step-by-step examples.
  • Discover how you can utilize the combined power of the Raspberry Pi and Arduino for your own projects.
  • Revolutionize the way you interact with your home on a daily basis.
In Detail
Low-cost and high-performing, with a massively diverse range of uses and applications, the Raspberry Pi is set to revolutionize the way we think about computing and programming. By combining the Raspberry Pi with an Arduino board you'll be able to revolutionize the way you interact with your home and become part of a rapidly growing group of hobbyists and enthusiasts.
This essential reference will guide you through a series of exciting projects that will allow you to automate your very own home. With easy-to-follow, step-by-step examples, diagrams, and explanations you will not only find it incredibly productive but also highly engaging and informative.
Assuming no prior knowledge, our detailed practical examples will guide you through building hardware and software solutions using the Raspberry Pi and Arduino. You will learn how you can use thermistors and relays to keep cool and stay in the shade whilst also utilizing electrical motors and photoresistors. These meticulously designed tutorials will form the basis of automating your entire home and getting you started with dozens of potential projects.
What you will learn from this book
  • Install an operating system for your Raspberry Pi.
  • Set up the Raspberry Pi and Arduino bridge shield.
  • Learn how to work with electronic components to build small circuits.
  • Develop applications that interact with your circuits.
  • Use thermistors and photoresistors to monitor and control your surroundings.
  • Control your own mains power with a relay shield and even connect a motor to your Raspberry Pi.
Approach
"Raspberry Pi Home Automation with Arduino" is an easy-to-follow yet comprehensive guide for automating your home using the revolutionary ARM GNU/Linux board.
Who this book is written for
Even if you have no prior experience with the Raspberry Pi or home automation you can pick up this book and develop these amazing projects. Full of detailed step-by-step instructions, diagrams, and images this essential guide allows you to revolutionize the way you interact with your home. If you don't know where to start, then this is the perfect book for you.

Friday, April 5, 2013

Read analog input at Arduino Due, display on Android graphically.

This example have same function as previous version in "Write and read analog on Arduino Due from Android using ADK" and "Android code to write and read analog on Arduino Due with ADK"; with a custom view to display the Analog input graphically. The video show how it work, with DAC1 pin and A0 pin connected together, such that the analog out loop back to analog input.



The main difference is in Android side.

Create a new class MyGraphView.java extends View, it is our custom View to display the input graphically.
package com.example.androidadkadc;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.util.AttributeSet;
import android.view.View;

public class MyGraphView extends View {
 
 final static int MAX_ITEM = 100;
 final static int MAX_VAL = 0x0FFF;
 final static int VIEW_WIDTH = 500; //Have to match with width of the View
 final static int VIEW_HEIGHT = 500; //Have to match with height of the View
 final static float X_DIV = (float)VIEW_WIDTH/MAX_ITEM;
 final static float Y_DIV = (float)VIEW_HEIGHT/MAX_VAL;
 
 Paint paintBackground;
 Paint paintGraph;
 Context myContext;
  
 class Item{
  int x;
  int y;
   
  Item(int nx, int ny){
   x = nx;
   y = ny; 
  } 
 }
 
 private List<Item> itemList = new ArrayList<Item>();
 Path pathGraph = new Path();
 
 public MyGraphView(Context context) {
  super(context);
  init(context); 
 }

 public MyGraphView(Context context, AttributeSet attrs) {
  super(context, attrs);
  init(context);
  
 }
 
 public MyGraphView(Context context, AttributeSet attrs, int defStyle) {
  super(context, attrs, defStyle);
  init(context); 
 }
   
 private void init(Context c){
  myContext = c;
    
  paintBackground = new Paint();
  paintBackground.setStyle(Paint.Style.FILL);
  paintBackground.setColor(Color.BLACK);
    
  paintGraph = new Paint();
  paintGraph.setStyle(Paint.Style.STROKE);
  paintGraph.setColor(Color.WHITE);
  paintGraph.setStrokeWidth(3);

 }

 @Override
 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
  int w = MeasureSpec.getSize(widthMeasureSpec);
  int h = MeasureSpec.getSize(heightMeasureSpec);
  setMeasuredDimension(w, h);
 }
 
 @Override
 protected void onDraw(Canvas canvas) {
  
  if(!itemList.isEmpty()){
   
   Item lastItem = itemList.get(itemList.size()-1);
   float invY = getHeight() - (lastItem.y * Y_DIV);
   
   if(itemList.size() == 1){
    pathGraph.reset();
    pathGraph.moveTo(0, invY);
   }else{
    pathGraph.lineTo(lastItem.x * X_DIV, invY);
   }
   canvas.drawPath(pathGraph, paintGraph);
  }
  
 }
 
 void addItem(long v){
  if(itemList.size() >= MAX_ITEM){
   itemList.clear();
  }
  
  itemList.add(new Item(itemList.size(), (int)v));
 }

}


Modify the MainActivity.java. The dummySource() method and MyAsyncTask() are for testing only, to simulate input data when no Arduino board available.

package com.example.androidadkadc;

import java.util.Random;

import android.os.AsyncTask;
import android.os.Bundle;
import android.os.SystemClock;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;

public class MainActivity extends AbstractAdkActivity {
 
 MyGraphView myGraphView;
 SeekBar seekBarBrightness;
 
 Random dummyRandom;

 @Override
 protected void doOnCreate(Bundle savedInstanceState) {
  setContentView(R.layout.activity_main);
  myGraphView = (MyGraphView)findViewById(R.id.myview);
  seekBarBrightness = (SeekBar)findViewById(R.id.seekbarbrightness);
  seekBarBrightness.setOnSeekBarChangeListener(
    new OnSeekBarChangeListener(){

     @Override
     public void onProgressChanged(SeekBar seekBar, 
       int progress, boolean fromUser) {
      WriteByteAdk((byte)(progress & 0xFF));
     }

     @Override
     public void onStartTrackingTouch(SeekBar arg0) {
      // TODO Auto-generated method stub
      
     }

     @Override
     public void onStopTrackingTouch(SeekBar arg0) {
      // TODO Auto-generated method stub
      
     }});
  
  //dummySource(); //for testing without Arduino Due board
 }

 @Override
 protected void doAdkRead_inBackGroundThread(int length, byte[] bfr) {
  //Accept only if 2 byte data received
  if(length == 2){

   final long val = (bfr[0] << 8) + (bfr[1] & 0xFF);

   runOnUiThread(new Runnable(){

    @Override
    public void run() {
     myGraphView.addItem(val);
     myGraphView.postInvalidate();
    }});
   
  }
  
 }
 
 //for testing without Arduino Due board
 private void dummySource(){
  dummyRandom = new Random();
  new MyAsyncTask().execute();
 }
 
 public class MyAsyncTask extends AsyncTask<Void, Void, Void> {

  @Override
  protected Void doInBackground(Void... arg0) {
   while(true){
    byte[] b = new byte[2];
    dummyRandom.nextBytes(b);
    b[0] = (byte)(b[0] & 0x0F);
    doAdkRead_inBackGroundThread(2, b);
    SystemClock.sleep(500);
   }
  }
 }

}


Modify the layout, main_activity.xml to add our custom view <com.example.androidadkadc.MyGraphView>.
<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="@string/hello_world" />
    <com.example.androidadkadc.MyGraphView
        android:id="@+id/myview"
        android:background="@android:color/black"
        android:layout_gravity="center_horizontal"
        android:layout_margin="10px"
        android:layout_width="500px"
        android:layout_height="500px" />
    <SeekBar
        android:id="@+id/seekbarbrightness"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:max="255"
        android:progress="0" />

</LinearLayout>


Modify /res/xml/myfilter.xml to update version.
<?xml version="1.0" encoding="UTF-8"?>
<resources>
    <usb-accessory
        manufacturer="Arduino-er"
        model="ArduinoDueAdkADC"
        version="0.2"/>
</resources>


The AndroidManifest.xml is same as previous version in Android side.

download filesDownload the files.



In Arduino, same as previous version in Arduino side, with update of:
  • char versionNumber[] = "0.2";
  • char url[] = "https://sites.google.com/site/arduinosite/exercise/androidadkadc/AndroidAdkADC_0.2.apk";


Wednesday, April 3, 2013

Android code to write and read analog on Arduino Due with ADK

it's android side coding of the exercise "Write and read analog on Arduino Due from Android using ADK".

Android side to write and read analog on Arduino Due with ADK
Android side to write and read analog on Arduino Due with ADK 


Modify AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.androidadkadc"
    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.androidadkadc.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>


/res/xml/myfilter.xml
<?xml version="1.0" encoding="UTF-8"?>
<resources>
    <usb-accessory
        manufacturer="Arduino-er"
        model="ArduinoDueAdkADC"
        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="@string/hello_world" />
    <TextView
        android:id="@+id/textin"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
    <SeekBar
        android:id="@+id/seekbarbrightness"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:max="255"
        android:progress="0" />

</LinearLayout>


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

package com.example.androidadkadc;

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


package com.example.androidadkadc;

import android.os.Bundle;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.SeekBar.OnSeekBarChangeListener;

public class MainActivity extends AbstractAdkActivity {
 
 TextView textIn;
 SeekBar seekBarBrightness;

 @Override
 protected void doOnCreate(Bundle savedInstanceState) {
  setContentView(R.layout.activity_main);
  textIn = (TextView)findViewById(R.id.textin);
  seekBarBrightness = (SeekBar)findViewById(R.id.seekbarbrightness);
  seekBarBrightness.setOnSeekBarChangeListener(
    new OnSeekBarChangeListener(){

     @Override
     public void onProgressChanged(SeekBar seekBar, 
       int progress, boolean fromUser) {
      WriteByteAdk((byte)(progress & 0xFF));
     }

     @Override
     public void onStartTrackingTouch(SeekBar arg0) {
      // TODO Auto-generated method stub
      
     }

     @Override
     public void onStopTrackingTouch(SeekBar arg0) {
      // TODO Auto-generated method stub
      
     }});
 }

 @Override
 protected void doAdkRead_inBackGroundThread(int length, byte[] bfr) {
  //Accept only if 2 byte data received
  if(length == 2){

   final long val = (bfr[0] << 8) + (bfr[1] & 0xFF);

   runOnUiThread(new Runnable(){

    @Override
    public void run() {
     String s = String.valueOf(val);
     textIn.setText(s);
    }});
   
  }
  
 }

}


download filesDownload the files.

Write and read analog on Arduino Due from Android using ADK

In this example, Android device can write analog output (DAC0/DAC1) and read analog input (A0) on Arduino Due board by using ADK. The video below show how it work, with DAC1 pin and A0 pin connected together, such that the analog out loop back to analog input.


Code in Arduino side:

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

 
// Accessory descriptor. It's how Arduino identifies itself to Android.
char applicationName[] = "ArduinoDueAdkADC"; // 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/androidadkadc/AndroidAdkADC_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);
    pinMode(analogInputA0, INPUT);
    pinMode(analogOutput0, OUTPUT);
    pinMode(analogOutput1, 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()){
      
        adk.read(&nbread, RCVSIZE, buf);
        if (nbread > 0){
            uint8_t dacValue = buf[0];
            analogWrite(analogOutput0, dacValue);  //Write to ADC
            analogWrite(analogOutput1, dacValue);  //Write to ADC
        }
        
        varA0 = analogRead(analogInputA0);

        //Send as 2 bytes
        adkVarA0[1] = varA0 & 0xFF;
        adkVarA0[0] = (varA0 >> 8) & 0x0F;
        adk.write(2, adkVarA0);
        
        delay(500);
    }    
}

Download>>

Android side code to write and read analog on Arduino Due with ADK



Take caution when you work on the IO pins, it's easy to be burnt out! The DAC0 on my board have no function now, because I mis-connected it to GND accidentally.

ARM documentation set for the ARM Cortex-M3 processors


ARM documentation set for the ARM Cortex-M3 processors

The ARM Cortex-M3 processor is a low-power processor that features low gate count, low interrupt latency, and low-cost debug. It is intended for deeply embedded applications that require fast interrupt response, including microcontrollers and automotive and industrial control systems. The ARM Cortex-M3 processor implements the ARMv7-M architecture profile.

Revision: r2p1 (with download links of PDF version):


Java ME Embedded and Raspberry Pi

Getting Started with Oracle Java ME Embedded and Raspberry Pi

Learn with Simon Ritter, Java Technology Evangelist, how Oracle Java ME Embedded and Raspberry Pi Model B can work together to create some interesting types of applications!

Monday, April 1, 2013

Android code sending command to Arduino to change LED brightness

A Byte of data between 0x00 and 0xFF will be sent to Arduino Due board from Android device via ADK interface, In Arduino side call analogWrite() function to change the brightness of the LED.


Modify AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.androidadkanalogled"
    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.androidadkanalogled.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>

/res/xml/myfilter.xml
<?xml version="1.0" encoding="UTF-8"?>
<resources>
    <usb-accessory
        manufacturer="Arduino-er"
        model="DueAdkAnalogLed"
        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="@string/hello_world" />
    <TextView
        android:id="@+id/textin"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
    <SeekBar
        android:id="@+id/seekbarbrightness"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:max="255"
        android:progress="0" />
</LinearLayout>


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

package com.example.androidadkanalogled;

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();
   } 
  }
 }
 
 //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;
   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;
 }
}


MainActivity.java
package com.example.androidadkanalogled;

import android.os.Bundle;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;

public class MainActivity extends AbstractAdkActivity {
 
 TextView textIn;
 SeekBar seekBarBrightness;

 @Override
 protected void doOnCreate(Bundle savedInstanceState) {
  setContentView(R.layout.activity_main);
  textIn = (TextView)findViewById(R.id.textin);
  seekBarBrightness = (SeekBar)findViewById(R.id.seekbarbrightness);
  seekBarBrightness.setOnSeekBarChangeListener(
    new OnSeekBarChangeListener(){

     @Override
     public void onProgressChanged(SeekBar seekBar, 
       int progress, boolean fromUser) {
      WriteByteAdk((byte)(progress & 0xFF));
     }

     @Override
     public void onStartTrackingTouch(SeekBar arg0) {
      // TODO Auto-generated method stub
      
     }

     @Override
     public void onStopTrackingTouch(SeekBar arg0) {
      // TODO Auto-generated method stub
      
     }});
 }

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

}




download filesDownload the files.

Arduino Due + Android + ADK: change LED brightness by calling analogWrite()

In this example, the LED brightness on Arduino Due can be controlled by sliding a SeekBar on Android device. A Byte of data between 0x00 and 0xFF will be sent to Arduino Due board from Android device via ADK interface, In Arduino side, it call analogWrite() function to change the brightness of the LED.


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

 
// Accessory descriptor. It's how Arduino identifies itself to Android.
char applicationName[] = "DueAdkAnalogLed"; // 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/androidadkanalogled/AndroidADKAnalogLED_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() {

    uint8_t buf[RCVSIZE];
    uint32_t nbread = 0;
   
    Usb.Task();
     
    if (adk.isReady()){
      
        adk.read(&nbread, RCVSIZE, buf);
        if (nbread > 0){
          
            uint8_t asciiChar[2];
          
            //Convert received uint8_t to human readable ASCII
            uint8_t lowNibble = buf[0] & 0x0F;
            uint8_t highNibble = (buf[0] & 0xF0) >> 4;
            
            if(lowNibble <= 0x09){
                asciiChar[1] = '0' + lowNibble;
            }else{
                asciiChar[1] = 'A' + lowNibble - 0x0A;
            }
            
            if(highNibble <= 0x09){
                asciiChar[0] = '0' + highNibble;
            }else{
                asciiChar[0] = 'A' + highNibble - 0x0A;
            }
            
            adk.write(2, asciiChar);
            
            uint8_t ledBrightness = buf[0];
            analogWrite(led, ledBrightness);
        }
         
    }
     
}

Download>>



Writes an analog value (PWM wave) to a pin. Can be used to light a LED at varying brightnesses or drive a motor at various speeds. After a call to analogWrite(), the pin will generate a steady square wave of the specified duty cycle until the next call to analogWrite() (or a call to digitalRead() or digitalWrite() on the same pin). The frequency of the PWM signal is approximately 490 Hz.

On most Arduino boards (those with the ATmega168 or ATmega328), this function works on pins 3, 5, 6, 9, 10, and 11. On the Arduino Mega, it works on pins 2 through 13. Older Arduino boards with an ATmega8 only support analogWrite() on pins 9, 10, and 11.

The Arduino Due supports analogWrite() on pins 2 through 13, plus pins DAC0 and DAC1. Unlike the PWM pins, DAC0 and DAC1 are Digital to Analog converters, and act as true analog outputs.

You do not need to call pinMode() to set the pin as an output before calling analogWrite().

The analogWrite function has nothing to do with the analog pins or the analogRead function.

source: http://arduino.cc/en/Reference/AnalogWrite

Android side code refer the post "Android code sending command to Arduino to change LED brightness".