Arduino Mega ADK Project and Basic4Android

CanguroCode

Active Member
Licensed User
Longtime User
Introduction
The search for communication between an embedded system and the outside world is always exciting. Being able to control the environment from the palm has been an interesting topic. In this paper is to explain simply and shortly as Android System communicate with a microcontroller mounted on a card called Arduino.
The project we are working together with a friend electronics expert (Julio-is reserved and not yet part of the forums-) and I (no expert but a little good at programming) and headed to operate this pileup . We share it with you.

Target
  • Send control signals to the digital outputs from Android to Arduino board. This may serve to: turn on or off a led up to a motor on or off (with the appropriate electronic settlement, which will not be addressed in this draft).
  • Wanted monitor temperature and humidity data that are provided by sensors. That is, send data from Arduino to Android.
  • Controlling a servomotor from Android.

Material

Software

Android Code
The code used until now for Android in Basic4Android is:
B4X:
Sub Process_Globals
    Dim Accesorio As UsbAccessory
    Dim Manejador As UsbManager
   Dim AStreams As AsyncStreams
End Sub

Sub Globals
   Dim Button1 As Button
   Dim Label1 As Label
End Sub

Sub Activity_Create(FirstTime As Boolean)
    Activity.LoadLayout("Escritorio")
      If FirstTime = True Then
           EncuentraAccesorio
       End If
End Sub

Sub Activity_Resume
    EncuentraAccesorio
End Sub

Sub Activity_Pause (UserClosed As Boolean)
End Sub

Sub EncuentraAccesorio
   Manejador.Initialize
    Dim ListaAccesorios () As UsbAccessory
   ListaAccesorios = Manejador.GetAccessories

      For i = 0 To ListaAccesorios.Length - 1
                 If ListaAccesorios(i).Description = "Prueba" Then
                    Accesorio = ListaAccesorios(i)
               Log(Accesorio.Description)
               Log(Accesorio.Manufacturer)
               Log(Accesorio.Serial)
             End If
        Next
            
      If Accesorio <> Null Then
         Dim Permiso As Boolean
         Dim r As Reflector
         r.Target = Accesorio
         Permiso= Manejador.HasAccessoryPermission(r.GetField("accessory"))

         If Permiso==True Then
            Manejador.OpenAccessory(Accesorio)
            Log (AStreams.IsInitialized)
            If AStreams.IsInitialized==False Then
               Try
                  AStreams.Initialize(Accesorio.InputStream,Accesorio.OutputStream,"AStreams")
               Catch
                  Log("No se inicializo AncyStreams")
               End Try
         End If
         Else 
            Manejador.RequestAccessoryPermission(r.GetField("accessory"))
            Permiso= Manejador.HasAccessoryPermission(r.GetField("accessory"))
            
               If Permiso Then
                  Manejador.OpenAccessory(Accesorio)
               End If
            
               If AStreams.IsInitialized==False Then
                  Try            
                     'AStreams.Initialize(Accesorio.InputStream,Accesorio.OutputStream,"AStreams")
                     AStreams.InitializePrefix(Accesorio.InputStream,False,Accesorio.OutputStream , "AStreams")
                  Catch
                     Log("No se inicializo AncyStreams")
                  End Try
               End If
         End If
      Else
         Log("No hay accesorio reconocido")
      End If
   
End Sub

'Funcion especial de los AStreams////////////////////////////////////
Sub AStreams_NewData (Buffer() As Byte)
    Dim msg As String
    msg = BytesToString(Buffer, 0, Buffer.Length, "UTF8")
    Label1.Text=msg
   'ToastMessageShow(msg, False)
    Log(msg)
End Sub

Sub AStreams_Error
    ToastMessageShow(LastException.Message, True)
End Sub
'///////////////////////////////////////////////////////////////////


Sub Button1_Click
   If AStreams.IsInitialized=False Then Return
   Dim Cadena As String
   Cadena="Hola"
   AStreams.Write(Cadena.GetBytes("UTF8"))
End Sub
The initial idea of ​​the code I got from the post created by the user Diego:
http://www.b4x.com/forum/basic4android-updates-questions/18292-arduino-uno-usb-host.html#post105928


Arduino Code
Before compiling the code the libraries should be placed in the Libraries folder Arduino Compiler. But the code will not compile and mark errors. The code used until now for Arduino:

B4X:
#include <Max3421e.h>
#include <Usb.h>
#include <AndroidAccessory.h>

#define ARRAY_SIZE 25

AndroidAccessory acc("Google, Inc.",
           "Prueba",
           "Prueba",
           "1.0",
           "http://www.android.com",
           "0000000012345678");

char hello[ARRAY_SIZE] = {'H','o','l','a',' ',
'M','u','n','d','o',' ', 'd', 'e', 's', 'd', 'e ',' ',
'A', 'r', 'd', 'u', 'i', 'n', 'o', '!'};

byte rcvmsg[255];
byte sntmsg[ARRAY_SIZE];

void setup() 
{
Serial.begin(115200);
acc.powerOn();
}

void loop() {
if (acc.isConnected()) {
 //read the sent text message into the byte array
 int len = acc.read(rcvmsg, sizeof(rcvmsg), 1);
  if (len > 0) 
  {
    
       for(int x = 0; x < 4; x++) 
       {
       Serial.print((char)rcvmsg[x]);
       delay(250);
       }
       Serial.println();
       delay(250);
     
    
   }

 for(int x = 0; x < ARRAY_SIZE; x++) 
  {
  sntmsg[x] = hello[x];
  }
 acc.write(sntmsg, ARRAY_SIZE);
 delay(250);
 }//Fin del if que verifica si el accesorio esta conectado
}


