text:
How to send 1 byte from android to arduino
My idea is Arduino sensor will read and pass the values read on android. Then android will calculate and send the control value (PWM) to the Arduino.
but android can only get the value from the Arduino but can not send them back to the Arduino ... Can someone please help?
This my code:
java code:
+MainActivity
package com.example.tut1;

import java.nio.ByteBuffer;
import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.bluetooth.BluetoothSocket;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;

import com.example.tut1.Bluetooth;
import com.jjoe64.graphview.GraphView;
import com.jjoe64.graphview.GraphView.GraphViewData;
import com.jjoe64.graphview.GraphView.LegendAlign;
import com.jjoe64.graphview.GraphViewSeries;
import com.jjoe64.graphview.GraphViewSeries.GraphViewStyle;
import com.jjoe64.graphview.LineGraphView;

public class MainActivity extends Activity implements View.OnClickListener {

    // private StringBuilder recDataString = new StringBuilder();

@Override
public void onBackPressed() {
    // TODO Auto-generated method stub
    if (Bluetooth.connectedThread != null) {
        Bluetooth.connectedThread.write("Q");
    }// Stop streaming
    super.onBackPressed();
}

// khai bao bien
String x, x1;
int u,u1,adc,adc1;
public String sensor, sensor1;
static boolean f=false;
// toggle Button
static boolean Lock;// whether lock the x-axis to 0-5
static boolean AutoScrollX;// auto scroll to the last x value
static boolean Stream;// Start or stop streaming
// Button init
Button bXminus;
Button bXplus;
Button bConnect, bDisconnect;
Button bStart,bStop;
TextView tvBluetooth, tvpid;
ToggleButton tbLock;
ToggleButton tbScroll;
ToggleButton tbStream;
// GraphView init
static LinearLayout GraphView, GraphView1;
static GraphView graphView, graphView1;
static GraphViewSeries Series, Series1;
// graph value
private static double graph2LastXValue = 0, graph2LastXValue1 = 0;
private static int Xview = 10, Xview1 = 10;

// khai bao bien timer
final Handler thandler = new Handler();
Timer t = new Timer();
TimerTask mTimerTask;

Handler mHandler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
        // TODO Auto-generated method stub
        super.handleMessage(msg);
        switch (msg.what) {
        case Bluetooth.SUCCESS_CONNECT:
            Bluetooth.connectedThread = new Bluetooth.ConnectedThread(
                    (BluetoothSocket) msg.obj);
            Toast.makeText(getApplicationContext(), "Connected!", 0).show();
            String s = "successfully connected";
            Bluetooth.connectedThread.start();
            break;
        case Bluetooth.MESSAGE_READ:

            byte[] readBuf = (byte[]) msg.obj;
            String strIncom = new String(readBuf); // create string from
                                                    // bytes array

            // if(strIncom.indexOf('s')==0){
            // strIncom = strIncom.replace("s", "");
            // }
            int a = strIncom.indexOf("c");
            int b = 4;
            int c = 4;
            int d = 8;
            sensor = (String) strIncom.subSequence(1, 5);
            sensor1 = (String) strIncom.subSequence(5, 9);
            tvBluetooth.setText(strIncom);
//              Bluetooth.connectedThread.write("E");
//              adc=Integer.parseInt(sensor);
//              adc1=Integer.parseInt(sensor1);
            tvpid.setText(sensor + "-" + sensor1+"-"+u+"-"+u1);
            // String readMessage = (String)msg.obj;
            // recDataString.append(readMessage);
            // sensor = recDataString.substring(0, 4);
            Log.d("strIncom", sensor);
            // if (strIncom.indexOf('.')==2 && strIncom.indexOf('s')==0){
            // strIncom = strIncom.replace("s", "");
            if((strIncom.indexOf("X")==9)&&(strIncom.indexOf("Y")==0)){
            if (isFloatNumber(sensor) && isFloatNumber(sensor1)) {
                Series.appendData(new GraphViewData(graph2LastXValue,
                        Double.parseDouble(sensor)), AutoScrollX);
                Series1.appendData(new GraphViewData(graph2LastXValue1,
                        Double.parseDouble(sensor1)), AutoScrollX);

                // X-axis control
                if (graph2LastXValue >= Xview && Lock == true) {
                    Series.resetData(new GraphViewData[] {});
                    graph2LastXValue = 0;
                } else
                    graph2LastXValue += 0.1;

                if (Lock == true)
                    graphView.setViewPort(0, Xview);
                else
                    graphView.setViewPort(graph2LastXValue - Xview, Xview);

                // grap1
                if (graph2LastXValue1 >= Xview1 && Lock == true) {
                    Series1.resetData(new GraphViewData[] {});
                    graph2LastXValue1 = 0;
                } else
                    graph2LastXValue1 += 0.1;

                if (Lock == true)
                    graphView1.setViewPort(0, Xview1);
                else
                    graphView1.setViewPort(graph2LastXValue1 - Xview1,
                            Xview1);

                // refresh
                GraphView.removeView(graphView);
                GraphView1.removeView(graphView1);
                GraphView.addView(graphView);
                GraphView1.addView(graphView1);
                dieukhienPPM();
                dieukhienPH();
            }
             }
//              if(f)
//              t.schedule(mTimerTask, 60, 60);

//              u = (int) adc/4;
//              u1=(int) adc1/4;
//              f=true;
            break;
        }
    }

    public boolean isFloatNumber(String num) {
        // Log.d("checkfloatNum", num);
        try {
            Double.parseDouble(num);
        } catch (NumberFormatException nfe) {
            return false;
        }
        return true;
    }

};

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
    requestWindowFeature(Window.FEATURE_NO_TITLE);// Hide title
    this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN);// Hide Status bar
    setContentView(R.layout.activity_main);
    // set background color
    LinearLayout background = (LinearLayout) findViewById(R.id.bg);
    background.setBackgroundColor(Color.BLACK);
    init();
    ButtonInit();
}

void init() {
    Bluetooth.gethandler(mHandler);

    // init graphview
    GraphView = (LinearLayout) findViewById(R.id.Graph);
    // init example series data-------------------
    Series = new GraphViewSeries("Signal", new GraphViewStyle(Color.YELLOW,
            2),// color and thickness of the line
            new GraphViewData[] { new GraphViewData(0, 0) });
    graphView = new LineGraphView(this // context
            , "Graph" // heading
    );
    graphView.setViewPort(0, Xview);
    graphView.setScrollable(true);
    graphView.setScalable(true);
    graphView.setShowLegend(true);
    graphView.setLegendAlign(LegendAlign.BOTTOM);
    graphView.setManualYAxis(true);
    graphView.setManualYAxisBounds(1024, 0);
    graphView.addSeries(Series); // data
    GraphView.addView(graphView);

    GraphView1 = (LinearLayout) findViewById(R.id.Graph1);
    // init example series data-------------------
    Series1 = new GraphViewSeries("Signal", new GraphViewStyle(
            Color.YELLOW, 2),// color and thickness of the line
            new GraphViewData[] { new GraphViewData(0, 0) });
    graphView1 = new LineGraphView(this // context
            , "Graph1" // heading
    );
    graphView1.setViewPort(0, Xview1);
    graphView1.setScrollable(true);
    graphView1.setScalable(true);
    graphView1.setShowLegend(true);
    graphView1.setLegendAlign(LegendAlign.BOTTOM);
    graphView1.setManualYAxis(true);
    graphView1.setManualYAxisBounds(1024, 0);
    graphView1.addSeries(Series1); // data
    GraphView1.addView(graphView1);
}

void ButtonInit() {
    bConnect = (Button) findViewById(R.id.bConnect);
    bConnect.setOnClickListener(this);
    bDisconnect = (Button) findViewById(R.id.bDisconnect);
    bDisconnect.setOnClickListener(this);
    bStart = (Button) findViewById(R.id.bStart);
    bStart.setOnClickListener(this);
    bStop = (Button) findViewById(R.id.bStop);
    bStop.setOnClickListener(this);
    // X-axis control button
    // bXminus = (Button)findViewById(R.id.bXminus);
    // bXminus.setOnClickListener(this);
    // bXplus = (Button)findViewById(R.id.bXplus);
    // bXplus.setOnClickListener(this);
    // //
    // tbLock = (ToggleButton)findViewById(R.id.tbLock);
    // tbLock.setOnClickListener(this);
    // tbScroll = (ToggleButton)findViewById(R.id.tbScroll);
    // tbScroll.setOnClickListener(this);
//      tbStream = (ToggleButton) findViewById(R.id.tbStream);
//      tbStream.setOnClickListener(this);
    tvBluetooth = (TextView) findViewById(R.id.tvBluetooth);
    tvpid = (TextView) findViewById(R.id.tvpid);
    // init toggleButton
    Lock = true;
    AutoScrollX = true;
    Stream = false;
}

@Override
public void onClick(View v) {
    // TODO Auto-generated method stub
    switch (v.getId()) {
    case R.id.bConnect:
        startActivity(new Intent("android.intent.action.BT1"));
        break;
    case R.id.bDisconnect:
        Bluetooth.disconnect();
        break;
    case R.id.bStart:
        if (Bluetooth.connectedThread != null)
            Bluetooth.connectedThread.write("E");
            doTimerTask();
        break;
    case R.id.bStop:
        if (Bluetooth.connectedThread != null)
            Bluetooth.connectedThread.write("Q");
        stopTask();
        break;
    // case R.id.bXminus:
    // if (Xview>1) Xview--;
    // break;
    // case R.id.bXplus:
    // if (Xview<30) Xview++;
    // break;
    // case R.id.tbLock:
    // if (tbLock.isChecked()){
    // Lock = true;
    // }else{
    // Lock = false;
    // }
    // break;
    // case R.id.tbScroll:
    // if (tbScroll.isChecked()){
    // AutoScrollX = true;
    // }else{
    // AutoScrollX = false;
    // }
    // break;
//      case R.id.tbStream:
//          if (tbStream.isChecked()) {
//              if (Bluetooth.connectedThread != null)
//                  Bluetooth.connectedThread.write("E");
//          } else {
//              if (Bluetooth.connectedThread != null)
//                  Bluetooth.connectedThread.write("Q");
//          }
//          break;
    }
}

