message:
CC3000 - Send GET request to an app, or sub-domain, on Heroku

I am working with Arduino UNO + AdaFruit CC3000 Wi-Fi shield. I ran it with a lot of websites and webpages, but for now I am going to get sub-domain from [Heroku][1], and it has no IP address. The sub-domain is `myapp.herokuapp.com`.

So, how can I send a GET request to such an application like that?

Here's the code :

     // Library headers section
     #include <Adafruit_CC3000.h>
     #include <ccspi.h>
     #include <SPI.h>
     #include <string.h>
     #include "utility/debug.h"

     // Constants area
     #define ADAFRUIT_CC3000_IRQ  3 // must be an interrupt pin (2 or 3)
     #define ADAFRUIT_CC3000_VBAT  5 // any pin
     #define ADAFRUIT_CC3000_CS  10 // any pin

     //use hardware SPI for remaining pins
     // Uno: SCK=13, MISO=12, MOSI=11
     Adafruit_CC3000 cc3000 = Adafruit_CC3000(ADAFRUIT_CC3000_CS,      ADAFRUIT_CC3000_IRQ,
                                              ADAFRUIT_CC3000_VBAT,      SPI_CLOCK_DIVIDER);
     #define WLAN_SSID  "Ibtikar.AP2"
     #define WLAN_PASS  "#ibtik@r#"
     // set security type
     // WLAN_SEC_UNSEC, WLAN_SEC_WEP, WLAN_SEC_WPA, WLAN_SEC_WPA2
     #define WLAN_SECURITY  WLAN_SEC_WPA2
     #define IDLE_TIMEOUT_MS  3000 // amount of time to wait with no date      recieved
                                   // before rejecting/closing the collection
     #define WEBSITE  "myapp.herokuapp.com"
     uint32_t ip;
     void setup() {
       // put your setup code here, to run once:
        Serial.begin(115200);
        Serial.print("Free RAM: "); Serial.println(getFreeRam(), DEC);
    /* Initialise the module */
        Serial.println(F("\nInitializing..."));
        delay(100);
        if (!cc3000.begin())
        {
          Serial.println(F("Couldn't begin()! Check your wiring?"));
          while(1);
        }
        Serial.print(F("\nAttempting to connect to "));           Serial.println(WLAN_SSID);
         if (!cc3000.connectToAP(WLAN_SSID, WLAN_PASS, WLAN_SECURITY)) {
           Serial.println(F("Failed!"));
           while(1);
         }
        Serial.println(F("Connected!"));
        /* Wait for DHCP to complete */
        Serial.println(F("Request DHCP"));
        while (!cc3000.checkDHCP())
        {
           delay(100); // ToDo: Insert a DHCP timeout!
        }

       /* Display the IP address DNS, Gateway, etc. */
       while (! displayConnectionDetails()) {
         delay(1000);
       }

        ip = 0;
       // Try looking up the website's IP address
       Serial.print(WEBSITE); Serial.print(F(" -> "));
       while (ip == 0) {
         if (! cc3000.getHostByName(WEBSITE, &ip)) {
           Serial.println(F("Couldn't resolve!"));
         }
         delay(500);
       }
       cc3000.printIPdotsRev(ip);

       // Optional: Do a ping test on the website
       Serial.print(F("\n\rPinging ")); cc3000.printIPdotsRev(ip);      Serial.print("...");
       int replies = cc3000.ping(ip, 5);
       Serial.print(replies); Serial.println(F(" replies"));
     }

     void loop() {
        /* Try connecting to the website.
          Note: HTTP/1.1 protocol is used to keep the server from closing the           connection before all data is read.
       */
        Adafruit_CC3000_Client www = cc3000.connectTCP(ip, 80);
       if (www.connected()) {
         www.fastrprint(F("GET "));
         www.fastrprint(F(" HTTP/1.1\r\n"));
         www.fastrprint(F("Host: myapp.herokuapp.com"));
         //www.fastrprint(WEBSITE);
         www.fastrprint(F("\r\n"));
         www.println();
       } else {
         Serial.println(F("Connection failed"));
         return;
       }
       Serial.println(F("-------------------------------------"));
       unsigned long lastRead = millis();
       while (www.connected() && (millis() - lastRead < IDLE_TIMEOUT_MS)) {
         while (www.available()) {
           char c = www.read();
           Serial.print(c);
           lastRead = millis();
         }
       }
       www.close();
       Serial.println(F("-------------------------------------"));

       /* You need to make sure to clean up after yourself or the CC3000 can           freak out */
       /* the next time your try to connect ... */
            Serial.println(F("\n\nDisconnecting"));
       cc3000.disconnect();
       delay(1000);
     }

     /**************************************************************************/
     /*!
         @brief  Begins an SSID scan and prints out all the visible networks
     */
     /**************************************************************************/

     void listSSIDResults(void)
     {
       uint32_t index;
       uint8_t valid, rssi, sec;
       char ssidname[33];

       if (!cc3000.startSSIDscan(&index)) {
              Serial.println(F("SSID scan failed!"));
              return;
       }

       Serial.print(F("Networks found: ")); Serial.println(index);
       Serial.println(F("================================================"));

       while (index) {
         index--;

         valid = cc3000.getNextSSID(&rssi, &sec, ssidname);

         Serial.print(F("SSID Name    : ")); Serial.print(ssidname);
         Serial.println();
         Serial.print(F("RSSI         : "));
         Serial.println(rssi);
         Serial.print(F("Security Mode: "));
         Serial.println(sec);
         Serial.println();
       }
       Serial.println(F("================================================"));

       cc3000.stopSSIDscan();
     }

          /**************************************************************************/
     /*!
         @brief  Tries to read the IP address and other connection details
     */
     /**************************************************************************/
     bool displayConnectionDetails(void)
     {
       uint32_t ipAddress, netmask, gateway, dhcpserv, dnsserv;

       if(!cc3000.getIPAddress(&ipAddress, &netmask, &gateway, &dhcpserv,      &dnsserv))
       {
         Serial.println(F("Unable to retrieve the IP Address!\r\n"));
         return false;
       }
       else
       {
         Serial.print(F("\nIP Addr: ")); cc3000.printIPdotsRev(ipAddress);
         Serial.print(F("\nNetmask: ")); cc3000.printIPdotsRev(netmask);
         Serial.print(F("\nGateway: ")); cc3000.printIPdotsRev(gateway);
         Serial.print(F("\nDHCPsrv: ")); cc3000.printIPdotsRev(dhcpserv);
         Serial.print(F("\nDNSserv: ")); cc3000.printIPdotsRev(dnsserv);
         Serial.println();
         return true;
       }
     }

  [1]: https://en.wikipedia.org/wiki/Heroku

