Thursday, October 15, 2015

BBC micro:bit - a pocket-sized, codeable computer that allows children to get creative with technology.

Android control Arduino Due LED, using ADK (Accessory Development Kit)

I have old posts of "Android code sending command to Arduino Due to turn LED On/Off (Android side)" and "Control Arduino Due LED from Android using ADK (Arduino Due side)" to show a simple control from Android to Arduino Due using ADK (Accessory Development Kit), at 2013. At both Android and Arduino development tools updated, I re-visit the example code again.



Arduino Due Side:

In current Arduino IDE 1.6.5, both Arduino Due and ADK library are not include by default, so you have to:
- Install Arduino Due to Arduino IDE
- Install USBHost library to Arduino IDE

DurAdkLed.ino (same as before)
#include "variant.h"
#include <stdio.h>
#include <adk.h>

// Accessory descriptor. It's how Arduino identifies itself to Android.
char applicationName[] = "HelloADKLED"; // 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/androidadkled/AndroidADKLED_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()){
      
        adk.read(&nbread, RCVSIZE, buf);
        if (nbread > 0){
            adk.write(nbread, buf);
            
            //Convert nbread to String
            String s = "";
            for (uint32_t i = 0; i < nbread; ++i) {
              s += (char)buf[i];
            }
            
            if(s == "LEDON"){
              digitalWrite(led, HIGH);
            }else if(s == "LEDOFF"){
              digitalWrite(led, LOW);
            }
        }
         
    }
     
}


Android Side:

AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.blogspot.android_er.androidadkled" >

    <uses-feature android:name="android.hardware.usb.accessory"/>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme" >
        <activity android:name=".MainActivity" >
            <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>


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

layout/activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<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:padding="16dp"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:autoLink="web"
        android:text="http://android-er.blogspot.com/"
        android:textStyle="bold" />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:autoLink="web"
        android:text="http://arduino-er.blogspot.com/"
        android:textStyle="bold" />

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


AbstractAdkActivity.java
package com.blogspot.android_er.androidadkled;

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;
import android.support.v7.app.AppCompatActivity;

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

public abstract  class AbstractAdkActivity extends AppCompatActivity {

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


MainActivity.java
package com.blogspot.android_er.androidadkled;

import android.os.Bundle;
import android.widget.CompoundButton;
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 CompoundButton.OnCheckedChangeListener(){

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

        ledOff.setOnCheckedChangeListener(new CompoundButton.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);
    }
}



adk.h: No such file or directory and Install USBHost library to Arduino IDE


adk.h (Accessory Development Kit) is part of USBHost library. In current Arduino IDE 1.6.5, it's not included by default.

To install USBHost:
> Sketch > Include Library > Manage Libraries
> Search to install USBHost.



Wednesday, October 14, 2015

No Arduino Due in Arduino Software


In current Arduino Software (IDE) 1.6.5, Arduino Due is not in default Board list. To install Arduino Due:
> Tools > Board > Boards Manager
> Select to install the item for Arduino Due


Monday, October 5, 2015

Arduino Uno + RFID-RC522, MFRC522 library example DumpInfo




This post show how Arduino Uno + RFID-RC522 (RFID reader) to dump info of RFID key and RFID card, using Arduino RFID Library for MFRC522.