public void doTimerTask() {
    mTimerTask = new TimerTask() {
        public void run() {
            thandler.post(new Runnable() {
                public void run() {
                    // TODO Auto-generated method stub
 //                     dieukhienPPM();
//                      dieukhienPH();
                    Bluetooth.connectedThread.write("A");
                    x = Integer.toString(u);
                    Bluetooth.connectedThread.write(x);
                    Bluetooth.connectedThread.write("B");
                    x1=Integer.toString(u1);
                    Bluetooth.connectedThread.write(x1);
                    Bluetooth.connectedThread.write("S");
                }
            });
        }
    };

    // public void schedule (TimerTask task, long delay, long period)
     t.schedule(mTimerTask, 500, 500); // Thoi gian delay va thoi gian lap
    // tinh
    // bang mili giay
}

public void stopTask() {
    if (mTimerTask != null)
        mTimerTask.cancel();
}

public void dieukhienPPM() {
    u= (Integer.parseInt(sensor)/4);
}

public void dieukhienPH() {
    u1 = (Integer.parseInt(sensor1)/4);
}

public static byte[] toByteArray(double value) {
    byte[] bytes = new byte[8];
    ByteBuffer.wrap(bytes).putDouble(value);
    return bytes;
}
}

+Bluetooth
package com.example.tut1;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Set;
import java.util.UUID;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class Bluetooth extends Activity implements OnItemClickListener{

public static void disconnect(){
    if (connectedThread != null) {
        connectedThread.cancel();
        connectedThread = null;
    }
}

public static void gethandler(Handler handler){//Bluetooth handler
    mHandler = handler;
}
static Handler mHandler = new Handler();

static ConnectedThread connectedThread;
public static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-           00805F9B34FB");
protected static final int SUCCESS_CONNECT = 0;
protected static final int MESSAGE_READ = 1;
ArrayAdapter<String> listAdapter;
ListView listView;
static BluetoothAdapter btAdapter;
Set<BluetoothDevice> devicesArray;
ArrayList<String> pairedDevices;
ArrayList<BluetoothDevice> devices;
IntentFilter filter;
BroadcastReceiver receiver;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_bluetooth);
    init();
    if (btAdapter==null){
        Toast.makeText(getApplicationContext(), "No bluetooth detected", 0).show();
        finish();
    }else{
        if (!btAdapter.isEnabled()){
            turnOnBT();
        }
        getPairedDevices();
        startDiscovery();
    }

}

private void startDiscovery() {
    // TODO Auto-generated method stub
    btAdapter.cancelDiscovery();
    btAdapter.startDiscovery();
}

private void turnOnBT() {
    Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
    startActivityForResult(intent, 1);
}

private void getPairedDevices() {
    devicesArray = btAdapter.getBondedDevices();
    if (devicesArray.size()>0){
        for(BluetoothDevice device:devicesArray){
            pairedDevices.add(device.getName());
        }
    }
}

private void init(){
    listView = (ListView)findViewById(R.id.listView);
    listView.setOnItemClickListener(this);
    listAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,0);
    listView.setAdapter(listAdapter);
    btAdapter = BluetoothAdapter.getDefaultAdapter();
    pairedDevices = new ArrayList<String>();
    filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
    devices = new ArrayList<BluetoothDevice>();
    receiver = new BroadcastReceiver(){
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (BluetoothDevice.ACTION_FOUND.equals(action)){
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                devices.add(device);
                String s = "";
                for(int a=0;a<pairedDevices.size();a++){
                    if (device.getName().equals(pairedDevices.get(a))){
                        //append
                        s = "(Paired)";
                        break;
                    }
                }
                listAdapter.add(device.getName()+" "+s+" "+"\n"+device.getAddress());

            }else if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)){

            }else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)){

            }else if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)){
                if (btAdapter.getState() == btAdapter.STATE_OFF){
                    turnOnBT();
                }
            }
        }

    };

    registerReceiver(receiver, filter);
    IntentFilter filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
    registerReceiver(receiver, filter);
    filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
    registerReceiver(receiver, filter);
    filter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
}

@Override
protected void onPause() {
    // TODO Auto-generated method stub
    super.onPause();
    unregisterReceiver(receiver);
}

protected void onActivityResult(int requestCode, int resultCode, Intent data){
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == RESULT_CANCELED){
        Toast.makeText(getApplicationContext(), "Bluetooth must be enabled to continue", Toast.LENGTH_SHORT).show();
        finish();
    }
}

@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
    // TODO Auto-generated method stub
    if (btAdapter.isDiscovering()){
        btAdapter.cancelDiscovery();
    }
    if (listAdapter.getItem(arg2).contains("(Paired)")){

        BluetoothDevice selectedDevice = devices.get(arg2);
        ConnectThread connect = new ConnectThread(selectedDevice);
        connect.start();
    }else {
        Toast.makeText(getApplicationContext(), "device is not paired", 0).show();
    }
}

private class ConnectThread extends Thread {
    private final BluetoothSocket mmSocket;
    private final BluetoothDevice mmDevice;

    public ConnectThread(BluetoothDevice device) {
        // Use a temporary object that is later assigned to mmSocket,
        // because mmSocket is final
        BluetoothSocket tmp = null;
        mmDevice = device;

        // Get a BluetoothSocket to connect with the given BluetoothDevice
        try {
            // MY_UUID is the app's UUID string, also used by the server code
            tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
        } catch (IOException e) { }
        mmSocket = tmp;
    }

    public void run() {
        // Cancel discovery because it will slow down the connection
        btAdapter.cancelDiscovery();

        try {
            // Connect the device through the socket. This will block
            // until it succeeds or throws an exception
            mmSocket.connect();
            //connectedThread = new ConnectedThread(mmSocket);
        } catch (IOException connectException) {
            // Unable to connect; close the socket and get out
            try {
                mmSocket.close();
            } catch (IOException closeException) { }
            return;
        }

        // Do work to manage the connection (in a separate thread)
        mHandler.obtainMessage(SUCCESS_CONNECT, mmSocket).sendToTarget();
    }

    /** Will cancel an in-progress connection, and close the socket */
    public void cancel() {
        try {
            mmSocket.close();
        } catch (IOException e) { }
    }
}

static class ConnectedThread extends Thread {
    private final BluetoothSocket mmSocket;
    private final InputStream mmInStream;
    private final OutputStream mmOutStream;

    public ConnectedThread(BluetoothSocket socket) {
        mmSocket = socket;
        InputStream tmpIn = null;
        OutputStream tmpOut = null;

        // Get the input and output streams, using temp objects because
        // member streams are final
        try {
            tmpIn = socket.getInputStream();
            tmpOut = socket.getOutputStream();
        } catch (IOException e) { }

        mmInStream = tmpIn;
        mmOutStream = tmpOut;
    }
    StringBuffer sbb = new StringBuffer();
    public void run() {

        byte[] buffer;  // buffer store for the stream
        int bytes; // bytes returned from read()

        // Keep listening to the InputStream until an exception occurs
        while (true) {
            try {
                try {
                    sleep(30);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

                buffer = new byte[1024];
                // Read from the InputStream
                bytes = mmInStream.read(buffer);
                // Send the obtained bytes to the UI activity
                mHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer).sendToTarget();
            } catch (IOException e) {
                break;
            }
        }
    }

    /* Call this from the main activity to send data to the remote device */
    public void write(String income) {

        try {
            mmOutStream.write(income.getBytes());
            for(int i=0;i<income.getBytes().length;i++)
            Log.v("outStream"+Integer.toString(i),Character.toString((char)(Integer.parseInt(Byte.toString(income.getBytes()[i])))));
            try {
                Thread.sleep(20);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        } catch (IOException e) { }
    }

    public void write_1(byte[] bytes) {
        try {
            mmOutStream.write(bytes);
            try{
                Thread.sleep(20);
            }catch(InterruptedException e){
                e.printStackTrace();
            }
        } catch (IOException e) { }
    }

    /* Call this from the main activity to shutdown the connection */
    public void cancel() {
        try {
            mmSocket.close();
        } catch (IOException e) { }
    }
}

}

code arduino
float nhietdo,doam,nhietdotb,doamtb;
float t,p;
char re;
char p1,p2;
int chanlaynhiet=0;
int pwm,pwm1;
String nhan,nhan1;
boolean batdau = false;
void setup()
{
 Serial.begin(9600);
 pinMode(10,OUTPUT);
 pinMode(11,OUTPUT);
 pinMode(8,OUTPUT);
 }