body:
You don't need to know the IP address; the `getHostByName()` method takes care of resolving the website to an address. It seems 2 lines are missing from your code:

        #define WEBPAGE "/index.html"  // change the string to the webpage you want
at the top, and:

       www.fastrprint(WEBPAGE);

right after `www.fastrprint(F("GET "));`. Without these lines, you've failed to indicate the specific webpage you wish to GET. Anyways, when i tried to open `myapp.herokuapp.com`, I got a message saying that its offline for maintenance, so you'll most likely fail to retrieve anything.


sender: user

message:
Arduino + ESP8266 - poll file from a server?

I really need all the help I can get...
It's been a week now and I'm still not able to solve the problem.

I have text file on a server. The whole address is www.example.com/test.txt
I want to read the file using a GET request every 3-5 secs and parse it for further actions. But the arduino codes that I've tried till now use software serial and it keeps misbehaving. Sometimes it skips a few serial-print commands and loops back sometimes it reads the file 3-4 times and then hangs. Basically I'm getting the response only a few times but then it stops working properly.

I want to solve this...I need a working arduino code to work with ESP8266 so that I can successfully poll a text file from server without any problems.

Here is my current code -

     #include<SoftwareSerial.h>

        #define led 13
        SoftwareSerial esp(11, 12);
        String domain = "www.example.com";
        String request = "GET /test.txt HTTP/1.0\r\n\r\n";

        void SerialDo(String command, float time, bool debug) {
          delay(100);
          esp.print(command);

          int i = millis();
          while (millis() - i < (time * 1000)) {
            while ( (esp.available())) {
              if (debug) {
                Serial.print((char)esp.read());
              }
            }
          }

          Serial.flush();
        }

        void setup() {
          // put your setup code here, to run once:
          digitalWrite(led, OUTPUT);
          Serial.begin(9600);
          esp.begin(9600);
          esp.setTimeout(3000);
          digitalWrite(led, LOW);
          Serial.println("Hello");
          //delay(2000);
          SerialDo("AT+RST\r\n", 5, true);
          Serial.flush();
          SerialDo("AT+CWMODE=1\r\n", 0.5, true);

          delay(1000);
          //SerialDo("AT+CWLAP\r\n", 5, true);
          SerialDo("AT+CWJAP=\"Sherlock\",\"Watson@11\"\r\n", 10, true);
          SerialDo("AT+CIPMUX=0\r\n", 0.5, true);

        }

        void loop() {

          delay(1000);
          Serial.print("loop\r\n");

          SerialDo("AT+CIPMUX=0\r\n", 0.5, true);
          SerialDo("AT+CIPSTART=\"TCP\",\"" + domain + "\",80\r\n", 1.5, true);
          esp.flush();

          esp.print("AT+CIPSEND=" + String(request.length()) + "\r\n");
          delay(100);
          esp.print(request);

          String t = "";
          int i = millis();
          while (millis() - i < 1500) {
            while ((esp.available() > 0)) {
              if (true) {
                char c = (char)esp.read();
                t += c;
                Serial.print(c);
              }
            }
          }

          esp.print("AT+CIPCLOSE\r\n");

          if (t.indexOf("hello world") > -1) {
            digitalWrite(led, !digitalRead(led));
          }
      }