Arduino library for MFRC522 and other RFID RC522 based modules (https://github.com/miguelbalboa/rfid) read and write different types of Radio-Frequency IDentification (RFID) cards on your Arduino using a RC522 based reader connected via the Serial Peripheral Interface (SPI) interface.

Install MFRC522 library to Arduino IDE:

You can download ZIP file from the library web page, and it to Arduino library, read the video below. After library added, it will be in the folder your_Documents\Arduino\libraries\,


and fritzing parts is in your_Documents\Arduino\libraries\rfid-master\doc\fritzing\.


Connect Arduino Uno and RFID-RF522 module:


In Arduino IDE, Open Example of DumpInfo in MFRC522:



/*
 * ----------------------------------------------------------------------------
 * This is a MFRC522 library example; see https://github.com/miguelbalboa/rfid
 * for further details and other examples.
 * 
 * NOTE: The library file MFRC522.h has a lot of useful info. Please read it.
 * 
 * Released into the public domain.
 * ----------------------------------------------------------------------------
 * Example sketch/program showing how to read data from a PICC (that is: a RFID
 * Tag or Card) using a MFRC522 based RFID Reader on the Arduino SPI interface.
 * 
 * When the Arduino and the MFRC522 module are connected (see the pin layout
 * below), load this sketch into Arduino IDE then verify/compile and upload it.
 * To see the output: use Tools, Serial Monitor of the IDE (hit Ctrl+Shft+M).
 * When you present a PICC (that is: a RFID Tag or Card) at reading distance
 * of the MFRC522 Reader/PCD, the serial output will show the ID/UID, type and
 * any data blocks it can read. Note: you may see "Timeout in communication"
 * messages when removing the PICC from reading distance too early.
 * 
 * If your reader supports it, this sketch/program will read all the PICCs
 * presented (that is: multiple tag reading). So if you stack two or more
 * PICCs on top of each other and present them to the reader, it will first
 * output all details of the first and then the next PICC. Note that this
 * may take some time as all data blocks are dumped, so keep the PICCs at
 * reading distance until complete.
 * 
 * Typical pin layout used:
 * -----------------------------------------------------------------------------------------
 *             MFRC522      Arduino       Arduino   Arduino    Arduino          Arduino
 *             Reader/PCD   Uno           Mega      Nano v3    Leonardo/Micro   Pro Micro
 * Signal      Pin          Pin           Pin       Pin        Pin              Pin
 * -----------------------------------------------------------------------------------------
 * RST/Reset   RST          9             5         D9         RESET/ICSP-5     RST
 * SPI SS      SDA(SS)      10            53        D10        10               10
 * SPI MOSI    MOSI         11 / ICSP-4   51        D11        ICSP-4           16
 * SPI MISO    MISO         12 / ICSP-1   50        D12        ICSP-1           14
 * SPI SCK     SCK          13 / ICSP-3   52        D13        ICSP-3           15
 */

#include <SPI.h>
#include <MFRC522.h>

#define RST_PIN     9       // 
#define SS_PIN      10      //

MFRC522 mfrc522(SS_PIN, RST_PIN);   // Create MFRC522 instance

void setup() {
    Serial.begin(9600);     // Initialize serial communications with the PC
    while (!Serial);        // Do nothing if no serial port is opened (added for Arduinos based on ATMEGA32U4)
    SPI.begin();            // Init SPI bus
    mfrc522.PCD_Init();     // Init MFRC522
    ShowReaderDetails();    // Show details of PCD - MFRC522 Card Reader details
    Serial.println(F("Scan PICC to see UID, type, and data blocks..."));
}

void loop() {
    // Look for new cards
    if ( ! mfrc522.PICC_IsNewCardPresent()) {
        return;
    }

    // Select one of the cards
    if ( ! mfrc522.PICC_ReadCardSerial()) {
        return;
    }

    // Dump debug info about the card; PICC_HaltA() is automatically called
    mfrc522.PICC_DumpToSerial(&(mfrc522.uid));
}

void ShowReaderDetails() {
    // Get the MFRC522 software version
    byte v = mfrc522.PCD_ReadRegister(mfrc522.VersionReg);
    Serial.print(F("MFRC522 Software Version: 0x"));
    Serial.print(v, HEX);
    if (v == 0x91)
        Serial.print(F(" = v1.0"));
    else if (v == 0x92)
        Serial.print(F(" = v2.0"));
    else
        Serial.print(F(" (unknown)"));
    Serial.println("");
    // When 0x00 or 0xFF is returned, communication probably failed
    if ((v == 0x00) || (v == 0xFF)) {
        Serial.println(F("WARNING: Communication failure, is the MFRC522 properly connected?"));
    }
}



- Similarly example run on Android: Android NFC: readBlock() for MifareClassic, to dump data in RFID tag
Step-by-step to make MFRC522-python work on Raspberry Pi 2/raspbian Jessie, read RFID tags using RFID Reader, RFID-RC522.
Raspberry Pi 2 + MFRC522-python - Dump RFID Tag data using mxgxw/MFRC522-python

Thursday, October 1, 2015

Install Arduino driver on Windows 10


Due to any reason, you cannot install the Arduino driver on Windows, you can try to update the driver manually in your Device Manager.
  • Plug in your board and wait for Windows to begin it's driver installation process. After a few moments, the process will fail, despite its best efforts
  • Click on the Start Menu, and open up the Control Panel.
  • While in the Control Panel, navigate to System and Security. Next, click on System. Once the System window is up, open the Device Manager.
  • Look under Ports (COM & LPT). You should see an open port named "Arduino UNO (COMxx)". If there is no COM & LPT section, look under "Other Devices" for "Unknown Device".
  • Right click on the "Arduino UNO (COmxx)" port and choose the "Update Driver Software" option.
  • Next, choose the "Browse my computer for Driver software" option.
  • Finally, navigate to and select the driver file named "arduino.inf", located in the "Drivers" folder of the Arduino Software download (not the "FTDI USB Drivers" sub-directory). If you are using an old version of the IDE (1.0.3 or older), choose the Uno driver file named "Arduino UNO.inf"
  • Windows will finish up the driver installation from there.

reference: Getting Started with Arduino on Windows - Install the drivers