This is the third post in a series on mobile development for Arduino. The Internet of Things is the ever growing cadre of physical entities, be it devices, vehicles, wearables, etc. that are embedded with sensors and are capable of network connectivity. These qualities, enable these physical entities to collect and exchange data that can be accessed remotely and integrated with computer networks to improve efficiency and ultimately produce benefits for society. This is why the Internet of Things is not only an emerging trend in the mobile industry but also the entire technology sector as well with the potential to be a primary catalyst for global economic development in the coming decade. We may very well be on the precipice of the second industrial revolution courtesy of the Internet of Things.

In my previous two posts, “Mobile Development for Arduino Part 1 and Part 2,” I provided an introduction to IoT software development using Arduino as a platform. Arduino is an open source hardware solution which gives developers an opportunity to cultivate a thorough understanding of electronics and learn how to integrate them using software. In Mobile Development for Arduino Part 1, we connected a mobile device to the Arduino via a USB cable and enabled the two devices to communicate via serial connection. In part 2, we cut the cord and established communication between the Arduino and mobile device by using bluetooth to make a serial connection. In this tutorial, we are going to up the ante by taking full-advantage of the “Internet” in Internet of Things and communicate with the Arduino via REST services over and HTTP connection.

The first thing we are going to do is upgrade our hardware. Previously, we used the Arduino Uno. Unfortunately, the Uno is not equipped with the necessary hardware components for network connectivity. However, the Arduino Yun is capable of network connectivity. For those who are unfamiliar with Arduino Yun, it is an Arduino model that has wifi network connectivity. The Yun also comes with additional features, such as micro and standard USB ports, support for microSD, and an ethernet port. It is a very suitable platform for any beginner’s initial foray into IoT development and prototyping. Alternatively, one could also purchase a wifi shield for their Arduino Uno and extend its functionality to include network connectivity.

1. Configure Yun to Connect Network

Arduino provides an easy to follow video guide on how to connect your Yun to a wireless network that is available for viewing here. It must be noted that it takes the Yun about 1 minute to “boot up” as a recognized device after plugging it into your computer. It will indicate that it is ready to begin the configuration process when the white USB light turns. Be sure to configure your Yun to work with REST. REST stands for Representational State Transfer. It is a type of network communication that will alow us to communicate with the Arduino Yun via HTTP requests. On the bottom of the configuration screen be sure to select the REST option.

image

Also be sure to take note of your Yun’s IP address after a successful configuration. This will be needed to execute our rest calls.

image

If you configure your Yun incorrectly, it can be easily remedied by holding the wifi reset button on the Yun board. After 30 seconds, the board will be ready to be re-configured.

2. Write Arduino Code

This code incorporates three Arduino libraries that make network communication possible. The Bridge library enables the two processors on the Yun to communicate with each other. The BridgeServer library allows the Yun to function as an Arduino based HTTP server and is modeled after the EthernetServer class. Likewise, the BrideClient library allows the Yun to function as HTTP client and is modeled after the EthernetClient class. This code allows Arduino to process the data that comes through via REST. When done, upload your sketch.

#include <Bridge.h>
#include <BridgeServer.h>
#include <BridgeClient.h>

BridgeServer server;
int speakerPin = 9;

void setup() {
  Serial.begin(9600);
  pinMode(speakerPin, OUTPUT);
  pinMode(13,OUTPUT);
  digitalWrite(13, LOW);
  Bridge.begin();
  digitalWrite(13, HIGH);

  server.listenOnLocalhost();
  server.begin();
}

void loop() {
 BridgeClient client = server.accept();

  if (client) {
    process(client);
    client.stop();
  }

  delay(50);
}

void process(BridgeClient client) {

    String incomingNote = client.readStringUntil('/');

    playNote(incomingNote.toInt());

}

void playNote(int note) {
  int tones[] = { 440, 494, 523, 587, 659, 698, 784};
  tone(speakerPin, tones[note], 200);
}

 

3. Connect Physical Arduino Yun Components in Manner Shown Below

image

Connect the GRD on the Yun to the Piezo and connect pin 9 on the Yun to the Piezo as well.

