Android Tutorial Arduino ADK Programming

Introduction

This tutorial deals with connecting the Arduino to your PC and ensuring that we can run programs on it. It includes a brief description of the programming language for the Arduino for those who have never used the C or C++ languages.


Connecting the Arduino

If you have been browsing the Arduino site at Arduino - HomePage you may have come across a section titled “Driver & Setup” at the bottom of the description page of the Arduino ADK Arduino - ArduinoBoardADK. Do not use the link given there to download the .inf file. The latest version of the Arduino IDE includes a new all-in-one driver (with security signature for Windows 8) which is located in the “drivers” folder of the IDE installation.

To connect the Arduino and install the necessary drivers you will need to have installed the IDE. The IDE communicates with the Arduino using a COM port which is implemented by a Serial to USB chip on the Arduino and a suitable driver on the PC. Some other Arduino boards use an FTDI chip which Windows 7 and 8 may well recognise but the Arduino ADK uses a specially programmed ATmega8U2 controller. This will not be recognised by Windows and needs the appropriate .inf file

The Arduino can power itself from the USB port of the PC to which it is connected so for this tutorial it will not need an external power supply. This may not be the case when it is connected to both a PC and an Android device and will definitely be the case if it is only connected to an Android device. Power issues are covered in more detail in the next tutorial.

To install the driver connect the Arduino to the PC with a standard A-B USB cable and wait for Windows to begin it's driver installation process. Skip finding a driver from Windows Update and after a few moments, the process will fail.

Click on the Start Menu, and open up the Control Panel.
While in the Control Panel 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)"
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 "drivers" folder of the Arduino Software download (not the "FTDI USB Drivers" sub-directory).
Windows will finish up the driver installation from there.


Running the first program

Start the IDE and select the COM port using Tools -> Serial Port. Unless you have other serial hardware connected to your PC you will probably only have a choice of one which should be the one to which the Arduino is connected. If more than one is present and you don’t know which one to select, make a note of which ports are available in the list then unplug the Arduino from the USB. When you check the Serial Port list again, you will see which one has disappeared. That is your serial port, and it should reappear once you plug it in again.

Open the “01.Basics\Blink” sketch by one of the ways described in the last tutorial. Press the Upload (second) button on the toolbar and hey presto! The program should be compiled and downloaded to the Arduino which after a short delay should now be sitting blinking its little LED at you. The console window will confirm your success.

ideok.png


If you get a cryptic message in red in the console window (as I did!)

avrdude: ser_send(): write error: sorry no info avail

ideerror.png


then you don’t have to spend hours on line trying to find out what’s wrong (as I did). It seems that the Arduino USB controller doesn’t like some USB hubs so make sure you plug it into a USB port on the case of the computer and not into a hub. Although I have seen this proviso before for other products, in practice they have always worked through my hubs. This is the first peripheral that I have found that won’t work through a hub!

You can explore the samples provided in the IDE to get a flavour of programming the Arduino. If you are using the IDE Serial Monitor note that the baud rate setting at the bottom right of the monitor must match the value used for Serial.begin in the Arduino program or you will see nothing or garbage. I would suggest always using 115200 baud for the fastest possible transfers.

baudrate.png


Also note that the Arduino board will reset (rerun your sketch from the beginning) when you open the serial monitor.


Programming basics

Arduino is programmed using a language similar to C++ with some slight simplifications and modifications. If you are familiar with C, C++, or even Java or C# then Arduino program source code will not look unfamiliar. However if you are only familiar with Basic type languages then some Arduino code may look terrifyingly strange. A somewhat simplified explanation follows and there are of course further resources available courtesy of a certain well-known search engine. You can explore the language on the Arduino - HomePage website. Look under “Reference” to begin with. There is a local copy of this in the “reference” folder in the Arduino IDE installation folder which can be opened from the IDE by Help -> Reference.

By convention an Arduino program, which is called a “sketch”, is made of four sections organised consecutively as follows


Program description

B4X:
/*
  Blink
  Turns on an LED on for one second, then off for one second, repeatedly. 
  This example code is in the public domain.
 */
This is a block comment that provides a description of the program. Conventionally it is located at the start of the source code. Strictly is not necessary but it is good practice to include it to help document the sketch.