sender: assistant

body:
It seems that you're trying to do the same thing:

> https://www.youtube.com/watch?v=q02f4sPghSo

Maybe it will help, I'm tryin' to do that (a POST), only that I don't have the server on a text file.


body:
You aren't implementing the timeouts well and I don't see the point of this `if`:

    if (true) {
       char c = (char)esp.read();
       t += c;
       Serial.print(c);
    }

It will always be executed. You have allotted 1500 ms to the whole process of reading the whole file, whether the ESP is done or not. Inside the loop, you are calling Serial.print(), as well as concatenating chars to a string, which takes a significant portion of the 1.5 secs. Get rid of the Serial.print() and use the timeout this way:

    unsigned long lastRead = millis();
    while (millis() - lastRead < 1500) {
        while (esp.available() {
            t += (char)esp.read();
            lastRead = millis();
        }
    }
    Serial.print(t);

Storing the value of `millis()` with an `int` isn't a good idea since after about 33 seconds, it'll overflow. The code above will ensure that the last time a character was read is always stored in `lastRead`; the end result is that no character is available from the ESP after a continuous 1500ms, we conclude that there's nothing more to be read or some error has occurred. Repeat this for the loop in `SerialDo` as well. The `setTimeout` in your setup() is also unneeded, in this case; you didn't call any `SoftwareSerial` method that makes use of it, so remove the line. Also if your server supports HTTP 1.1, then try this request:

        String request = "GET /test.txt HTTP/1.1\r\nHost: www.example.com\r\n\r\n"


message:
Run Arduino on USB and at the same time BreadBoard on higher voltage?

I am trying to design a bicycle LED lighting system, and for that I bought an Arduino yesterday (so very beginner with Arduino).

My final system will operate at 6V, so I plan to put everything on a breadbord and tune everything (blinking times, resistor values, etc.) and for that I want to keep my Arduino plugged to USB during development.

So my question is:

How should I connect USB-powered Arduino to a higher-voltage-powered breadbord (between 6 and 12V) safely?

body:
Unless you intend to run both supplies simultaneously, there's no problem. Your ~ 6v input will need to be stepped down and regulated to 5v, and the USB provides a regulated 5v, so the system shouldn't care which one you are using.

If you need to run your system off the 6v during development and need USB communication, I'd suggest using a USB-to-TTL-Serial cable such as this one: [https://www.sparkfun.com/products/9718][1]. Connect its Tx & Rx pins to your Arduino's (Uno?) pins 1 and 0, respectively, and it's ground pin to the ground rail served by your battery supply.

Typical regulators will need more headroom above their output voltage to give you a steady, regulated output, and this includes the 5v regulators on Arduino boards which usually specify 7-12v at the Vin (unregulated) input. A 6v battery won't meet this spec so you'd need a buck/boost regulator that could provide a regulated 5v from "0+" to 6v input. Or you might move your system to a bare AtMega328p with a lower clock speed (see the data sheet for max clock speed vs. Vcc), and run it at 3v (for example) which would give a simpler regulator more headroom from its 6v input.

  [1]: https://www.sparkfun.com/products/9718


body:
Datasheet can be found here: http://www.atmel.com/devices/atmega328.aspx?tab=parameters

From this, the absolute rated voltage on the ATMega (aka, the chip at the heart of the Arduino) is 6V.  Above that... above that you risk magic smoke.  But you can just, *maybe* get away with running your whole system on 6V.

Important point - do not rely on using 4 AA batteries for this.  Regulate your 6Vish to *exactly* 6V.  Just remember that this is at the extreme limit of the spec.  If you try this, before you start repeat to yourself "I have just voided my warranty.  It is now my fault when it dies."

Alternatively, why are you so wedded to 6V?  What are you trying to achieve?


body: I think as far as i understood the problem, the system or whatever you call is will run on what ever power as long that power is not fed to the arduino that will not be a problem, just connect the two grounds together and power the arduino through the computer and connect the pins to the system accordingly. i think this will solve thus the trivial problem.


message:
Android stops reading from bluetooth module

I am trying to read from a bluetooth module connected to arduino Uno. My application is a simple counter where the values are displayed on the arduino and the android app. The problem is that my android application get readings for some time (40-50 sec) and then stop at a random reading. When I check on the arduino serial monitor, the counter keeps counting and doesn't stop. Can someone please help?

Note: Ignore the buttons that I created :D

Java code:

    package com.example.ibm.bluetooth_3;

    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.lang.reflect.Method;
    import java.util.UUID;
    import com.example.ibm.bluetooth_3.R;

    import android.app.Activity;
    import android.bluetooth.BluetoothAdapter;
    import android.bluetooth.BluetoothDevice;
    import android.bluetooth.BluetoothSocket;
    import android.content.Intent;
    import android.os.Build;
    import android.os.Bundle;
    import android.os.Handler;
    import android.util.Log;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.TextView;
    import android.widget.Toast;

    public class MainActivity extends Activity {
        private static final String TAG = "bluetooth2";

        Button btnOn, btnOff;
        TextView txtArduino;
        Handler h;

        final int RECIEVE_MESSAGE = 1;  // Status  for Handler
        private BluetoothAdapter btAdapter = null;
        private BluetoothSocket btSocket = null;
        private StringBuilder sb = new StringBuilder();

        private ConnectedThread mConnectedThread;

        // SPP UUID service
        private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");

        // MAC-address of Bluetooth module (you must edit this line)
        private static String address = "00:06:66:68:30:D6";

        /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            btnOn = (Button) findViewById(R.id.btnOn);     // button LED ON
            btnOff = (Button) findViewById(R.id.btnOff);    // button LED OFF
            txtArduino = (EditText) findViewById(R.id.txtArduino);  // for display the received data from the Arduino
            h = new Handler() {
                public void handleMessage(android.os.Message msg) {
                    switch (msg.what) {
                        case RECIEVE_MESSAGE:             // if receive massage
                            byte[] readBuf = (byte[]) msg.obj;
                            String strIncom = new String(readBuf, 0, msg.arg1);     // create string from bytes array
                            sb.append(strIncom);            // append string
                            int endOfLineIndex = sb.indexOf("\r\n");       // determine the end-of-line
                            if (endOfLineIndex > 0) {            // if end-of-line,
                                String sbprint = sb.substring(0, endOfLineIndex);    // extract string
                               sb.delete(0, sb.length());          // and clear
                                txtArduino.setText(sbprint);                                  // update TextView
                            }
                            //Log.d(TAG, "...String:"+ sb.toString() +  "Byte:" + msg.arg1 + "...");
                            break;
                    }
                };
            };

            btAdapter = BluetoothAdapter.getDefaultAdapter();  // get Bluetooth adapter
            checkBTState();

            btnOn.setOnClickListener(new OnClickListener() {
                public void onClick(View v) {
                    btnOn.setEnabled(true);
                    mConnectedThread.write("1"); // Send "1" via Bluetooth
                    //Toast.makeText(getBaseContext(), "Turn on LED", Toast.LENGTH_SHORT).show();
                }
            });

            btnOff.setOnClickListener(new OnClickListener() {
                public void onClick(View v) {
                    btnOff.setEnabled(true);
                    mConnectedThread.write("0"); // Send "0" via Bluetooth
                    //Toast.makeText(getBaseContext(), "Turn off LED", Toast.LENGTH_SHORT).show();
                }
            });
        }

        private BluetoothSocket createBluetoothSocket(BluetoothDevice device) throws IOException {
            if(Build.VERSION.SDK_INT >= 10){
                try {
                    final Method  m = device.getClass().getMethod("createInsecureRfcommSocketToServiceRecord", new Class[] { UUID.class });
                    return (BluetoothSocket) m.invoke(device, MY_UUID);
                } catch (Exception e) {
                    Log.e(TAG, "Could not create Insecure RFComm Connection",e);
                }
            }
            return  device.createRfcommSocketToServiceRecord(MY_UUID);
        }

        @Override
        public void onResume() {
            super.onResume();

            Log.d(TAG, "...onResume - try connect...");

            // Set up a pointer to the remote node using it's address.
            BluetoothDevice device = btAdapter.getRemoteDevice(address);

            // Two things are needed to make a connection:
            //   A MAC address, which we got above.
            //   A Service ID or UUID.  In this case we are using the
            //     UUID for SPP.

            try {
                btSocket = createBluetoothSocket(device);
            } catch (IOException e) {
                errorExit("Fatal Error", "In onResume() and socket create failed: " + e.getMessage() + ".");
            }

        /*try {
          btSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
        } catch (IOException e) {
          errorExit("Fatal Error", "In onResume() and socket create failed: " + e.getMessage() + ".");
        }*/

            // Discovery is resource intensive.  Make sure it isn't going on
            // when you attempt to connect and pass your message.
            btAdapter.cancelDiscovery();

            // Establish the connection.  This will block until it connects.
            Log.d(TAG, "...Connecting...");
            try {
                btSocket.connect();
                Log.d(TAG, "....Connection ok...");
            } catch (IOException e) {
                try {
                    btSocket.close();
                } catch (IOException e2) {
                    errorExit("Fatal Error", "In onResume() and unable to close socket during connection failure" + e2.getMessage() + ".");
                }
            }

            // Create a data stream so we can talk to server.
            Log.d(TAG, "...Create Socket...");

            mConnectedThread = new ConnectedThread(btSocket);
            mConnectedThread.start();
        }

        @Override
        public void onPause() {
            super.onPause();

            Log.d(TAG, "...In onPause()...");

            try     {
                btSocket.close();
            } catch (IOException e2) {
                errorExit("Fatal Error", "In onPause() and failed to close socket." + e2.getMessage() + ".");
            }
        }

        private void checkBTState() {
            // Check for Bluetooth support and then check to make sure it is turned on
            // Emulator doesn't support Bluetooth and will return null
            if(btAdapter==null) {
                errorExit("Fatal Error", "Bluetooth not support");
            } else {
                if (btAdapter.isEnabled()) {
                    Log.d(TAG, "...Bluetooth ON...");
                } else {
                    //Prompt user to turn on Bluetooth
                    Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                    startActivityForResult(enableBtIntent, 1);
                }
            }
        }

        private void errorExit(String title, String message){
            Toast.makeText(getBaseContext(), title + " - " + message, Toast.LENGTH_LONG).show();
            finish();
        }

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

            public ConnectedThread(BluetoothSocket 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;
            }

            public void run() {
                byte[] buffer = new byte[1024];  // buffer store for the stream
                int bytes; // bytes returned from read()
                // Keep listening to the InputStream until an exception occurs
                while (true) {
                    try {
                        // Read from the InputStream
                        bytes = mmInStream.read(buffer);  // Get number of bytes and message in "buffer"
                        h.obtainMessage(RECIEVE_MESSAGE, bytes, -1, buffer).sendToTarget();  // Send to message queue Handler
                    } catch (IOException e) {
                        break;
                    }
                }
            }

            /* Call this from the main activity to send data to the remote device */
            public void write(String message) {
                Log.d(TAG, "...Data to send: " + message + "...");
                byte[] msgBuffer = message.getBytes();
                try {
                    mmOutStream.write(msgBuffer);
                } catch (IOException e) {
                    Log.d(TAG, "...Error data send: " + e.getMessage() + "...");
                }
            }
        }
    }

