How To Build Custom Android App for your Arduino Project using MIT App Inventor

In this Arduino Tutorial we will learn how to build custom Android applications for controlling Arduino using the MIT App Inventor online application. You can watch the following video or read the written tutorial below.

Overview

For this tutorial we have two examples. The first example is controlling a simple LED and the second one is controlling a Stepper Motor using smartphone. In my previous tutorial we already learned how to make the Bluetooth communication between the Arduino Board and the Smartphone using the HC-05 Bluetooth module and explained the Arduino code needed for the first example.

Arduino Code

Here’s a quick overview of that code. So, via the serial port we receive the incoming data from the smartphone and store it in the ‘state’ variable. If we receive the character ‘0’ which is sent from the smartphone when the ‘LED: OFF’ button is pressed, we will turn the LED off and send back to the smartphone the String “LED: OFF”. On the other hand, if we receive the character ‘1’ we will turn the LED on and send back the String “LED: ON”.

/* Arduino and HC-05 Bluetooth Module Tutorial
 * 
 * by Dejan Nedelkovski, www.HowToMechatronics.com
 * 
 */
 
#define ledPin 7
int state = 0;

void setup() {
 pinMode(ledPin, OUTPUT);
 digitalWrite(ledPin, LOW);
 Serial.begin(38400); // Default communication rate of the Bluetooth module
}

void loop() {
 if(Serial.available() > 0){ // Checks whether data is comming from the serial port
 state = Serial.read(); // Reads the data from the serial port
 }

 if (state == '0') {
 digitalWrite(ledPin, LOW); // Turn LED OFF
 Serial.println("LED: OFF"); // Send back, to the phone, the String "LED: ON"
 state = 0;
 }
 else if (state == '1') {
 digitalWrite(ledPin, HIGH);
 Serial.println("LED: ON");;
 state = 0;
 } 
}Code language: Arduino (arduino)

So now we need to build our custom Android application which will send those characters ‘0’ and ‘1’ when a particular button is pressed, as well as, receive the incoming Strings from the Arduino.

MIT App Inventor

From the MIT App Inventor website we need to log in into the online building application by clicking the “Create apps!” button. In order to log in we need to have a Gmail account. Once we are logged in now we can create our first project. Here’s how the design window looks and now we can start building our application.

MIT App Inventor Design Window

But before do that, we can connect our smartphone to this project so that we can see how the app is taking shape directly on our smartphone in real time. In order to do that first we have to download the MIT AI2 Companion app from the Play Store and install it on our smartphone. Then from the Connect menu from the online editor we will select AI Companion and a barcode will appear which we just need to scan it or insert the code into the smartphone app and the connection between the online editor and the smartphone app will be established.

Mit App Inventor and Smartphone Connection

So now for example, if we insert a button in the screen of the online editor, the button will appear in real time on the smartphone as well. Similar to this, if you don’t want to use your smartphone while building the app, you can install the Android Emulator on your computer and use in the same way. You can find more details how to set up the Emulator on their website.

Building the App – Example 1

Now we are ready to build the first example. We will start with the layout of the program. First we will add some HorizontalArrangements from the layout Palette and set their properties like the height, the width and the alignment to match our program desired look. Then from the UserInterface Palette we will add a ListPicker and attach an image to it. The ListPicker will be used for selecting the Bluetooth device to which our smartphone will connect.

Building the Android App Example 01

Next we will add another HorizontalArrangements in which we will place a Label. This label will indicate whether the smartphone is connected or not to the Bluetooth module and that’s why we will set the initial text of this label to “Not Connected”. The next label will be used for displaying the status of the LED, whether is turned off or on. The initial state will be “LED: OFF”. Next we will add the two buttons, ‘Turn On’ and ‘Turn Off’ for controlling the LED. At this point it is good to rename the components so that we can easier recognize and use them in the Blocks editor later. What’s left now is to add the BluetoothClient which is a Non-visible component as well as a clock which will be used for the real time indication of the connection status.

Blocks Editor

Now in the Blocks editor we are ready to give life to our program. From the left side we got all the blocks and function related to the previously added components.

Android App Blocks Example 01