#includes

B4X:
#include <alloc.h>
#include <util/atomic.h>

.h files are associated with libraries and are used in a similar way to .xml files in Basic4android. The compiler reads the .h files so that it knows what the contents of the similarly named pre-compiled library are so that it can emit the correct code to link the compiled program with the corresponding library.

Programs are automatically linked with the AVR Libc library AVR Libc which is included in the IDE. Look in the “Library Reference” link on that web page for the other include files that are provided with AVR Libc. The .h files for Libc are located in “hardware\tools\avr\avr\include” in the Arduino IDE installation folder though you don’t need to know this as the compiler knows where to look.

Programs automatically include “Arduino.h” which is located in “hardware\arduino\cores\arduino” and this in turn already includes several of the AVR Libc header files: math.h”, “stdlib.h” and “string.h”. The other modules documented in the Libc “Library Reference” are available but will need their .h files specifically included if their functionality is to be available.


Declarations

Entries here, outside of any functions are like Sub Globals in a Basic4android program. Any definitions, variables or class instances declared here are available to any of the functions in the program just like Global variables in Basic4android.

Variables have types, just like in Basic4android but though similarly named have different sizes.

boolean stores one of two (10byte) values, true or false.
byte stores an 8-bit (1-byte) unsigned number, unlike Basic4android, from 0 to 255
char stores an 8-bit (1-byte) signed number, like Basic4android Byte , from -128 to 127
unsigned char stores an 8-bit (1-byte) unsigned number from 0 to 255. Same as a byte
word stores a 16-bit (2-byte) unsigned number, from 0 to 65535. Same as an unsigned int
int stores a 16-bit (2-byte) value from -32,768 to 32,767
unsigned int stores a 16-bit (2-byte) value from 0 to 65,535
short stores a 16-bit (2-byte) value from -32,768 to 32,767. Same as an int
long stores a 32 bit (4 bytes) value from -2,147,483,648 to 2,147,483,647
unsigned long stores a 32 bit (4 bytes) value from 0 to 4,294,967
float stores a 32 bit (4 bytes) as a 6-7 precision floating point value
double is the same as a float for the 8-bit Arduinos like this Mega ADK

String representing a character array. See the String handling section below.


B4X:
float float1, floa2t, float3; // define three float variables like: Dim float1, float2, float3 As Float
int  ints[10]; // define an array of 10 ints like: Dim ints(10) As Int
int someints[] = { 1, 2, 3 }; // declare an initialised array of three ints like: Array As Int(1, 2, 3)
int led = 13; // declare an int variable initialised with the value 13: Dim led As Int = 13
There is another sort of definition that uses “#define” to define textual substitutions made in the source code before it is compiled. By convention these definitions are usually in upper case. Note that whereas most program statements are terminated with a semi-colon #define and #include are not.

B4X:
#define FRED  3; // substitutes "3" for "FRED" wherever "FRED" is found in the source code.

There is also an alternate form of #define that may be encountered that defines macro substitutions but that is not discussed here and a further form, mentioned below, that defines compilation constants.


Function definitions

Functions are very similar to Subs in Basic4android but are defined somewhat differently

B4X:
int Add(int a, int b)
{
   return a + b;
}

is the same as the Basic4android

B4X:
Sub Add(a As Int, b As int) As Int
   Return a + b
End sub


A function that returns nothing must be declared as “void”

B4X:
void Nothing(float aNumber)
{
   // do something useful but don’t return anything
}
You can place variable declarations inside functions and, just like in Basic4android, these variables are local to that function and are not visible outside it.


Special functions

Two special functions are always found in a sketch

B4X:
// the setup routine runs once when you press reset or otherwise start the program.
void setup()
{                
     // initialize everything here
}

B4X:
// the loop routine runs over and over again forever once the setup function has completed
void loop()
{
   // do the repetitive stuff here over and over again
}


String handling

I thought this important enough to dedicate a section to it. Strings are very important in Basic4android and very easy and natural to use, as they also are in Java and C#. Arduino on the other hand uses C style zero terminated strings which are terminated with a null character (ASCII code 0). This allows functions (like Serial.print()) to tell where the end of a string is. Otherwise, they would continue reading subsequent bytes of memory that aren't actually part of the string.