Android XML:

    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
        android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingRight="@dimen/activity_horizontal_margin"
        android:paddingTop="@dimen/activity_vertical_margin"
        android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity"
        android:focusable="true">

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="On"
            android:id="@+id/btnOn"
            android:layout_alignParentTop="true"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="52dp"
            android:enabled="true"
            android:focusable="true"
            android:focusableInTouchMode="true" />

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Off"
            android:id="@+id/btnOff"
            android:layout_below="@+id/btnOn"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="63dp"
            android:enabled="true"
            android:focusable="true"
            android:focusableInTouchMode="true" />

        <EditText
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:inputType="number"
            android:ems="10"
            android:id="@+id/txtArduino"
            android:layout_below="@+id/btnOff"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="65dp" />

    </RelativeLayout>

Android Manifest:

    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="com.example.ibm.bluetooth_3" >
        <uses-permission android:name="android.permission.BLUETOOTH" />
        <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
        <application
            android:allowBackup="true"
            android:icon="@drawable/ic_launcher"
            android:label="@string/app_name"
            android:theme="@style/AppTheme" >
            <activity
                android:name=".MainActivity"
                android:label="@string/app_name" >
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />

                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
            </activity>
        </application>

    </manifest>

Arduino code:

    #include <SoftwareSerial.h>
    SoftwareSerial mySerial (3, 2);
    void setup()
    {
      Serial.begin (57600);
      mySerial.begin (115200);
    }

    void loop()
    {
      for (int i=0; i < 1000000; i++)
      {
        mySerial.println (i);
        Serial.println (i);
        delay (100);
      }
    }