void loop()
{
if(Serial.available()>0){
 re = Serial.read();
 switch(re){
 case 'S':
 Send();
 digitalWrite(8,LOW);
 break;

  case 'A':
  nhan=Serial.read();
  //digitalWrite(8,LOW);
  break;

  case 'B':
  nhan1=Serial.read();
  //digitalWrite(8,LOW);
   break;

  case 'E' :
  batdau = true;
  break;

  case 'Q':
  batdau = false;
  break;
 }
  if(batdau){
   start();
   }
}

void start()
{
 while(1)
 {//doc ppm
   for(int i=0;i<10;i++)
   {
   nhietdotb=nhietdotb+analogRead(A0);
   delay(1);
   }
   nhietdo=nhietdotb/10;
   nhietdotb=0;
   //doc ph
   for(int j=0;j<10;j++)
   {
  doamtb=doamtb+analogRead(A1);
  delay(1);
   }
  doam=doamtb/10;
  doamtb=0;
 //if (isDigit(pwm1))
 //analogWrite(10,pwm1);
 //if (isDigit(pwm2))
 //analogWrite(11,pwm2);
 analogWrite(11,nhan1.toInt);
 analogWrite(10,nhan.toInt);
 digitalWrite(8,HIGH);

 if(Serial.available()>0)
 return;
}
}

void Send()
 {
  Serial.print('s');
  Serial.print('Y');
   if((nhietdo<1000)&&(nhietdo>=100)){
   Serial.print("0");
   }else if((nhietdo<100)&&(nhietdo>=10)){
   Serial.print("00");
   }else if(nhietdo<10){
   Serial.print("000");
  }
   Serial.print(nhietdo,0);

if((doam<1000)&&(doam>=100)){
  Serial.print("0");
  }else if((doam<100)&&(doam>=10)){
  Serial.print("00");
  }else if(doam<10){
  Serial.print("000");
 }
 Serial.print(doam,0);
 Serial.print('X');
 Serial.print(nhan);
 Serial.print(nhan1);
}

Can you post your Arduino code please, it may help locating the problem. Some more information on your set-up would also be useful. What Bluetooth module are you using?

i am using module HC-05 and board arduino Uno R3.

Your issue is probably this code (and similar) in the Android MainActivity:
x = Integer.toString(u);
Bluetooth.connectedThread.write(x);

Remember that you are sending bytes, not ascii representations of them.  For example, if the variable 'u' is 9, you would be sending the value 57.  The larger problem is that if 'u' is 10 or higher, you are sending more than one byte, and the code below...
case 'A':
    nhan=Serial.read();
    //digitalWrite(8,LOW);
    break;

...only reads one byte of the number.  A better way to approach this is to always send your data in a packet - start each packet with a control or attention byte (255 is a good one), a command for your select, and as many bytes as you need for the data.  Then always send and read a complete packet.
Arduino code:
//Defines make your code more readable.
#define PACKET_SIZE 3
#define CONTROL_BYTE 255
#define WHATEVER_A_MEANS 65
#define WHATEVER_B_MEANS 66

//...

void loop()
{
    byte buffer[PACKET_SIZE];

    if (Serial.available() >= PACKET_SIZE)
    {
        // Read the first byte
        buffer[0] = Serial.read();
        // If it's really the start byte (255) ...
        if (buffer[0] == CONTROL_BYTE)
        {
            // ... then get the next two bytes
            for (i = 1; i < PACKET_SIZE; i++) buffer[i] = Serial.read();
        }
        else
        {
            //Otherwise it isn't a good packet.
            return;
        }

        switch (buffer[1])
        {
            case WHATEVER_A_MEANS:
                nhan = buffer[2];
                break;
            case WHATEVER_B_MEANS:
                nhan1 = buffer[2];
                    break;
            //etc.
        }

        //...

Android code:
//Class level scope. Note that these don't have to be 'letters' unless you
//need them to be for some other reason.
public static final byte CONTROL_BYTE = (byte)255;
public static final byte WHATEVER_A_MEANS = (byte)65;
public static final byte WHATEVER_B_MEANS = (byte)66;

//...
public void doTimerTask() {
    mTimerTask = new TimerTask() {
        public void run() {
            thandler.post(new Runnable() {
                public void run() {
                    Bluetooth.connectedThread.write(CONTROL_BYTE);
                    Bluetooth.connectedThread.write(WHATEVER_A_MEANS);
                    //Note that this is a narrowing cast of u.
                    Bluetooth.connectedThread.write((byte)u);

If 'u' needs to hold values bigger than 8 bits (you have it declared as an int), you'll need to split it into bytes and then recombine them in the Arduino code.

sr,
Arduino code
float nhietdo,doam,nhietdotb,doamtb;
float t,p;
char re;
char p1,p2;
int chanlaynhiet=0;
int pwm,pwm1;
String nhan,nhan1;
boolean batdau = false;
void setup()
{
  Serial.begin(9600);
  pinMode(10,OUTPUT);
  pinMode(11,OUTPUT);
  pinMode(8,OUTPUT);
}
void loop()
{
if(Serial.available()>0){
re = Serial.read();
switch(re){
  case 'S':
  Send();
  digitalWrite(8,LOW);
  break;

  case 'A':
  nhan=Serial.read();
//      digitalWrite(8,LOW);
      break;

      case 'B':
      nhan1=Serial.read();
//      digitalWrite(8,LOW);
       break;

      case 'E' :
      batdau = true;
      break;

      case 'Q':
      batdau = false;
      break;
    }
    if(batdau){
     start();
    }
  }

void start()
{
  while(1)
  {//doc ppm
    for(int i=0;i<10;i++)
    {
    nhietdotb=nhietdotb+analogRead(A0);
    delay(1);
    }
    nhietdo=nhietdotb/10;
    nhietdotb=0;
    //doc ph
    for(int j=0;j<10;j++)
    {
   doamtb=doamtb+analogRead(A1);
   delay(1);
    }
   doam=doamtb/10;
   doamtb=0;
//    if (isDigit(pwm1))
//   analogWrite(10,pwm1);
//   if (isDigit(pwm2))
//   analogWrite(11,pwm2);
   analogWrite(11,nhan1.toInt);
   analogWrite(10,nhan.toInt);
   digitalWrite(8,HIGH);

   if(Serial.available()>0)
   return;
}
}

void Send()
{
   Serial.print('s');
   Serial.print('Y');
   if((nhietdo<1000)&&(nhietdo>=100)){
   Serial.print("0");
   }else if((nhietdo<100)&&(nhietdo>=10)){
   Serial.print("00");
   }else if(nhietdo<10){
   Serial.print("000");
  }
   Serial.print(nhietdo,0);

   if((doam<1000)&&(doam>=100)){
  Serial.print("0");
  }else if((doam<100)&&(doam>=10)){
  Serial.print("00");
  }else if(doam<10){
  Serial.print("000");
 }
 Serial.print(doam,0);
 Serial.print('X');
 Serial.print(nhan);
 Serial.print(nhan1);
}

You shouldn't post this as an answer to the question, instead you should edit your question to include the code above.

As Cominterm said, you are doing a lot of mistakes. I would use start and end bytes like:
HEX       ASCII

31 3B  |  "1;" -start of the message

3F 30  |  "?0" - end of message

And in arduino check for them.
Also a tip, if you read bytes i would get rid of those 'A', 'S' and so on. These are ascii codes. You can easily do a mistake and this will be pain in the ass. Send byte 10 from Android and read as byte 138 in Arduino, because in Java byte is -127 : 128 and Arduino 0 : 255
I would do in hex representation, this helps in troubleshooting. For ex.: byte 1C hex in Android is 1C hex in Arduino.
Also get rid of those byte to string, int to string conversations. They add more points to mistake :) Also check if string is terminated with \0 and it will be 2 bytes instead of 1.


text:
How to compile and upload the specific (.cpp + .h) code?
I have a specific arduino code (no .ino files) https://github.com/justintconroy/MdbBillValidator , which can't be opened by arduino IDE. How can I make & upload this code? I have an arduino 2560 mega.
I've created an empty MdbBillValidator.ino file and added these lines:
#include "MdbBillValidator.h"

void setup() {

}

void loop() {

}

Here is the error message
MdbSerial.cpp: In function ‘void __vector_37()’:
MdbSerial.cpp:289:23: error: ‘TXB8’ was not declared in this scope
MdbSerial.cpp:291:24: error: ‘TXB8’ was not declared in this scope
MdbSerial.cpp: In function ‘void __vector_52()’:
MdbSerial.cpp:314:23: error: ‘TXB8’ was not declared in this scope
MdbSerial.cpp:316:24: error: ‘TXB8’ was not declared in this scope
MdbSerial.cpp: In function ‘void __vector_55()’:
MdbSerial.cpp:339:23: error: ‘TXB8’ was not declared in this scope
MdbSerial.cpp:341:24: error: ‘TXB8’ was not declared in this scope
MdbSerial.cpp: At global scope:
MdbSerial.cpp:554:135: error: expected ‘)’ before numeric constant
MdbSerial.cpp:554:189: error: no matching function for call to ‘MdbSerial::MdbSerial(ring_buffer*, ring_buffer*, volatile uint8_t*, volatile uint8_t*, volatile uint8_t*, volatile uint8_t*, volatile uint8_t*, volatile uint8_t*, int, int, int, int, int, int, int, int, int, int, int)’
MdbSerial.cpp:554:189: note: candidates are:
MdbSerial.cpp:352:1: note: MdbSerial::MdbSerial(ring_buffer*, ring_buffer*, volatile uint8_t*, volatile uint8_t*, volatile uint8_t*, volatile uint8_t*, volatile uint8_t*, volatile uint8_t*, uint8_t, uint8_t, uint8_t, uint8_t, uint8_t, uint8_t, uint8_t, uint8_t, uint8_t, uint8_t, uint8_t, uint8_t)
MdbSerial.cpp:352:1: note:   candidate expects 20 arguments, 19 provided
In file included from MdbSerial.cpp:38:0:
MdbSerial.h:52:7: note: MdbSerial::MdbSerial(const MdbSerial&)
MdbSerial.h:52:7: note:   candidate expects 1 argument, 19 provided

That's a library. You can't just run that code. You can create a new sketch, and place these files in this new sketch's folder. Then #include it inside the ino file.

Hm!
Okay, I'll try to do that!

@Gerben which files should I include?

I think #include "MdbBillValidator.h"

don't work. compilation error

Let me get my crystal ball, to see the error message.

Oh, I've added it. Pls review the question again. Any ideas?

What folder are the library files living in? How many files from that repository did you download, and what folder do they live in? All the error report is telling me is that the library can't find the files it depends on.

I've cloned a file to the directory, and create an MdbBillValidator.ino (as the name of the directory)

The problem is that I need to import this code just a simple usual library.

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


text:
SoftwareSerial Struggles
Just trying to understand and use the SoftwareSerial
I want to connect a WiFi Module (ESP8266)
If I send an AT command to the module I would like to print a response on my pc screen in the serial monitor
Some example code it tried
   SoftwareSerial dbgSerial(10, 11); // RX, TX
   void setup()
   {
     // Open serial communications and wait for port to open:
     Serial.begin(57600);
     Serial.setTimeout(5000);
     dbgSerial.begin(9600); //can't be faster than 19200 for softserial
     dbgSerial.println("ESP8266 Demo");
     //test if the module is ready
     Serial.println("AT+RST");
     delay(1000);
     if(Serial.find("ready"))
     {
       dbgSerial.println("Module is ready");

I would like to receive ready in the serial

Looks like you are swapping the use of Serial and dbgSerial. I think you mean to use Serial to print to the computer and dbgSerial to communicate with your module. Serial.println should display the message in the terminal on your computer.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
Obfuscate .hex file
I've wrote a code for arduino mega, and want to force it from copying (this is commerce project). How can I obfuscate .hex file before uploading to arduino?

I think you are looking for something like this


text:
How to have an Arduino communicate with 3 other Arduinos?
I was wondering how I can get 4 Arduinos in total to communicate with each-other through a wired connection. The goal is to have the master Arduino send a number 0-100 to each of the other Arduinos.
The master unit will be an Arduino Uno and the other 3 Arduinos will be Arduino Pro Minis.

There are lots of ways. You're going to need to be more specific about your requirements.

how to communicate multiple ardunio wirelessly??

@SHAUKATALIKHAN  lookup NRF24L01 with radionics

You could use: U(S)ART, I²C or SPI. You should check this post for information on these protocols.
Some quick googling gave me this:

SPI: mainly for high data rates, approx 25 MHz clock but only bus has to be on same voltage level, single master (can be done through software), data arbitration not possible.
I2C: mainly for control and low data transfer (limited by bus capacity, etc...), but can be interfaced to different voltage levels and multimaster bus environment, inbuilt arbitration etc...
UART: single P2P comm, 115 kbps max.

http://www.edaboard.com/thread53139.html
I don't fully agree with it. You can send via UART to multiple devices, but then you have to handle the addressing in software. But other than that, UART is very easy to debug as Arduinos often have an USB connection.
"I²C is somewhat complicated at the physical level, but all that complication is handled by the hardware (the TWI interface of the AVR chips). At the user level, it may be the simplest to use". I don't yet have a lot of experience with this protocol, but if you want to use it, check out the other answer.
SPI would be a fair shot as it does enable master with multiple slaves in its standard.
Summary:
All protocols have different pros and cons. It's not really up to us to choose one for you. And you should look them up and learn about them by yourself.
Then try to choose which one applies most to your needs, and get started with that protocol. They are well documented and if you really can't get out of it, you can post another question ;D

I²C is somewhat complicated at the physical level, but all that complication is handled by the hardware (the TWI interface of the AVR chips). At the user level, it may be the simplest to use: only two wires and no need to match port configurations (baudrate, parity, stop bit(s)...).

Ah, I see, haven't yet used I²C with arduino, but for a beginner, but in general it's better to know the hardware before you start on the software. In this way you know what to do and how to debug it. But I can imagine that arduino has steady/easy libraries for this. But same is for setting up serial connection in arduino?

UARTs don't need to be single P2P; AVRs do support a form of multiple slave using a 9-bit protocol.

I also said that in the 3rd 'paragraph', though adressing isn't standard in the uart protocol? Or well you will have to handle it software. With SPI you simply have a slave select pin that selects which slave to talk to.
I didn't know that 9-bit protocol is for adressing? Or well I don't believe it's defined so in the standard? But yes, an extra bit could help.
You could also send one byte with the address/setting and then send (an)other byte(s) with the message. Then on each slave you should check the first byte, and only handle the second when neccesary.

I agree knowing the physical layer can help, but for using I²C you only need to know that addresses and data are multiplexed on the same lines, which simplifies the cabling (only 2 wires). On the software side, it's really simple: see the Master Writer/Slave Receiver Arduino tutorial, which can be trivially expanded to many slaves just by using different slave addresses.

You can use the I2C communication protocol through the wire.h library. That will permit you to use the arduino uno as master device and the pro minis as slave.
Briefly, you use a two wire's connected to the SDA and SCL pins of all the arduino board and then the master to interact ( meaning request data and send data) with the slaves uses there address (that is user defined in the slave software). So the normal routine in I2C goes like this:

The master sends the address plus the read write instruction on the bus.
All the arduino boards listen and if the address matches with there internal adress they perform the instruction.
If it is write command from the master the slaves prepare to receive. If it is read command from the master, the master waits until the slave send a byte.

Fr more information go on:
Arduino two wire communication
I2C official datasheet

And you are probably using I2C already to interface with sensors, displays and other components. I

You can use RS-485 connection between all arduinos using serial port of all. For a half duplex connection for 4 arduinos, the setup can be like this:
What Do You Need:

4 RS-485 line drivers (like max485). One for each arduino
if the distance between arduinos are short (under 1 mt) these will br enough
if the distance between arduinos are long (over 2mt) you'll need to use at least 24 AWG twisted pair cable between them and 2 120 ohm resistors. These resistors will be line terminators.
You can check max485 datasheet to see how to connect them

Setting Up:
To use rs485 with arduino and half duplex, you'll need 3 pins. 2 pins for rx and tx. 1 pin for transmit-enable. In half duplex mode, normally all nodes are in listening mode. To configure transmit enable, connect "drive enable" and "receive enable" pins of rs485 driver together. This will be our "transmit-enable" pin.
Connection:
      |        |
c  RX |------->|RO     4
p  TX |------->|DI     8
u D13 |------->|TE&RE^ 5
      |        |

Software:
Download this library (Mertbus). This library implements a basic transport layer. It is in alpha stage but functional. There is sample code in it and also a .net library.
The logic is similar to TCP/IP. Give every node an address between 0 and 126. 127 is the broadcast id. Means if you send data to id 127 all nodes will receive it. If you send data to only one node (ex. 2 ...) only target node will receive.
Sample:
#include "MertBus.h" //include header

#define TXEN 13  //transmit-enable pin
#define SELF_ID 1  //id of this node

MertBus mb;  //communicator class

void setup() {
   Serial.begin(57600); //prepare the serial port as usual
   Serial.println("Begin init");
   //then initialize mertbus instance with port, pin and id
   mb = MertBus(Serial,TXEN,SELF_ID);
}

void loop() {
  if(mb.checkData()) {    //check if and valid data received
    // reply to sender char[] and length, 26 chars
    mb.reply("Incoming Data (SendData): ",26);
    // reply to sender the received data
    mb.reply(mb.Buffer,mb.ReceiveCount);
  } else {
    digitalWrite(13,HIGH);
    delay(400);
    digitalWrite(13,LOW);
    delay(400);
  }
}

To be a master, to send data (without replying to a message, starting a new one):
//buffer data to send, to_addr is target node address
//buffer_size is the size of data to send.
mb.sendData(char * buffer, uint8_t to_addr, uint8_t buffer_size)

If they are reasonably close to each other, by far the simplest would be to use serial comms, since you say you want to send a number (but do not mention receiving anything).
You could have the Tx pin on the master Arduino connected to the Rx pin of all the other Arduinos (plus a ground connection of course). Then send your numbers to your heart's delight. I suggest some sort of protocol like:
(42)

Where the opening and closing braces indicate to the receiver where the number starts and ends. If the distance is more than (say) 5 meters, an RS485 transceiver may be called for at each end, eg.

I have a description of the sort of thing on my RS485 communications page.
You can "drop" multiple transceivers off the same pair of cables.
RS485 is reasonably resistant to line noise because it is a balanced protocol.
These transceivers can transmit or receive but not at the same time. In your case you would have the master with Tx Enable active, and the slaves the Tx Enable not active.
If the chips are dropped off a long cable run you should have a termination resistor between A and /B at the end (say, 120 Ω).
SPI could be OK, but is really for short runs. I2C could be OK too, but may be unnecessarily complex. However if you go with I2C it does have a "broadcast" mode which might suit sending the same thing to multiple devices.

References

RS485 communications
RS485 - Wikipedia
I2C (Wire)
SPI
Async serial

Nick, what did you use to generate those circuit diagrams?

ExpressSCH from expresspcb.com. It's free software for Windows that draws schematics and PCBs. It's simple to use (which is why I like it). It has a library of major parts, plus you can make your own out of boxes and lines.

PJON is a bit banged serial bus protocol for multiple nodes. You may find it useful.

PJON™ (Padded Jittering Operative Network) is an Arduino compatible,
  multi-master, multi-media communications bus system. It proposes a
  Standard, it is designed as a framework and implements a totally
  software emulated network protocol stack that can be easily
  cross-compiled on many architectures like ATtiny, ATmega, ESP8266,
  Teensy, Raspberry Pi, Linux and Windows x86 machines. It is a valid
  tool to quickly and comprehensibly build a network of devices


text:
Wifi module for arduino shield
Recently I bought a B006RATC2E wireless shield for my Arduino One, but didn't notice that I had to buy a wifi module as well to let it work (bad surprise as the shield already cost me $30 + travel expenses to CR). Could someone be so kind to suggest me some compatible wifi modules for the shield?
I'm kind of newbie in this and when I search specs for Adafruit and XBee modules, the documentation is not explicit about the compatibility with Arduino shields, so I'm stuck.
I don't want to buy components that would't work together (my budget is limited). Is XBee XB24 a good module for the shield? Any other alternative?
Thanks in advance for any help!

Wireless doesn't necessarily mean it's WiFi.
You should get an XBee module that explicitly states that it's a WiFi module.
For a cheaper alternative you can check ESP8266 WiFi modules, which you can get for $5.

That definitely helped me, along with this tutorial: http://www.cse.dmu.ac.uk/~sexton/ESP8266, thanks gre_gor! And the best, I don't need a wireless shield to get WiFi


text:
Conflicts with USB and external power supply
I want to power an Arduino Leonardo with an external power supply and simultanously communicate via USB. I have read some other threads on this topic, therefore, I know that if one supplies more than 7V over the power jack, the board will use the external power supply in this case.
My suspicion is rather concerning the ground connection. From the schematic, I can tell that the USB ground is connected via a tiny coil to the board ground, so with DC it is shorted. Wouldn't that cause problems if the computer's USB ground is at a different potential than the external power supply of the board, resulting in a voltage between the two grounds? What if this voltage is up to several Volts?
Thanks a lot!

USB is mains earth references (except for laptops). You other power supply is either also main-earth references, or floating. In either case no current will flow. That's the way I understand it. Either way, everybody does it this way, so it's not a problem..

Why do you suspect a potential difference? Where is th 7V coming from? If the 7V power supply is free floating and used for nothing else, there is no source for potential difference.
A typical wall wart will have a free floating output.

I intend to use the power supply of another PC. Are these ground potentials always guaranteed to be connected to Earth?

Connect the grounds of the two PC together, then they will be.

@Dawamaha or, if you want to be 100% sure, use a multimeter...

When you connect the USB, you also connect the ground of the computer to he arduino board. And then when the external power supply is connected to the arduino board the negative pin or the ground pin coming from the external power supply is connected to the ground pin of the USB. Thus the external power supply and the PC share the same ground.

I am going to clear one thing, many students and hobbyists are still confused and think that their Arduino board will blow away if they use the External power supply at the same time when Arduino board is connected to the pc through USB cable. This statement is totally wrong, you can give power to the Arduino board by using both sources at the same time and Arduino board is intelligent device it will choose the best input power having more current as compared to the other one.

It's actually a choice of whether or not the voltage from the power jack exceeds 7.3V. This is because there is a MOSFET on the board that chooses USB input if Vin exceeds 6.6V (a voltage divider lets it compare the output of the 3.3V voltage regulator to that). Since Vin is on the other side of a protection diode which drops 0.7V, then you need to put 7.3V or more into the input jack for it to switch to using that.

To answer your question:  I have never seen a conflict like that.
I power my Unos with CCTV-style power supplies (12V) when I am using the HC-11 Wireless module which requires 100 mA or more in order to communicate.
When powered on just USB they can't talk at all.  I mean, not at all - like you simply can't make them work until you plug in the second power supply to get more current.
Everything in the board is grounded together, and that it 99% of the battle when using two power supplies.  Whether I am programming from a Raspberry Pi or a laptop, it all works the same.


text:
How do I send an IR signal from an Arduino
I want to send a generic (not Sony, etc.) remote's signal from my Arduino.  I have already used a IR decoder program to capture the timing of the signal:
int IRsignal[] = {
// ON, OFF (in 10's of microseconds)
    88, 88,
    174, 88,
    86, 86,
    88, 86,
    88, 88,
    86, 86,
    88, 174,
    86, 88,
    86, 88,
    174, 174,
    86, 88,
    86, 2252,
    88, 88,
    174, 88,
    86, 86,
    88, 88,
    86, 88,
    86, 86,
    86, 176,
    86, 88,
    86, 88,
    174, 174,
    86, 88,
    86, 0};

Now I need to send this through the IR LED.  I have never written a program that can modulate a signal at this microsecond level.  How would I do this?

Use a library, like IRremote. Otherwise, you have to setup one of the pwm-timers to generate a 38kHz frequency, and then turn on and off this pwm based on the values you have captured above.

Use the IRRemote library as mentioned and use the IRecord example.  This will allow you to input a signal and then push a button which will send that signal from the infra-red LED on the arduino.

Please, take a look at Ken Shirrif's  IRRemote library, as it is what you need. I used it in some project and worked better than other solutions that I coded.

I think that this is the one I am using, I am having a hard time finding good documentation for 'generic' IR signals (or RAW signals)


text:
Arduino Board with Microphone
I have this microphone (http://www.digikey.com/product-detail/en/CMA-4544PF-W/102-1721-ND/1869981) and an Arduino Uno board. I'm trying to read audio values off of my microphone (to test the noise of something (in dB)). I'm very new at this kind of stuff so keeping it simple would really help me out! I have a bunch of different capacitors, LM386N op amps, a bread board, and many resistors. Could someone provide a code and schematic that could help me get data off of my mic? I've tried using this schematic: http://wiring.org.co/learning/basics/microphone.html
but couldn't get the code to download onto a Wiring S board due to a "timeout" error and it not being able to "connect with the programmer".
Any and all help would be much appreciated!!

You can use Maxim MAX4466 op-amp which works very well with Arduino. There is a breakout available for the same for arduino at Adafruit here. The chip has a select-able gain from 25x-125x. This amplifies works very well to get a nice waveform for audible noise. There are a couple of libraries available for the waveform that you record and can translate it to frequencies. You can also use it to distort or change the voice. Here is a schematic of the circuit if you want to make one yourself.

Very interesting stuff. As you are new to this kind of stuff i can suggest you, instead of explaining ( because videos are cool), to watch this video that explains very clearly how to use the lm386 with some filters. That video is a project about controlling the arduino through whistling. Hope that helped.

The LM386 is an amplifier that is meant to drive a speaker. What you're looking for is a preamplifier, like the TL072 (cheap) for example, which is meant to amplify a microphone.
Most decent preamps require more than 5V. The OPA2134 is a more expensive opamp that can run off 5V. There are others but not all readily available and cheap.
Now if it's just for fun there is no need to be too fussy. Probably that's why in the arduino world you'll find many examples of people using LM358 and LM386 as microphone preamps.
What you probably don't want to hear is to look in the manuals. But actually in those manuals you find example schematics for all the different use cases. And you'll find the amplifier use case in there too for lm386: on page 11 and 12. That's what you are looking for. To start.
Next you need to bias the output to +2.5V. You do this with a voltage divider. Two registers of say 100k back to back from your arduino 5V vcc output to GND. They 'divide the 5V between them' giving you 2.5V in the middle. That's where you connect the output of your opamp and also one of the analog input pins, say A0.
Be aware that you should start with a small(er) amplification factor. Because amplifying your microphone voltage above 5V peek to peek would fry your arduino pin.

There is an Ap called Db, it works great on my iphone. I have had it a long time. I think it was $0.99 at the time.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Use pointer in calculation results in error
I'm building a project to measure/track flyball dog races.
The dogs timings are measured by photoelectric sensors at the start/finish line of the racing lane.
I have most of my code working (available on github) but I'm having some difficulties in handling very short crossings of dogs. Since I cannot realistically run a real race at home next to my development machine :-), I'm trying to build a simulator class which gives the triggers that would normally come from my photoelectric sensors.
I have a RaceHandler class which has the following in its header file:
class RaceHandlerClass
{
 public:
   long* lRaceStartTime = &_lRaceStartTime;

 private:
   long _lRaceStartTime;
}
extern RaceHandlerClass RaceHandler;

As you can see I made a public pointer lRaceStartTime which points to the private _lRaceStartTime member variable.
This might seem stupid/strange, but it really should a private member variable, I just want to 'temporarily' make it publicly available, so that I can use it in a temporary 'simulator' class to simulate a race towards my code.
Then I want to use this public pointer in the Simulator class like so:
long* lRaceStartTime = RaceHandler.lRaceStartTime;
long lRaceElapsedTime = micros() - lRaceStartTime;

However I get the following error when trying to compile this:

error: invalid operands of types 'long unsigned int' and 'long int*'
  to binary 'operator-'

I'm afraid my c++ knowledge ends here and I have no clue what I should do different to fix this...
Any help would be greatly appreciated!

Since I cannot realistically run a real race at home next to my development machine - how about mice?

Try this:
long* lRaceStartTime = RaceHandler.lRaceStartTime;
long lRaceElapsedTime = micros() - *lRaceStartTime;

You assigned the pointer to lRaceStartTime on the first line, but on the second line you are subtracting the pointer from micros() which returns an unsigned long.  You need to dereference the pointer before subtracting. Also you might consider making all your longs unsigned to match the return type of micros() http://arduino.cc/en/reference/micros

Thanks, this indeed solved my problem. Guess I need a little more practice with pointers...

No worries, happy to help.  Feel free to post more questions, this site needs to get out of beta!

I realise your question was but a simple query on syntax. But I would like to point out that the whole idea of object orientation is encapsulating functions and data so that external calls do not have to know about the internal-workings of that class.
It's common with object oriented programming to use 'getters' and 'setters' to modify private member-variables of the class. You really should not be giving a pointer to a private member. If you need to read/write it, add a setter function.
class RaceHandler
{
public:
    void setStartTime()
    {
        race_start_time = micros();
    }

    void setStartTime(unsigned long start_time)
    {
        race_start_time = start_time;
    }

    unsigned long getStartTime()
    {
        return race_start_time;
    }

    unsigned long getElapsedRaceTime()
    {
        return micros() - race_start_time;
        // TODO: handle overflow of micros() after ~72 minutes
        // maybe use millis() instead
    }

private:
    unsigned long race_start_time;
}

Obviously this is laborious.  Some languages have special support for getters and setters to provide the functionality with less syntax.
Time is always positive, use an unsigned long.  As people have already said, millis() & micros() return an unsigned long too.
RaceHandler race1;

race1.setStartTime();

[...]

unsigned long elapsed_time = race1.getElapsedRaceTime();

Time is always positive, use an unsigned long. - whilst this is quite true on the Arduino, I recently discovered that time_t is typedef'd to signed integer. In other words, you can represent times before 1st January 1970 by using negative numbers. Of course, this doesn't apply on the Arduino, as the concept of millis() returning time before the system was reset doesn't make a lot of sense.

@Nick Gammon - Yep, time_t is signed.  We've got until 2038 to sort that out ;)

Which is getting increasingly close. :)


text:
How to calculate phase shift between two square waveforms with Arduino DUE
I have two square wave signals with the same frequency. I want to measure the phase shift between these two signals. There will be a small phase difference between two signals. (0-90 degree) and the frequency will vary in the range 100mHz - 50kHz. I am using an Arduino DUE (ATMEL ATSAM3X8E AU ,ARM)
I tried to use "micros()" for timer functionality to get 2 different times and then calculate the phase shift using the following code:
int led=47,count1=0,count2=0,temp=0;
int i=0,j=0;
float time1[3]={0,0};
float time2[3]={0,0};
float freq1=0,freq2=0;
float period1=0,period2=0;
float ps=0;

void setup()
{
      Serial.begin(9600);
      Serial.println();
       Serial.println();
      pinMode(31,INPUT);
      pinMode(33,INPUT);
      pinMode(led,OUTPUT);
      digitalWrite(led,HIGH);
      noInterrupts();
      attachInterrupt(31,in1,RISING);
      attachInterrupt(33,in2,RISING);
      interrupts();
}

void in1()
{      noInterrupts();
       switch(i){
           case 0 : time1[i]=micros(); i++;  break;
           case 1 : if(j==1){time1[i]=micros(); i++; break;}
       }
       interrupts();
}
void in2()
{      noInterrupts();
       switch(j){
            case 0 : if(i==1){time2[j]=micros(); j++; break;}
            case 1 : if(i==2){time2[j]=micros(); j++; break;}
       }
           if(j==2){
             period1 = (time1[1]-time1[0]);
             period2 = (time2[1]-time2[0]);
             freq1 = 1000.0/period1;
             freq2 = 1000.0/period2;
             ps = (((time2[1]-time1[1])*360.0)s/period1);
          if(freq1==freq2){
          Serial.println("");
          Serial.print("TIME1[0] = ");
          Serial.print(time1[0],6);
          Serial.print("\t TIME1[1] = ");
          Serial.print(time1[1],6);
          Serial.print("\t DEL1 = ");
          Serial.println(time1[1]-time1[0],6);
          Serial.print("TIME2[0] = ");
          Serial.print(time2[0],6);
          Serial.print("\t TIME2[1] = ");
          Serial.print(time2[1],6);
          Serial.print("\t DEL2 = ");
          Serial.println(time2[1]-time2[0],6);
          Serial.print("\t x = ");
          Serial.print(time2[0]-time1[0],6);
          Serial.print("period1(ms) = ");
          Serial.print(period1,6);
          Serial.print("\t period2(ms) = ");
          Serial.println(period2,6);
          Serial.print("freq1 = ");
          Serial.print(freq1,6);
          Serial.print("\t freq2 = ");
          Serial.print(freq2,6);
          Serial.print("\t Phase Shift = ");
          Serial.println(ps,6);
          }
          else {
          i=0;j=0;
          interrupts();
          }
       }
       interrupts();
}
void loop()
{
       ;
}

When I run this code I am not getting any errors, but in high frequency (above 400 Hz) Ihave a problem. When I tested at 0 degrees, this code produced this output:
400 Hz 1.152 degree
500 Hz 1.440 degree
600 Hz 1.727 degree
700 Hz 2.015 degree
800 Hz 2.304 degree
900 Hz 2.592 degree
1 kHz  2.880 degree
2 kHz  5.760 degree
3 kHz  8.649 degree
.
.
.
10 kHz 28.8 degree

Each frequency has lowest degree that this code can calculate.
How can I fix this code? Is it possible to calculate the phase shift between two square wave signals this way?

First make sure you limit the data sent to the serial port inside your ISR when the interrupts are disabled. At 9600 baud it takes 1ms to send one byte over the serial link.

@Alex the Due might have hardware serial, which is dealt with asynchronously by the hardware UART/USB. The Due is a powerful Cortex M3 I doubt there is any processing issue there..

chaya have you looked at an oscilloscope and seen if the numbers are correct, or even close at all?

chaya your output doesn't match the strings shown in the code, where are the lines showing "period" and "phase shift"?

@KyranF. I understand the asynch part but it still takes 1ms per byte. The only thing that can help here is buffering (FIFO) but eventually you will run out of buffer space anyway.

The best solution would be to just capture time in ISR1 and ISR2. And then subtract the values and display the difference in the main loop at a slower speed. Obviously you may miss a few samples every now and then.

With 0° you have two inputs triggering interrupts at the same time.  That can't happen.  You can't run two interrupts at the same time, so the second one gets queued up until the first has finished.
With all that serial printing in there there's going to be quite a delay between one interrupt triggering and the next one being allowed to trigger - giving you skewed results.
I would suggest passing your signal through an XOR gate so that you end up with a single small pulse that represents the phase shift between the two signals.

XOR won't tell you which one happens first

You could look at A XOR B to get the length of the pulse and A to figure out which one came first.

I agree. XOR would be nice plus using a timer in capture mode. It's still fishy when you get close to 0°.

You could implement a phase detector (e.g. Type 2) and filter (charge pump) to produce a voltage proportional to phase. A type-2 PD would be sensitive to neg or pos phase shift.

Even if your code worked perfectly, with zero processing latency, you still are working with a timer resolution of only 1 microsecond.  If I did my math correctly, that means at 50 kHz, the smallest phase difference you can detect is around 18 degrees.  At 100 MHz, 1 microsecond is 100 complete cycles.  You probably want to look into hardware specifically designed for phase detection.

That's "mHz" (small m) -- millihertz, not megahertz.

Oops.  Well, the 50 kHz limit still applies.  He didn't specify his needed precision, but one degree precision would limit you to 2.7 kHz.

I think you can at least get a lot closer with the Due as in my answer, although I'm not sure if 50kHz is reachable. Using a 42MHz timebase gives just barely enough resolution, and 20us per cycle is just enough to get some calculation done. The most obvious problem is that the serial can't possibly send 50,000 reports per second, so there would have to be some aggregation/decimation there!

Good point, @hobbs.  I should be more explicit that my limit is referring to the OP's code that uses the micros() function to do the timing.  Using the timer directly can get you better resolution.

Connect the two signals to the TIOA pins of two different timer/counter channels on the same timer/counter block (either TIOA0 and TIOA1, which are Arduino pins 2 and A7, or any two of TIOA6, TIOA7, and TIOA8, which are Arduino pins 5, 3, and 11, respectively).
Set the two timer channels to capture mode, "up" counting, and internal clocking at the fastest rate that seems appropriate (I don't see any reason not to use TIMER_CLOCK1 = 42MHz on the Due). Set them both to load RA on rising edge of TIOA, and RB on falling edge. Assuming TIOA0 and 1:
pmc_enable_periph_clk(ID_TC0);
TC_Configure(TC0, 0,
    TC_CMR_TCCLKS_TIMER1 |
    TC_CMR_WAVSEL_UP |
    TC_CMR_LDRA_RISING |
    TC_CMR_LDRB_FALLING
);

pmc_enable_periph_clk(ID_TC1);
TC_Configure(TC0, 1,
    TC_CMR_TCCLKS_TIMER1 |
    TC_CMR_WAVSEL_UP |
    TC_CMR_LDRA_RISING |
    TC_CMR_LDRB_FALLING
);

Set them both to generate interrupts on RA load:
TC0->TC_CHANNEL[0].TC_IER = TC_IER_LDRAS;
NVIC_EnableIRQ(TC0_IRQn);
TC0->TC_CHANNEL[1].TC_IER = TC_IER_LDRAS;
NVIC_EnableIRQ(TC1_IRQn);

Enable both clocks, and synchronize them so that they're both 0 at the same moment:
TC0->TC_CHANNEL[0].TC_CCR = TC_CCR_CLKEN;
TC0->TC_CHANNEL[1].TC_CCR = TC_CCR_CLKEN;
TC0->TC_BCR = TC_BCR_SYNC;

And handle the interrupts:
void TC0_Handler() {
    uint32_t status = TC0->TC_CHANNEL[0].TC_SR;
    if (status & TC_SR_LDRAS) {
        uint32_t tm = TC0->TC_CHANNEL[0].TC_RA;
        // rising edge of TIOA0 happened at "tm",
        // do something here to deal with it...
    }
}

void TC1_Handler() {
    uint32_t status = TC0->TC_CHANNEL[1].TC_SR;
    if (status & TC_SR_LDRAS) {
        uint32_t tm = TC0->TC_CHANNEL[1].TC_RA;
        // rising edge of TIOA1 happened at "tm",
        // do something here to deal with it...
    }
}

(Just defining functions with those names registers them as interrupt handlers, using weak-symbol magic).
If you choose to use TIOA6/7/8, the clock will be ID_TC6/ID_TC7/ID_TC8, and the EnableIRQ will be TC6_IRQn/TC7_IRQn/TC8_IRQn, but the TC_Configure calls will be TC2, 0 / TC2, 1 / TC2, 2, the SYNC will be issued to TC2, and the register accesses will be to TC2->TC_CHANNEL[0] / TC2->TC_CHANNEL[1] / TC2->TC_CHANNEL[2]. This is due to the way that the channels are grouped into blocks of three in the hardware. This is also why you have to use 0 and 1, or two of 6, 7, and 8; in order to sync the timers they have to be on the same block (and TIOA2 through TIOA5 aren't routed on the Due).
Because the clocks run at MClk/2 = 42MHz, the times you get will be in units of 1/42 microsecond, 42 times better than you get from micros(). Because the timer values are latched into the timer hardware before the interrupt is set, there isn't a problem if the two events come close to each other in time; you'll get the second interrupt after you finish handling the first, and the value in the register will still be valid (as long as you don't take so long that you miss more than one edge).
If you're interested in the falling edges, you can get those as well by setting the TC_IER_LDRBS bits and checking for status & TC_SR_LDRBS in your interrupt handlers.
Final advice: set your serial baud rate higher than 9600 if you can, you'll greatly decrease the amount of time you spend in Serial.print!


text:
Is it problematic to 'check an input pin' or 'set an output pin' each step?
I am using an Arduino in an automation project which will be using a state machine to conduct a one-hour scenario.  Currently, the Arduino reads each input pin, runs its state update script, then sets each update pin.  99.99% of the time, each output pin will be set to the same state that it had in the last step.  Although it is better (in my opinion) to only set the pin when a setting changes, I was wondering if constantly checking and setting pins would have a big negative impact on the hardware?
Would checking a pin's current state (digitalRead or other method) before setting the pin improve anything?

what do you mean by "negative impact"? Are you talking about the speed the application runs? physical wearing of the hardware?

It does not hurt the Arduino to set an output pin to high if it was already set to high.  If you are concerned about performance, it is more efficient to just set the output pin compared to reading the pin and then setting it only if it's different

Would checking a pin's current state (digitalRead or other method)
  before setting the pin improve anything?

So instead of:
SetPin(OUTPUTPIN,true);

You want to do:
if(!PinIsSet(OUTPUTPIN)){
 SetPin(OUTPUTPIN,true):
}

To avoid writing to a pin (making it high) when it's already high/enabled?
Well doing so will waste a little amount of your programs' speed (it'll need to check each pin before setting it). But when you set a pin, when it's already high, it simply doesn't even change. And even then it's not required to check it first, Microcontrollers are basically made for this.


text:
Question regarding powering Arduino through the USB Port
If powering the Arduino (Mega) through the USB port, is a voltage of 5.19VDC acceptable?

Yes, the ATMEGA328 processor will work without any problem, in fact if you go in the power informations section on the datasheet, you will find that the processor can run from a little less of 3V to a maximum of 5.5V.
Just be careful, because the processor works at that power, but the board will need from 5 to 5.5V.

That's the approximate expected voltage. The Arduino devices are typically powered at 5V, but the chips themselves are rated to work at values lower and higher than 5V.

The 5.19V you see, I guess you expect 5.00V, is a combination of power supply tolerance and the tolerance of your voltmeter.
Your voltmeter also has some error, we tend to forget that sometimes.


text:
Control Speed of DC FAN Using Arduino PID Library
I want to make a circuit that control speed of DC fan Using Arduino PID Library to get thing at specific temperature.

The circuit looks like this but can be changed, The dc fan motor connected to PWM 3 and thermistor connected with pin A0.
The thermistor check the temperature of a device that heated by nearby heater so fan cools the device to get the specific temperature.
Case 1
When Heater not running, the thermistor value in Serial monitor 0-1023, When fan not running it gives 1023 and when fan runs at full speed it gives about 0.
Case 2
But when heater is running the values of thermistor has been changed and when fan not running it gives 1023 and when fan runs at full speed it gives about 500.
I want to set a point 650 from thermistor value(INPUT Value), and fan speed have to adjust using pid so temperature adjusted and the thermistor gives 650 value.
Sample PID code
 #include <PID_v1.h>
//Define Variables we'll be connecting to double Setpoint, Input, Output;
//Define the aggressive and conservative Tuning Parameters
double aggKp=4, aggKi=0.2, aggKd=1;
double consKp=1, consKi=0.05, consKd=0.25;
//Specify the links and initial tuning parameters
PID myPID(&Input, &Output, &Setpoint, consKp, consKi, consKd, DIRECT);
void setup()
{
  Serial.begin(115200);
  //initialize the variables we're linked to
  Input = map(analogRead(0), 0, 1023, 255, 0);
  Setpoint = 650;
  myPID.SetOutputLimits(0, 255);
  //turn the PID on
  myPID.SetMode(AUTOMATIC);
}
void loop()
{
  int sensorValue = analogRead(0);
  Input = map(analogRead(0), 0, 1023, 255, 0);
    double gap = abs(Setpoint-Input); //distance away from setpoint
  if(gap<10)
  {  //we're close to setpoint, use conservative tuning parameters
    myPID.SetTunings(consKp, consKi, consKd);
  }
  else
  {
     //we're far from setpoint, use aggressive tuning parameters
     myPID.SetTunings(aggKp, aggKi, aggKd);
  }
  myPID.Compute();
  analogWrite(3,Output);
  Serial.println(sensorValue);
}

What changes have to done in code so we can set point from input values?
And
Please help me so this code works for me.

You can't connect a motor directly to an output pin (unless it's a really small motor). You also need to a flyback diode to the motor. My guess is that the motor is generating a lot of "noise" on the power rail, leading to weird analogRead values.

Two thing that may be helpful.
First make sure you have a common ground. For instance for you transistor you are using separate power from the arduino and 12 volt source. Connecting the two ground of the arduino and the power supply may resolve this for you.
The other thing is it is often times helpful to put a capacitor across the DC motor to help with voltage fluctuations.

But the grounds are connected in the diagram...

First try using external power source to power the motor, as only  very small motors can be connected to an Arduino's power source.(Basically, the Motor is using most of the power, leaving too little power for the Arduino to operate properly)
If that fails, change the code(I will give sample code by tomorrow, if you cannot find one yourself)-maybe use a PWM signal instead of trying PID, as it is much simpler and give very little room for error.
And also, don't forget the fly back diode mentioned by Gerben.

you do not read full question , i know the output of dc motor is always a PWM Signal for speed Controlling. i want to use PID Library to detect error between Set Point and current temperature value and change speed of motor according to that value.

I knew that you obviously knew that output to a DC motor is always a PWM signal, I meant to tell you to leave the PID library and write your own code so that it acts like PID.

I have tried that and it works easily enough.

link

There are some issues with your map command.
For example, you are reading the thermistor value using analogRead(A0), which has a return range from 0 to 1023. After that you attempt to use map() to change this value to 0 - 255 but use the wrong syntax. The correct syntax for this command is Input = map(analogRead(0), 0, 1023, 0, 255);. However, I can't see the reason for that because you are reading values 0-1023, change it to 0-255, but set point is 650. So you never get setpoint because maximum is 255.
Try use as input just analogread(0). There is no reason to change input into PWM range and output is for PID library in PWM range as a default so you can send output direct to motor pin. Of course use some H-bridge or something like that.

//Now it will work
//  https://arduino.stackexchange.com/questions/9731/control-speed-of-dc-fan-using-arduino-pid-library

#include <PID_v1.h>
double Setpoint, Input, Output;  //not there in original sketch
//Define Variables we'll be connecting to double Setpoint, Input, Output;
//Define the aggressive and conservative Tuning Parameters
double aggKp = 4, aggKi = 0.2, aggKd = 1;
double consKp = 1, consKi = 0.05, consKd = 0.25;
//double consKp=2, consKi=5, consKd=1;

//Specify the links and initial tuning parameters
PID myPID(&Input, &Output, &Setpoint, consKp, consKi, consKd, REVERSE);
void setup()
{
  Serial.begin(9600);
  //initialize the variables we're linked to
  // Input = map(analogRead(0), 0, 1023, 255, 0);

  //int val = analogRead(0);
  //val = map(val, 0, 1023, 0, 255);
  // analogWrite(9, val);

  Setpoint = 100;
  myPID.SetOutputLimits(0, 255); //MIN,MAX
  //turn the PID on
  myPID.SetMode(AUTOMATIC);  // MANUAL
  myPID.SetControllerDirection(REVERSE);  // DIRECT
}
void loop()
{
  int sensorValue = analogRead(0);
  Input = map(sensorValue, 0, 1023, 0, 255);

  double gap = abs(Setpoint - Input); //distance away from setpoint
  if (gap < 10)
  { //we're close to setpoint, use conservative tuning parameters
    myPID.SetTunings(consKp, consKi, consKd);
  }
  else
  {
    //we're far from setpoint, use aggressive tuning parameters
    myPID.SetTunings(aggKp, aggKi, aggKd);
  }

  myPID.Compute();
  analogWrite(3, Output);
  Serial.print(" PWM = ");
  Serial.print(Output,0);
  Serial.print("       sensor value =  ");
  Serial.print(sensorValue);
  Serial.print("       Input =");
  Serial.println(Input,0);
}

It may be better to not use map(), as it will give trouble between float and int variable usage - do it manually in the code.

This is both a comment rather than an answer, and also erroneous.  Arduino's map() in an integer function.  It is perfectly legitimate to initialize a floating point variable with an integer value.


text:
What do symbols like UCSR0C, UMSEL01, etc. means?
I have a code with a connection to serial port:
// Set baud rate
UBRR0H = UBRRH_VALUE;
UBRR0L = UBRRL_VALUE;
// Disable USART rate doubler (arduino bootloader leaves it enabled...)
UCSR0A &= ~(1 << U2X0);
// Set async, no parity, 1 stop, 9bit
UCSR0C = (0<<UMSEL01)|(0<<UMSEL00)|(0<<UPM01)|(0<<UPM00)|(0<<USBS0)|(1<<UCSZ01)|(1<<UCSZ00);
UCSR0B |= (1<<UCSZ02); // 9bit
// Enable rx/tx
UCSR0B |= (1<<RXEN0)|(1<<TXEN0);

I see the comments but I want to know exactly what does these chunks means. Is there any complete documentation about these symbols?

Take a look in the datasheet under the "20. USART0" section:
http://www.atmel.com/images/Atmel-8271-8-bit-AVR-Microcontroller-ATmega48A-48PA-88A-88PA-168A-168PA-328-328P_datasheet_Complete.pdf
I will list the names of the registers, what they are called, and then what your code is doing specifically:

UBRR0H and UBRR0L together form the baud rate divider.  Your program probably uses F_CPU and <util/setbaud.h> to calculate a divider and set the baud rate.  For more information see Table 20-12.
UCSR0A  "USART Control and Status Register n A"  --  This line is enabling the U2X0 which doubles the transmission speed
UCSR0C  "USART Control and Status Register n C" --  This line is enabling the UCSZ01 and UCSZ00 bits to set parity check to "Enabled, Odd Parity".  See Table 20-9.  This line has extra information, all the statements with 0<< actually do nothing.
USCR0B " USART Control and Status Register n B" -- This line is setting the UCSZ02 bit which is described here: "The UCSZn2 bits combined with the UCSZn1:0 bit in UCSRnC sets the number of data bits (Character SiZe) in
a frame the Receiver and Transmitter use. "  This basically allows you to select 9 bit wide serial if you would like (8 bit is more common)
The final USCR0B line enables tx and rx

Thanks a lot!
How can I setup which arduino mega rx/tx port (0-usb, or 1,2,3-gpio) will it use?

@asiniy: By changing the numeral in the symbol. All 4 USARTs work exactly the same way.

Should I use USCR1B for gpio rx1/tx1?

I strongly recommend you to read the datasheet. You are confusing UART module with GPIO module. Once you use one pin for one purpose (say serial comunication) you cannot use it for another thing (say general I/O to read a physical button state). Of course it is possible if you write your code in a way it changes all the registers (the ones you call "symbols") on excecution time. But just be carefull that the routines that used those pins for UART don't execute meanwhile!


text:
Arduino Motor Shield and Adafruit CC3000 WiFi Shield Compatibility
My question is similar to this one: Motor shield and wireless transceiver compete for same pins
But not exactly the same!
I would like to know if the solution is as practical, though.
I have an Arduino Mega 2560 R3, with an Arduino Motor shield plugged into it. Now I want to use the Adafruit CC3000 WiFi shield. It plugs in fine, but when reading the specifications, it wants to use pins 13, 12, 11 which are also used by the Motor shield. I also want to use pin 10 as a servo is plugged into it. This is all on a robot so I don't have space to wire the shield separately through a breadboard or similar.
It should perhaps also be noted that I have the motor shield on top of the wifi shield so that the wifi shield can use the ICSP ports which the motor shield doesn't have, therefore any redirecting of pins on the CC3000 will mean that the motor shield pins will also be affected unless I redirect them too, and at that point I feel like it would be all a bit of a mess.
The solution to the other question was indeed to redirect the relevant pins to other free pins on the micro-controller board. However, I noticed that the Adafruit shield has a second row of connector holes next to the main pin holes. In the shield documentation I found, I didn't find any specific reference to these parts and in what situations they could be used, but maybe this is one of them.
My concern with using these is that (as you can see in the second image below, ignoring the coin!), the ports are wired together in the board. Does this mean that it won't make any difference which I use; if I connect a second row of pins/connectors to these points will it simply transmit the same data down both sides? I don't know enough about how electronics work at that level to understand the consequences.
So really my question is: can I use the outside row of ports for my motor shield and the inside row for the wifi shield?

EDIT:
So I've spent until now on the Adafruit forums trying to get some help with this and I still am not all the way there... maybe at this point someone here can cast fresh eyes over my problem.
The Adafruit CC3000 uses both the dedicated ICSP pins and pins 3, 11-13 to transmit the same data. The reason for this is to do with compatibility between different Arduino boards and their versions. E.g. apparently the Uno uses those pins whilst the mega uses some of the pins in the 50s range. I'm not sure what to make of this as the Uno and most of the boards seem to have the ICSP pins, so if they're not used for this purpose then what's the point of connecting to them? Anyway.
As it was explained to me, even if the board can use the ICSP pins to communicate with the microcontroller, it is still sending data via the other pins. So the main pins are essentially useless at this point. To make them useful again, the idea is that you sever the wires that are sending the data through them (often referred to as trace wires). This means that only the ISCP ones will be active for what they are needed, and the main pins will be free for other uses. This is what I ended up doing to my board for pins 11-13, and then for pin 3 I cut the trace wire and wired up the connection to pin 2 as these can both be used for an IRQ (interrupt request) on the Mega and I need pin 3 for the motor shield. The lighting on these pictures isn't the best, but you can see what I've done (the lower part of the second image shows where I made the cuts and the top image shows the wire connection):

After doing that I have been testing the shield connected to both my Mega and my Uno and they both produce the same results. This is using the Adafruit-created library called Adafruit_CC3000_Library. It starts the initialisation, then whilst it's trying to run the code it gets stuck. I traced the problem to a while(1) loop of which you can only exit by meeting a condition which is never met in my case: if (*pucReceivedData == HCI_TYPE_EVNT). This may be because pucReceivedData is not initialised properly, but I don't know why and whether it has to do with my modifications. This happens in the hci_event_handler method of evnt_handler.cpp. This is  through the main file and wlan.cpp so I won't write it here as it is simple enough to follow.
It should also be noted that this shield doesn't work properly with the later versions of the arduino IDE (1.5+) so I had to reinstall 1.0.6. To be honest, I got the same problem on both versions so who knows.
I realise that this is a very specific problem, but I figure that this may leave someone with a lot fewer issues in the future. If anyone has any bright ideas, even if just for testing then I would be grateful.

And I've just realised that pin 3 is used as the PWM for one of my motors and the IRQ for the wifi shield. Pin 3 also has a 'double' next to it, though. Any advice would be appreciated!

Right, have hopefully come up with a solution from talking to Arduino and Adafruit, so will post it up tomorrow (if it works!).

It works!
First I'll say thanks to the moderators/support staff from Adafruit. One dude in particular has tried to help me constantly for the past couple of days or so.
So, following on from my edit, Adafruit told me that the ICSP pins are connected to the control part of the board via the main pins. I should have seen it actually, but I obviously didn't examine and understand it properly. This means that although I severed the connection between the main pins and the centre, the ICSP and 11,12,13 were still connected together. What I actually needed was for the ICSP pins to be connected to the controls to receive the data, and the main pins to be detached from them. So I de-soldered the solder jumpers that I had originally put on the connector plates on the underside of the board (which connect the ISCPs to the main pins), then soldered wire from the ICSP side to the associated breakout holes which are the ones on the inside of the cuts that I made on the board. Here is a picture:

If anyone tries to do this, beware of where you are wiring to! I was very careful to make sure I matched the connecting wires to the correct pins. I have tested it several times (using the example test file that comes with the library) and it works as it should. It works on my Uno R3 and my Mega 2560 R3, which is great, as now pins 11-13 are free to use for my motor shield, or potentially any other shield which may need those pins.
I hope this helps someone else in the future. There doesn't seem to be any information on this particular combination of shields, but as these projects are becoming more popular this may prove to be useful.


text:
Is it possible to use two encoders with Arduino Uno?
I would like to control 2 motors with the Arduino Uno board, which provides only two interrupt pins on digital 2 and 3.
I've set one encoder using these pins, and it works. What do you think about the following approaches:

Timer Interrupt:

Create a Timer Interrupt.
Connect the seconder encoder to an analog pin.
Set an analog read function in the interrupt service routine.
Change the prescaler of the ADC and increase the acquisition time.

PinChangeInt

Use PinChangeInt to capture the pin change interrupt rather than an external interrupt.

This should allow you to use almost any I/O pins on the Uno for the
  encoder.
as Ignacio Vazquez-Abrams suggested here

Just go with the PinChangeInterrupts solution. There are some libraries for it if you want. I don't get the timer or analog read solution.

Just to check the state of the pin as fast and precise as possible but they suggested to check it with a normal digital pin.

It is very possible. use a separate interrupt pin for Phase A of both motors, then read phase B from a non interrupt pin in the interrupt handler.
http://www.spiked3.com/?p=5501


text:
How to add the Wiring S board to Arduino IDE v.1.6.2?
My Arduino Uno is running out of memory to support my script (yes, I've tried several ways of optimize it already: PROGMEM, EEPROM, no Strings, and so on), so I would like to upload my script to my Wiring S board.
However, instead of "porting" all libraries to Wiring, I would like to compile my script in Arduino IDE and upload it to my Wiring S. It used to be "easy" in Arduino v.1.0.x. because somwhere I got a Wiring folder (containing, among other things, a boards.txt file) and copied it to Arduino's hardware folder getting the Wiring S board listed in Arduino IDE.
Since Arduino 1.5 the specification for adding other boards changed. I'd say it's more complex now. I simply cannot understand most of the new specification (yes, I'm new into electronics), so I haven't been able to add my Wiring S board.
Running my script in Arduino 1.0.x doesn't seem to be an option, since it throws lots of errors (although the script compiles in Arduino 1.6.2).
Do you have any experience adding other boards (like Wiring S) to Arduino IDE? Could you please give me some hint?

Which version? There seem to be 4 different chips on these boards. What is the main chip? PS new specification isn't that different. It requires everything to be put in an folder (avr), and requires a platform.txt file with just a name and version (two lines). The boards.txt file has some variables with new names. You'll get some error messages in the IDE is something is incorrect.

You're right, but those changes are enough for us basic users to be unable to work with the configuration we used to work with. On the other hand, it's Wiring S v.1.0, it looks exactly like this one: http://www.lextronic.fr/P22978-platine-de-developpement-wiring-s.html

The one you link to is a Atmega644P, while v1.0 is atmega128. What boards.txt file did you use for the Arduino 1.0? So I can try to port it for you.

I use Wiring S, that works with AtMega644p. The confusion arose because on top of the microcontroller, there is a sticker saying "WIRING S 1.0" (as shown in the link I posted). So, Wiring S, AtMega644p. The boards.txt I used is https://titanpad.com/wiringsboards Thanks!

Here is my attempt at porting. I don't have that board, so I can't really test it. Just be careful, as the pin numbers might be different on the board, then in the IDE. Also check the higher number pins.

There are two things I do; I use the Serial.print(F("string/n")); which prints the data from flash rather then copying it to ram.  Keep as many of your variables local as possible, that will save ram.  This is done by defining then in the function, the added advantage nothing outside the function can change them.
Global and Static variables are the first things loaded into SRAM. They push the start of the heap upward toward the stack and they will occupy this space for all eternity.
Variables created in functions, are dynamically allocated objects and data. Unlike Global and Static variables, these variables can be de-allocated to free up space at function exit. But Every function call creates a stack frame that makes the stack grow toward the heap. This data is usable within the function, but the space is 100% reclaimed when the function exits!

Thanks for your answer, although I'm not really asking for hints on saving program space.


text:
Can I damage an arduino by setting pins high with no load
I have an Arduino project that has 15 different output pins set.  Some are currently attached to devices and others are not.  Will testing my program cause a problem / damage if it sets pints to HIGH that do not have anything connected to them?

Nope, you should be just fine.
Having a pin set to any state while unplugged will not cause any problems with your microcontroller.