We will start with the BluetoothList ListPicker. From there first we will add the ‘BeforePicking’ block and attach to it the ‘set Bluetooth Elements’ block. Then from the BluetoothClient blocks we will add the ‘BluetoothClient AddressesAndNames’ block. What this set of blocks will do is set a list of Bluetooth devices which are already paired with our phone so when we will click on the ListPicker “Connect Button” the list of all paired devices will show up.

BeforePicking Block

Next we have to set what will happen after we will pick or select our particular Bluetooth module. From the BluetoothClient block we will add the ‘call BluetoothClient .Connect address’ block and add the block ‘BluetoothList Selection’ to it, which means that our phone will connect to the Bluetooth address that we have previously selected.

AfterPicking Block

Next from the Clock blocks we will add the “.Timer” block. Within this block we will make the real time indication whether the phone is connected or not to the Bluetooth module using the “set Text” block of the label named “Connected”.

Clock Block

Next we need to give life to the two buttons. So when the “TurnOn_Button” will be clicked we will use the Bluetooth client function “Send1ByteNumber” to send a number to the Arduino Bluetooth module. In our case that’s the number 49 which corresponds to the character ‘1’ according to the ASCII table and that will turn on the LED. Right after that we will use the “ReceiveText” BluetoothClient function to receive the incoming String which is send back from the Arduino to the phone. This String is set to the “LED_Status” Label.

Buttons Blocks

The same procedure goes for the “TurnOff_Button” where the sending number should be changed to 48 which corresponds to character ‘0’. What’s left now is to download and install the program on our smartphone. We can do that from the “Build” menu by either saving it to our computer and then transfer to our phone or scan a QR code for online download of the program. Here’s the demonstration of the example.

Here’s a download file of the above MIT App Inventor project:

Stepper Motor Control Example


Now let’s take a look at the second example, controlling a stepper motor. At the top of the screen we have the same components for the Bluetooth connection as the previous example. Next we have a Canvas component which is used for drawing and inserting images. I inserted two transparent images which I previously drew. The first one is an image of a gauge which will be fixed in place and the second one is an image of a pointer which will be rotating. Next we have a Check button for switching between Manual and Auto or continuously running mode and a button for changing the rotation direction. At the button we have a slider for changing the rotation speed of the stepper motor.

Android App Blocks Stepper Motor Control

Here are the blocks and the Arduino code behind this example. So, in the Blocks editor again we have the same blocks for the Bluetooth connection as the previous example.

Stepper Motor Control Example Block 01

Now for rotating the pointer image we use the ImageSprite function “.PointInDirection” which rotates the image from 0° position to the X and Y coordinates where the Canvas has been touched. At the same time we set the rotated ImageSprite heading to the text label above. After that we call custom made procedure, or function which is actually a 10m seconds delay.

Lastly we send the heading value as a Text to the Arduino using the “SendText” Bluetooth function. This value will be accepted by the Arduino and it will rotate the stepper motor accordingly.

Stepper Motor Control Example Block 04

Next is the the CheckBox block. So if the CheckBox is checked we will send the text “Auto” to the Arduino which will activate stepper motor to rotate continuously. While we are in this mode if we press the “Reverse” button, we will send the text “Reverse” to the Arduino which will change the rotation direction of the motor. Also, while we are in this mode, we can change the speed of rotation. If we change the position of the slider, the current value of the slider position will be send to the Arduino which will change the rotation speed of the stepper. If we uncheck the CheckBox we will get back into the manual mode.  Here’s the demonstration of the example.

Stepper Motor Control Example Block 05

Here’s a download file of the above MIT App Inventor project, as well as the two images used in the project:

Here’s the Arduino code of the second example:

/*  Stepper Motor Control via HC-05 Bluetooth Module
 *      
 *  by Dejan Nedelkovski, www.HowToMechatronics.com
 *  
 */

// Defining variables
const int stepPin = 7; 
const int dirPin = 6;
String state = ""; 
int currentHeading=0;
int currentAngle=0;
int lastAngle=0;
int angle=0;
int rotate=0;
int runContinuously=0;
String mode = "Manual";
boolean dirRotation = HIGH;
int rotSpeed = 1500;
 
