Introduction: Nexus 7 and the Arduino.

About: computoman.blogspot.com Bytesize articles instead of a trilogy in one post.

Will show several ways to show how to use an Arduino as a sensor using The Nexus 7 for a terminal and to do development. This can be very important for protecting your electronic equipment especially servers.

Note 1: All connections are to a standard Arduino board. This instructable is for users very familiar with the Arduino boards. If you are a novice, you may want to get additional help.

Note 2: With android 5.1, you may not be able to direct connect the devices, but using a router that has a dhcp server can be a temporary fix. Android 5.0x does not seem to support ethernet connections.

Wigh android 5.1.1and the latest version of the software, there is no way to fix the baud rate so uploads do not work.

Step 1: Working With the Nexus 7.

Want to hook your Nexus 7 directly to your arduino, then all you need is a OTG cable and a standard usb cable. Get the free (at this time) UsbTerminal app from the playstore and install it.You will want to set the Arduino serial port and the nexus 7 both the the same speed. We use 9600. 
 Have fun.

Code to test the connect from the Arduino to the Nexus 7.


<code>
void setup() {
  // put your setup code here, to run once:
 Serial.begin(9600);

}

void loop() {
  // put your main code here, to run repeatedly:
  Serial.println("This is a test");
  delay(1000);
}
</code>

Step 2: Developing for the Arduino on the Nexus 7

Assuming you have used the standard ide for the Arduino on a personal computer. There are enough tutorials that it should not be needed  to be repeated. (arduino.cc).  Arduinodroid is an ide for the Arduino that runs under Android. It seems to have the basic files built in. The software also worked with my Osepp Arduino board. It was the first application I saw in the playstore, but there may be more.

Step 3: Several Examples to Work With.

Some examples aka basic building blocks to play with. Some of frames  are still under construction or to be completely revised..
1.  EMF (Electomotive force) field reader
2. Capacitive reader
3. Temperature reading
4. Flood detection.

Step 4: Magnetic Field

Test anything that might be emitting electromagnetic energy, Bug detector?


<code>
// EMF Detector for LED Bargraph v1.0
// 5.12.2009
// original code/project by Aaron ALAI - aaronalai1@gmail.com

#define NUMREADINGS 15 // raise this number to increase data smoothing

int senseLimit = 15; // raise this number to decrease sensitivity (up to 1023 max)
int probePin = 5; // analog 5
int val = 0; // reading from probePin


// variables for smoothing

int readings[NUMREADINGS];                // the readings from the analog input
int index = 0;                            // the index of the current reading
int total = 0;                            // the running total
int average = 0;                          // final average of the probe reading


void setup() {


  Serial.begin(9600);  // initiate serial connection for debugging/etc

  for (int i = 0; i < NUMREADINGS; i++)
    readings[i] = 0;                      // initialize all the readings to 0
}

void loop() {

  val = analogRead(probePin);  // take a reading from the probe

  if(val >= 1){                // if the reading isn't zero, proceed

    val = constrain(val, 1, senseLimit);  // turn any reading higher than the senseLimit value into the senseLimit value
    val = map(val, 1, senseLimit, 1, 1023);  // remap the constrained value within a 1 to 1023 range

    total -= readings[index];               // subtract the last reading
    readings[index] = val; // read from the sensor
    total += readings[index];               // add the reading to the total
    index = (index + 1);                    // advance to the next index

    if (index >= NUMREADINGS)               // if we're at the end of the array...
      index = 0;                            // ...wrap around to the beginning

    average = total / NUMREADINGS;          // calculate the average

    Serial.println(val); // use output to aid in calibrating
  }
}
</code>

Step 5: Capacitive Sense.

Touch sensor or field sensor. great for using on doors (around door knobs) or near something that should not be touched.


<code>
#include <CapacitiveSensor.h>