body:
On the Arduino side, try increasing the delay or decreasing the baud rate. I have an application that dumps a stored history to a Bluetooth module talking to [Bluetooth Terminal/Graphics][1]
on a Google Nexus 7. At 57600 baud, I've seen the same thing happen. My solution was to delay for 50ms after every 100 lines of output. While your Arduino code should be sending even slower than mine does, your Android system including your application code, might need an even slower input.

[1]: https://play.google.com/store/apps/details?id=com.emrctn.BluetoothGraphics


body:
I am not sure if you have found the answer. Here are my observation. Those who are searching for same problem can refer to these...

1. Change your Android device. Devices will have different bluetooth stack provided by bluetooth chip makers. Cheap ones will have problems. I had this. When I tested with another couple of devices, they seem to have handled it very well. It is all in the bluetooth stack on Android device!

2. Though I have not had problems with Arduino bluetooth device, try changing that.

3. Disable all logging on Android app. This will reduce burden on device.

4. Disable Serial communication on Arduino used for debugging purpose. This way you can make sure that only one serial communication channel is active communicating with Android.

If you follow this, surely you will have solved your problem as I have solved the same.

-Sachin


message:
How to share a library on Arduino Playground?

I have written an ISR-based timer library for Arduino Uno and I would like to share it on the website and get it reviewed.