void setup() {
  // Sets the two pins as Outputs
  pinMode(stepPin,OUTPUT); 
  pinMode(dirPin,OUTPUT);
  Serial.begin(38400); // Default communication rate of the Bluetooth module
}
void loop() {
  delayMicroseconds(1);
  if(Serial.available() > 0){ // Checks whether data is comming from the serial port
    state = Serial.readString(); // Reads the data from the serial port
 }
 // When Auto Button is pressed
 if (mode == "Auto") {
  if (state == "Reverse") {
    delay(10);
    if (dirRotation == HIGH) {
      dirRotation = LOW;
    }
    else {
      dirRotation = HIGH;
    }  
    digitalWrite(dirPin,dirRotation);
    delay(10);
    state = "";
  }
  rotSpeed = state.toInt();
  if (rotSpeed >= 300 && rotSpeed <= 3000) {
  digitalWrite(stepPin,HIGH); 
  delayMicroseconds(rotSpeed); 
  digitalWrite(stepPin,LOW); 
  delayMicroseconds(rotSpeed);
  }
  else {
  digitalWrite(stepPin,HIGH); 
  delayMicroseconds(1500); 
  digitalWrite(stepPin,LOW); 
  delayMicroseconds(1500);
  }
  
  if (state == "Manual"){
    mode = state;
  }
 }
 // When Program is in Manual mode
 else if (mode == "Manual"){ 
 currentHeading = state.toInt();
 //Serial.println(angle);
 //Serial.println(state);
 if (currentHeading < 0 ){
  currentHeading = 360+currentHeading;
 }
 currentAngle = map(currentHeading,0,359,0,200);
 digitalWrite(dirPin,HIGH); // Enables the motor to move in a particular direction
  // Makes 200 pulses for making one full cycle rotation
  if (currentAngle != lastAngle){
    if(currentAngle > lastAngle){  
      rotate = currentAngle - lastAngle;  
      for(int x = 0; x < rotate; x++) {
      digitalWrite(stepPin,HIGH); 
      delayMicroseconds(500); 
      digitalWrite(stepPin,LOW); 
      delayMicroseconds(500); 
      }
    }

    if(currentAngle < lastAngle){  
      rotate = lastAngle - currentAngle; 
      digitalWrite(dirPin,LOW); //Changes the rotations direction
      for(int x = 0; x < rotate; x++) {
      digitalWrite(stepPin,HIGH); 
      delayMicroseconds(500); 
      digitalWrite(stepPin,LOW); 
      delayMicroseconds(500); 
      }
    }
  }
  lastAngle = currentAngle;
  if (state == "Auto"){
    mode = state;
  }
 }
}
Code language: Arduino (arduino)