4. Sanity Check Via Web Browser

At this point, your Yun should be fully capable of receiving information from a network and executing commands based off of that information. We can verify this by constructing a web request and calling it in a web browser. To accomplish this, we need to take the IP address of the Yun that we created in step 1 and make a uri with the IP address you identified in step 1.

For example, https://10.0.0.19/arduino/1 . The “10.0.0.19” in this uri routes us to the Yun, the “Arduino” is used by the Bridge libraries to identify that it is a REST request, and the “1” is the note that we would like the Piezo to play, based on the array in our sketch file. Run this uri in your web browser and you should hear your Piezo make a sound. If you don’t hear a sound, ensure that the Yun has power and that both the white USB light and red WLAN light are on. Otherwise, repeat steps 1-4.

5. Create Yun Fragment, Web Service, and Yun Fragment in Android Application

The application we created in part 2 will be used as the foundation for our new code. We need to architect our application so that we can separate the concerns of making web requests and managing the data related to those requests. To do this we are going to implement the RxJava and Retrofit libraries. Rxjava allows for more functional programming and Retrofit simplifies the process of making web request. In your app level build.gradle file add the following imports:

compile 'com.squareup.retrofit:retrofit:1.9.0'
compile 'io.reactivex:rxjava:1.0.14'

Next, we need to create a web services interface for our web requests.

public interface interfaceWebServices {

   public static class Factory {

       public static interfaceWebServices create(String endpoint) {

           RestAdapter restAdapter = new RestAdapter.Builder()
                   .setEndpoint(endpoint)
                   .build();

           if (BuildConfig.DEBUG) {
               restAdapter.setLogLevel(RestAdapter.LogLevel.FULL);
           }

           return restAdapter.create(interfaceWebServices.class);
       }

   }

   @GET("/arduino/{note}")
   Observable<Response> sendNote(@Path("note") String note);

}

Next, we need to create our web manager class.

public class WebManager {

   private interfaceWebServices webService;

   public WebManager (interfaceWebServices webService){
       this.webService = webService;
   }

   public Observable<Response> sendNote(String note) {
       return webService.sendNote(note);
   }
}

Lastly, we need to create a new Fragment to handle wifi network communication with the Yun. Be sure to also call a new instance of this fragment in Activity_Main and not the fragments from the previous tutorials.

public class FragmentArduinoYun extends Fragment implements AdapterView.OnItemClickListener {
   static final String TAG = "Fragment Arduino";

   @Bind(R.id.coordinatorLayout)CoordinatorLayout coordinatorLayout;
   @Bind(R.id.lv_notes)ListView notesListView;

   String[] musicalNotes = new String[] { "A","B","C","D","E","F","G"};

   WebManager webManager;

   public static FragmentArduinoYun newInstance() {
       return new FragmentArduinoYun();
   }

   public FragmentArduinoYun() {
       // Required empty public constructor
   }

   @Override
   public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
   }

   @Override
   public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
       View rootView = inflater.inflate(R.layout.fragment_arduino, container, false);
       ButterKnife.bind(this, rootView);
       return rootView;
   }

   @Override
   public void onViewCreated(View view, Bundle savedInstanceState) {
       super.onViewCreated(view, savedInstanceState);

       ArrayAdapter<String> musicalNotesAdapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, musicalNotes);
       notesListView.setOnItemClickListener(this);
       notesListView.setAdapter(musicalNotesAdapter);

       webManager = new WebManager(interfaceWebServices.Factory.create("https://10.0.0.19"));
   }


   @Override
   public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

       webManager.sendNote(String.valueOf(position))
               .observeOn(AndroidSchedulers.mainThread())
               .subscribe(r -> {}, e -> Toast.makeText(getContext(), e.toString(), Toast.LENGTH_LONG).show());
   }

}

All that is left to do now is run and the application and make melodious music with your Internet of Things prototype.

The GitHub repository for this ongoing project is available here. Stay tuned for more mobile development for Arduino!

Leave a Reply to Joe Swanson Cancel reply

Your email address will not be published. Required fields are marked *