Conclusions
To date September 13 has managed to send a string ("Hola") to Arduino which can be viewed via the Serial monitor. Also been sent from Arduino to Android the same chain and can be seen in a Label from Android. Thanks to the data type AnsyncString sending and receiving of data can be simultaneously (or so it appears to the end user) and the system will not lock -Correct me if I'm wrong-.

Other comments and Earrings
This code is not yet finalized and is in development, so it is not optimized, maybe you can make a better way, for now it works this way. Lack implement appropriate communication protocol (I'm thinking of using the same Google uses in its Demokit). As I said, I will upload progress to the page.

Acknowledgements

Erel. For providing the correction to obtain permits for accessory
Jerel.For providing the correction in the code to write and send data

Brief bibliography and links
Connect via USB Sockets

AsyncStreams Tutorial

USB Library information

Sorry for the spelling, I'm from mexico and I have little knowledge of the English language, If you have any mistake or any comments, please let me know, this will be welcome.

Regards.
 
Last edited:

bluedude

Well-Known Member
Licensed User
Longtime User
Sending values

Hi,

The ADK works with a Grove shield attached and sensor but not sure how to wrap the sensor data in the array

char hello[ARRAY_SIZE] = {'H','o','l','a',' ',
'M','u','n','d','o',' ', 'd', 'e', 's', 'd', 'e ',' ',
'A', 'r', 'd', 'u', 'i', 'n', 'o', '!'};

I'm trying: char hello[ARRAY_SIZE] = sensorValue

but nothing gets displayed in Android.

Why the weird formatting like {'H'} and not just "hello".

Cheers,
 
Upvote 0

PaulR

Active Member
Licensed User
Longtime User
It looks like he's avoiding having a null terminator at the end of the string for some reason. When you do it like char ar[] = "Hello" or char ar[5] = "Hello", even though "Hello" is 5 characters, to the compiler it looks like 6. So char ar[6] = "Hello" is required if declaring the size.

A more flexible way would be removing #define ARRAY_SIZE 25 and...
B4X:
char hello[] = "Hola Mundo deste Arduino!";

const int ARRAY_SIZE = sizeof(hello)-1;

byte sntmsg[ARRAY_SIZE];

With your problem, I don't know (my newly ordered Arduino is somewhere between here and Hong Kong at the moment) if AndroidAccessory.Write on the Arduino expects an array of the typedef(?) byte or not, but looking at the exampes you can assign at least an int or char to a byte without explicity casting so...
B4X:
byte msg = sensorValue;
acc.write(msg, sizeof(msg));
// or...
byte msg[1] = {sensorValue};
acc.write(msg, sizeof(msg));
.. should work (maybe both).

On the b4a side, nothing will display since the code in the first post formats to UTF-8 and you are sending raw bytes. To display the content of the raw bytes you could change the encoding to US-ASCII. Of course you want the values though so because you know you've sent an int, you can use the ByteConverter library. So in place of...
B4X:
'Funcion especial de los AStreams////////////////////////////////////
Sub AStreams_NewData (Buffer() As Byte)
    Dim msg As String
    msg = BytesToString(Buffer, 0, Buffer.Length, "UTF8")
    Label1.Text=msg
    'ToastMessageShow(msg, False)
    Log(msg)
End Sub
... you...
B4X:
'Funcion especial de los AStreams////////////////////////////////////
Sub AStreams_NewData (Buffer() As Byte)
    Dim b As ByteConverter
    Dim ints As Int()
    ints = b.IntsFromBytes(Buffer)
    Label1.Text=ints(0)
    'ToastMessageShow(msg, False)
    Log(msg)
End Sub

Hope this helps/works... as I say it's untested.
 
Upvote 0

FrankieC

New Member
Licensed User
Longtime User
Hello All,

I'm trying to get the ADK working and have been using the code above along with Astream examples but alas I have still had no luck (lots of red). I have had the ADK working with examples in Eclipse but I believe this would be a better IDE for development and would much prefer to use it.

Anyway what I wanted to ask is would it be possible for someone to post working source code for both the Arduino and B4A that uses the ADK method and does not require rooting and modifying my tablet (Usb serial library recently posted, not very useful if I may share with others who haven't got a clue). Preferably in English as I had fun translating GeneralGervious's code and as I say still had red at the end (maybe I forgot to add some libraries?)

Sorry if this has already been done, I have tried to scour the forum but I think I'm chasing my tail and starting to see double.

Also, bit of a side note but would help with this and it's probably been answered a dozen times, can I rip the Eclipse ADK 2011 source code into A4A? It would solve a lot of problems.

Many thanks for your patients,
Frankie
 
Upvote 0

FrankieC

New Member
Licensed User
Longtime User
I Encountered the same problem as Thuong, 01-11-2013, 07:38 AM. Where in you suggested trying following:

Android fails to open the USB port.
Try the solution proposed here: http://www.b4x.com/forum/additional...03-usb-rs232-adaptor-driver-5.html#post120979

But reading that it suggests rooting and adjusting internal files. Something I would dearly like to avoid considering I can quite happily communicate using programs rendered in Eclipse. I did wonder whether it is just a case of having to ask permission to use the USB? As this currently does not happen and it is a prerequisite of all ADK apps.

Thanks for the speedy reply.
 
Upvote 0
Top