39 thoughts on “How To Build Custom Android App for your Arduino Project using MIT App Inventor”

  1. Hi,
    Very good tutorial.
    But the program responds the alternate messages to the mobile phone (“LED:OFF” and “LED:ON”) when we press the ON or OFF button on the mobile phone app.
    I corrected the program by using the different value for the state variable outside the conditions. It made me solve that problem. Now it is working fine.

    Reply
    • A possible alternative may be to remove the action set(LED_Status.Text)to … from the TurnON_Button and TurnOFF_Button controls and insert it at the end of the timer:

      when Clock1.Timer
      do
      if …
      if …
      if call(BluetoothClient1.BytesAvailableToReceive > 0) then set(LED_Status.Text)to …

      It causes however another issue if you alternate quick enough between the 2 buttons!

      Reply
  2. Hi, You are correct; Thanks for pointing this out. I did not know why I was getting those numbers but now it makes sense. Also, I modified the code to use the software serial for my MEGA. Pins 10&11.

    Reply
  3. Hi Dejan
    I’m doing the same as you have mentioned in your description for Stepper motor, but unfortunately I can’t get my stepper motor to move!

    I’m using Arduino UNO, DRV8825 where I connect DIR–> D6 and STEP–>D7. RESET and SLEEP is set to High –>5V. Supply voltage 12V
    I use your code and your App. And I can see the TX LED on Arduino is flashing each time when I move the angel in App or use slider bar, but the motor will not move. Do you have any suggestions to what it could be the case ?
    (The stepper motor and wire correction is correct connected )

    Reply
  4. Hello Dejan, thank you very much for your tutorials, they are awesome!! I just would like to comment something. In this one, sometimes you accelerate the video and that turned it difficult to follow.
    After following every step mine was still not working, so after a few hours of troubleshooting, I saw that when you call the bottom (on the MIT APP) you use the function to send a number and that was not working for me. When I used another function (Call bluetoothClient.sendText “1”) then it finally worked. Hope it helps someone. Thanks again!

    Reply
  5. Dear Sir Dejan Nedelkovoski please also give tutorials on the
    ==>RFID MFRC522 a cheap 13.56MHz module with tag and keychain.
    ==>Ethernet Shield Wiznet W5100.
    ==>WiFi ESP8266-01(esp-01) a cheap WiFi with full TCP/IP stack with MCU and 512KB(blue)/1MB(black) with built-in RF on PCB etched antenna uses 3.3Volt (given externally not from Arduino as it does not run as it requires more Current)Please reply as I had commented before this.

    Reply
  6. Sir, can you please create a tutorial on how to built an android app for controlling motors of RC Car? just an app that can move the car to forward and backward then right and left directions. I just want to built a smartphone controlled RC Car using arduino and bluetooth module but I don’t have any initial ideas on how to start it. Your help is much appreciated. thank you!

    Reply
  7. There is one mistake in “Blocks” that causes weird (-65536 error) instead of “Not Connected” status. In the YT video and first photo in tutorial (“Blocks” structure) the text color (Red and Blue) is set to “Text” type. It should be “TextColor”.

    Reply
    • Thanks Konrad, nice catch! I was had the same issue but since I’m new to the MIT App Inventor I completely missed the mistake. Glad you made the comment.

      Reply
  8. I made my own .apk with this tutorial but when I open my app there is “Not Connected” only for the moment, then I have error code “-3407872”. Where is the problem.? Do You help me with that.?

    Reply
  9. Hello, I have a problem in compare data
    receives from arduino to the cellphone but when I need to compare the data had problems. Example Arduino send : “a” , Android recive and compare : “a”=”1” I have no response in the label

    Reply
  10. hello sir its a great project and i am going to do it for my college project…… but i want to have a video on how to connect the arduino with blutooth and stepper motor in this project……. if you can upload a video on how to connect the hardware it would be great….. thank you!

    Reply
  11. Hello sir, can you provide a tutorial -to create a softwear in visual studio that connect & control ardunio and display senser data like temp,humidity,servo motor speed,led on off………….

    Reply
  12. Hello Sir, this project is really good.I install .apk file from this website for led toturial .It open and connect with my bluetooth. when I Turn On led my led is not blinking .and mobile going hang. I also repet this process in my other android device ..there also connection between mobile and bluetooth is success .but led is not blink (mobile work properly)……Please help me to solve this problame…..

    Reply
  13. If I use a different version of the HC-05 Bluetooth module, will this still work or do I have to use the exact bluetooth module used in this tutorial?

    Reply
  14. Hello. Thanks for this awesome tutorial. I need to do something similar in my project. I want to display the signal (as a graph) on the app. The signal being fed to Arduino analog input. Is there any way to do it? I am not so good at programming, so appinventor seemed easy way to make an app.
    Thanks!

    Reply
  15. hello there,

    great tutorial. using app inventor 2, i did the same app but there is problem. after i run the app on my phone in the beginning it displays not connected message but after that it displays a number (-65536). so i dont know whether the device is connected or not?

    Reply
  16. hello, thank you is really good! how can I create an app and a sketch but using the Ethernet Shield? could you help me? I would like to create an application for Android and manage Arduino pin remotely. Thanks so much!

    Reply
  17. Hello , very good your video classes . I was trying to make a mixture of those programs that you did. I would like to make a radar as you used in the processor or something like that , with app inventor , it is possible ? I did not find any information on how to do this in AI2 . It would be necessary another application to create the radar ? Which application?

    The AI2 would get the values ​​starting from arduino , reading data ( angle and distance) would be sent via Bluetooth .

    It is possible to do it? I do not have much knowledge on AI2 , but I can learn more.

    Thank you!

    Reply

Leave a Comment