But I am stuck on how to post it to playground.

body:
The [Arduino Playground library list][1] is a wiki page (like everything on the playground). That means anyone can log in to edit it and add links to their own libraries. The "Log In" and "Sign Up" links are at the top right of the Arduino site. When you first go to edit a Playground page you'll be taken to a "Password required" page but don't worry, this is only to prevent spam and the password is pre-filled. You only need to click the "I'm not a robot" checkbox, wait for the green checkmark to appear, then click "Submit".

There are a couple of important things to note though. Firstly, the Playground library list isn't there for getting your work reviewed. It's a place to post things that are functional and ready to be used by other people. If you need someone to help with your project then you can maybe post on the Arduino forums. Alternatively, if you have specific questions, you can post here on Arduino SE.

If you're ready to post your library online, you also have to be aware that the Playground itself won't host your code. You can put a link there and maybe some documentation. However, you'll need to host your code somewhere else, such as [Github][2].

  [1]: http://playground.arduino.cc/Main/LibraryList
  [2]: https://github.com


message:
Unusual behaviour when moving data to PROGMEM

I've got some working code with a definition that looks like this:

    const unsigned char DynTextPositions[10][4][4] = {
        ...
    };

Which is defined / referenced via a header:

    #include <avr/pgmspace.h>
    #ifndef DYNTEXTPOS_H
    #define DYNTEXTPOS_H

    extern const unsigned char DynTextPositions[10][4][4];

    #endif