/*
 * CapitiveSense Library Demo Sketch
 * Paul Badger 2008
 * Uses a high value resistor e.g. 10 megohm between send pin and receive pin
 * Resistor effects sensitivity, experiment with values, 50 kilohm - 50 megohm. Larger resistor values yield larger sensor values.
 * Receive pin is the sensor pin - try different amounts of foil/metal on this pin
 * Best results are obtained if sensor foil and wire is covered with an insulator such as paper or plastic sheet
 */


CapacitiveSensor   cs_4_2 = CapacitiveSensor(4,2);        // 10 megohm resistor between pins 4 & 2, pin 2 is sensor pin, add wire, foil
CapacitiveSensor   cs_4_5 = CapacitiveSensor(4,5);        // 10 megohm resistor between pins 4 & 6, pin 6 is sensor pin, add wire, foil
CapacitiveSensor   cs_4_8 = CapacitiveSensor(4,8);        // 10 megohm resistor between pins 4 & 8, pin 8 is sensor pin, add wire, foil

void setup()                    
{

   cs_4_2.set_CS_AutocaL_Millis(0xFFFFFFFF);     // turn off autocalibrate on channel 1 - just as an example
   Serial.begin(9600);

}

void loop()                    
{
    long start = millis();
    long total1 =  cs_4_2.capacitiveSensor(30);
    long total2 =  cs_4_5.capacitiveSensor(30);
    long total3 =  cs_4_8.capacitiveSensor(30);

    Serial.print(millis() - start);        // check on performance in milliseconds
    Serial.print("\t");                    // tab character for debug windown spacing

    Serial.print(total1);                  // print sensor output 1
    Serial.print("\t");
    Serial.print(total2);                  // print sensor output 2
    Serial.print("\t");
    Serial.println(total3);                // print sensor output 3

    delay(10);                             // arbitrary delay to limit data to serial port 
}


</code>

Step 6: Temp Sensor.

Temp sensor. Isit too hoo for you or your equipment, so now you can tell. Could also be the start of a sous vide machine.

<code.>

//declare variables
float tempC;
int tempPin = 0;

void setup()
{
Serial.begin(9600); //opens serial port, sets data rate to 9600 bps
}

void loop()
{
tempC = analogRead(tempPin);           //read the value from the sensor
tempC = (5.0 * tempC * 100.0)/1024.0;  //convert the analog data to temperature
Serial.print((byte)tempC);             //send the data to the computer
delay(1000);                           //wait one second before sending new data
}

</code>

Step 7: Flood Sensor.

This is a short circuit sensor that could easily be used to detect where there is liquid such as water flowing into the rool. Did a pipe break or a window break during a storm.

<code>
 /* Flood Sensor

 This sketch Display message when water (anything conductive) bridges the gap in the sensor.

   created 02/09/09
   by n00b


 */

 const int floodSensors = 2;     // the number of the Flood Sensor pin

 // variables will change:
 int floodSensorState = 0;         // variable for reading the floodSensors status

 void setup() {
   // initialize the flood Sensor pin as an input:
   pinMode(floodSensors, INPUT);    
   Serial.begin(9600);
 }

 void loop(){
   // read the state of the flood Sensor value:
   floodSensorState = digitalRead(floodSensors);

   // check if the flood Sensor is wet.
   // if it is, the floodSensorState is HIGH:
   if (floodSensorState == HIGH) {    
     // turn LED on:   
    Serial.println(floodSensorState); 
    Serial.println("Warning there is a flood");
   }
   else {
     // Not flood:
     // Serial.println(floodSensorState);
    // Serial.println(floodSensorState);
   }
 }

</code>

Step 8: Check Out Web Page From the Arduino.

If your arduino has an ethernet adapter you can try this setup. Just connect to http://192.168.1.17 from another system on the network to turn on or turn off an led. Home automation basic idea to start with.

You will need to copy your ip setting somewhere so that you can restore them when you finnish.
Then set new ip adress settings so the two can talk with each other.

Nexus 7
IPadress: 192.168.1.20
Netmask 255.255.255.0
Gateway 192.1168.1.20

Arduino
IPadress: 192.168.1.17
Netmask 255.255.255.0
Gateway 192.1168.1.20