Traditionally in C you would char* (pointer to a char) to handle strings treating them as arrays of characters.
B4X:
  char myString1[] = "This is the first line";
or equivalently
  char* myString2 = "This is the first line";

In fact all the traditional C style string handling functions like strcmp and strcat etc. are available but there is a String object available which implements many of the methods familiar in Basic4android and is probably more convenient for those not accustomed to traditional C style string handling.

B4X:
 String myString3 = "This is the first line";

Apparently the String class in Arduino can be subject to memory problems as the dynamic memory allocation used by the String class leads to a lot of memory fragmentation. To overcome these objections there is an undocumented member of the String object that can reserve additional memory for the String and so help overcome these problems. See Issue 449 - arduino - String.reserve(numBytes) for an explanation. String.reserve(size) returns an unsigned char value of 1 (true) if the String buffer was already large enough or if it was successfully enlarged and 0 (false) otherwise.


Debugging

The Arduino IDE doesn’t have a debugger that can step and break an executing program like Basic4android can. However the IDE does have a Serial Monitor that you can send debugging information to in the same way that you can send information to the log in Basic4android using the Log(something) keyword. After downloading the program to the Arduino do Tools -> Serial Monitor to open it and then have your program send debug information to it using the Serial object. Your program can also receive information from the Serial Monitor so you can implement your own interactive debugging code when you need to.

B4X:
int analogValue = 0;    // variable to hold the analog value

void setup()
{
   // open the serial port at 115200 bps:
   Serial.begin(115200);
}

void loop()
{
   // read the analog input on pin 0:
   analogValue = analogRead(0);

   // print it out
   Serial.println(analogValue);       // print as an ASCII-encoded decimal
   // delay 100 milliseconds before the next reading:
   delay(100);
}

A useful form of the #define directive can be used to effectively “comment out” logging statements but still keep them in the code

If you put this in the declarations and comment it in or out as required
B4X:
#define DEBUG

you can put this anywhere in your code where it will only be executed when DEBUG is defined

B4X:
#ifdef DEBUG
   Serial.println("some debugging info");       
#endif

The next tutorial

In the next tutorial we going to connect our Arduino to our Android device and try to get the two to talk to each other! We will have both the Basic4android and Arduino IDEs running side by side on our PC with the Arduino logging messages to the Serial Monitor over USB and the Android logging messages via B4A Bridge to its IDE and the program running on the Arduino and the Android device talking to each other and swapping messages.


Tutorials

In addition to this tutorial there are other tutorials. They are:


1. Introduction to the Arduino Mega ADK and Android Accessories. Introduction

2. Installing the Arduino IDE and compiling your first program. Installation

3. This one!

4. Connecting the Arduino Mega ADK to your Android device and writing both an Arduino and a Basic4android program to communicate with each other. Consummation

5. Some commentary on the two programs in tutorial 4. Coda
 
Last edited:

warwound

Expert
Licensed User
Longtime User
Looking forward to your tutorial #4 here.

I got a Mega ADK a few weeks back and so far all the online turorials i've found have bean useless.

Martin.
 

Kim Rowden

Member
Licensed User
Longtime User
agraham, thank you, very helpful...

One question... you say that #define and #include are not terminated by a semi-colon - but your #define example is shown as
#define FRED 3;

- ie WITH a semi-colon... ?
Thanks,
-Kim
 

Beja

Expert
Licensed User
Longtime User
Thanks agraham, undoubtedly great endeavor...

I wish I know something about Arduino itself, before learning how to program it.. there are a lot of talk about it, but few describes it. Is it a general purpose mController? then there are hundreds of conrollers out there.. smaller in size, bigger in memory and processing power and much cheaper.
furthermore, they can easily be programmed by a variant of Basic. But since I have little idea about the board then I hope someone sheds light and
explains the special thing in it that puts it apart from the crowd.
 

daniedb

Active Member
Licensed User
Longtime User
Hi Agraham
Worked through you excellent tutorials, but for some reason nothing work..
What TX/RX do you connect the Bluetooth on Mega.
Will it work on the Normal ATmega 2560 or must it be Mega ADK?

Thanks
Danie
 
Top