This data is being fed into a rendering function which draws lines based on the given positions. The data is read as follows:

    float deltas[4][4];
    // ...
    deltas[n][k] = float(DynTextPositions[c+1][n][k] - DynTextPositions[c][n][k]) / 32.0;

As-is, this works just fine, as long as I've got my other scenes commented out. When I uncomment them, the combined data size seems to overflow the data segment. This is expected, because there's a fair bit of data, so I'm trying to move the `DynTextPositions` data into `PROGMEM`.

I've got `PROGMEM` working with some bitmaps, but it doesn't seem to work here. An example definition for a working bitmap is as follows:

    PROGMEM const unsigned char ArduinoLogo[] = { ... };

However, as soon as I apply the `PROGMEM` attribute to `DynTextPositions` the rendering code seems to freak out - the positions appear to be all off-screen and completely wrong.

The only thing I can think of is that, for some reason, the data is either being considered signed rather than unsigned, or is getting corrupted along the way. Either that or the nested array is somehow being treated as a set of pointers.

Any idea why this might be?

body:
Including `<avr/pgmspace.h>` and using the `PROGMEM` qualifier macro are only two of the steps required in order to get this to work. Since the data will no longer be available via the data bus you will need to use the various `pgm_read_*()` macros or `*_P*()` functions defined in `avr/pgmspace.h`. These work by using the appropriate assembly code instructions to access data stored in program space, i.e. flash, on the MCU.