<code>
/*
Web Server
A simple web server
Circuit:
* Ethernet shield attached to pins oA, 0B 0C, 0D
*/
//——————————————————————————————————-
#include <SPI.h>
#include <Ethernet.h>
// Enter a MAC address and IP address for your controller below.
byte mac[] = {0×90, 0xA2, 0xDA, 0x0D, 0×48, 0xD3 };
// The IP address will be dependent on your local network:
// assign an IP address for the controller:
IPAddress ip(192,168,1,17);
IPAddress gateway(192,168,1,1);
IPAddress subnet(255, 255, 255, 0);
// Initialize the Ethernet server library with the port you want to use.
EthernetServer server(80);
String readString;
//——————————————————————————————————-
//————————————————-
// Any extra codes for Declaration :
// Declare Pin 8 as an LED because thats what we will be connecting the LED to.You could use any other pin and would then have to change the pin number.
int led = 8;
//————————————————-
//——————————————————————————————————-
void setup()
{
//————————————————-
// Extra Set up code:
pinMode(led, OUTPUT); //pin selected to control
//————————————————-
//——————————————————————————————————-
//enable serial data print
Serial.begin(9600);
//start Ethernet
Ethernet.begin(mac, ip, gateway, subnet);
server.begin();
Serial.print(“Server is at “);
Serial.println(Ethernet.localIP());
Serial.println(“LED Controller Test 1.0″);
}
//——————————————————————————————————-
//——————————————————————————————————-
void loop()
{
// listen for incoming clients
EthernetClient client = server.available();
if (client)
{
Serial.println(“new client”);
while (client.connected())
{
if (client.available())
{
char c = client.read();
//read char by char HTTP request
if (readString.length() < 100)
{
//store characters to string
readString += c;
//Serial.print(c);
Serial.write(c);
// if you’ve gotten to the end of the line (received a newline
// character) and the line is blank, the http request has ended,
// so you can send a reply
//if HTTP request has ended
if (c == ‘\n’) {
Serial.println(readString); //print to serial monitor for debuging
//——————————————————————————————————–
// Needed to Display Site:
client.println(“HTTP/1.1 200 OK”); //send new page
client.println(“Content-Type: text/html”);
client.println();
client.println(“<HTML>”);
client.println(“<HEAD>”);
//——————————————————————————————————–
//————————————————-
// what is being Displayed :
client.println(“<TITLE>Home Automation</TITLE>”);
client.println(“<center>”);
client.println(“</HEAD>”);
client.println(“<BODY>”);
client.println(“<H1>Home Automation</H1>”);
client.println(“<hr />”);
client.println(“<center>”);
client.println(“<a href=\”/?lighton\”\”>Turn On Light</a>”);
client.println(“<br />”);
client.println(“<br />”);
client.println(“<a href=\”/?lightoff\”\”>Turn Off Light</a><br />”);
client.println(“</BODY>”);
client.println(“</HTML>”);
delay(1);
//stopping client
client.stop();
//————————————————-
// Code which needs to be Implemented:
if(readString.indexOf(“?lighton”) >0)//checks for on
{
digitalWrite(8, HIGH); // set pin 4 high
Serial.println(“Led On”);
}
else{
if(readString.indexOf(“?lightoff”) >0)//checks for off
{
digitalWrite(8, LOW); // set pin 4 low
Serial.println(“Led Off”);
}
}
//clearing string for next read
readString=”";
// give the web browser time to receive the data
delay(1);
// close the connection:
client.stop();
Serial.println(“client disonnected”);
}
}
}
}
}
}
</code>

Step 9: Arduino Commander

Control your Arduino board from your Android device over Bluetooth, Ethernet or USB (Diecimila, Duemilanove, Uno r1/r2/r3, Mega, Leonardo, Nano) using WYSIWYG interface, Android sensors or JavaScript script. Get Arduino Commander from the play store.

Step 10: Msp430.

Did find one application for the Msp430 to run on the Nexus 7. Have not tried it so use at your own risk.