Under GCC 4.7 or higher when writing C code, the `__flash` named address space is available. Variables declared within this namespace do not require any additional steps to access them. Note that the Arduino IDE compiles as C++, and hence does not make this (or any of the others) available.


message:
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);
    }

body:
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);
    }


body:
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][1] 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.

  [1]: http://www.asciitable.com/


body:
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.


message:
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

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


message:
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

body: 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.


message:
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.

body:
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:

 1. The master sends the address plus the read write instruction on the bus.
 2. All the arduino boards listen and if the address matches with there internal adress they perform the instruction.
 3. 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][1]

[I2C official datasheet][2]

  [1]: http://arduino.cc/en/Reference/Wire
  [2]: https://www.google.it/urlhttps://www.google.it/url?sa=t&source=web&rct=j&ei=IIsZVZ31G8bsUveEgbgB&url=http://www.nxp.com/documents/user_manual/UM10204.pdf&ved=0CB4QFjAB&usg=AFQjCNG5emVs3tU5RbGVKjblTMFgLLHdqg&sig2=rdzEDOM6eEHT43fGziDtxQ


body:
You could use: U(S)ART, I²C or SPI. You should check [this post][1] 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

  [1]: https://electronics.stackexchange.com/questions/37814/usart-uart-rs232-usb-spi-i2c-ttl-etc-what-are-all-of-these-and-how-do-th


body:
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][1] 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)

  [1]: https://github.com/mgulsoy/MertBus


body:
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.

![RS485 connections][1]

I have a description of the sort of thing on my [RS485 communications](http://www.gammon.com.au/forum/?id=11428) 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](http://www.gammon.com.au/forum/?id=11428)
* [RS485 - Wikipedia](https://en.wikipedia.org/wiki/RS-485)
* [I2C (Wire)](http://www.gammon.com.au/i2c)
* [SPI](http://www.gammon.com.au/spi)
* [Async serial](http://www.gammon.com.au/forum/?id=10894)

  [1]: https://i.stack.imgur.com/87ZLH.png


body:
[PJON](https://github.com/gioblu/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


message:
Wifi module for arduino shield

Recently I bought a [B006RATC2E](http://rads.stackoverflow.com/amzn/click/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](http://rads.stackoverflow.com/amzn/click/B007R9U1QA) a good module for the shield? Any other alternative?

Thanks in advance for any help!

body:
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.


message:
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!

body:
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.


body: 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.


body:
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.


body: 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.


message:
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?

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

  [1]: https://github.com/shirriff/Arduino-IRremote


body: 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.


message:
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!!

body:
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][1] 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.

  [1]: https://youtu.be/hpMVG4a9sR4


body:
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][1]. 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.![enter image description here][2]

  [1]: https://www.adafruit.com/products/1063
  [2]: https://i.stack.imgur.com/Va3A5.jpg


body:
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][1]. 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.

  [1]: https://www.ti.com/lit/ds/symlink/lm386.pdf


message:
Use pointer in calculation results in error

I'm building a project to measure/track [flyball][1] 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][2] 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!

  [1]: http://en.wikipedia.org/wiki/Flyball
  [2]: https://github.com/vyruz1986/FlyballSensor

body:
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


body:
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();


message:
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?

body:
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.


body: 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](http://en.wikipedia.org/wiki/Phase_detector).


body:
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`!


message:
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?

body: 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


body:
> 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.


message:
Question regarding powering Arduino through the USB Port

If powering the Arduino (Mega) through the USB port, is a voltage of 5.19VDC acceptable?

body: 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.


body:
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.


body:
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.


message:
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.
![enter image description here][1]

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.

  [1]: https://i.stack.imgur.com/ZoVbA.jpg

body:
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.


body:
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.


body:
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.