body:
I am currently playing with a MindWave Mobile headset. I am parsing bluetooth data received from a connected BlueSMIRF Silver.
The code I started from is a [sample from the MindWave wiki][1] and it works using hardware Serial.
For reference here is the original code:

    ////////////////////////////////////////////////////////////////////////
    // Arduino Bluetooth Interface with Mindwave
    //
    // This is example code provided by NeuroSky, Inc. and is provided
    // license free.
    ////////////////////////////////////////////////////////////////////////

    #define LED 13
    #define BAUDRATE 57600
    #define DEBUGOUTPUT 1

    #define GREENLED1  3
    #define GREENLED2  4
    #define GREENLED3  5
    #define YELLOWLED1 6
    #define YELLOWLED2 7
    #define YELLOWLED3 8
    #define YELLOWLED4 9
    #define REDLED1    10
    #define REDLED2    11
    #define REDLED3    12

    #define powercontrol 10

    // checksum variables
    byte generatedChecksum = 0;
    byte checksum = 0;
    int payloadLength = 0;
    byte payloadData[64] = {
      0};
    byte poorQuality = 0;
    byte attention = 0;
    byte meditation = 0;

    // system variables
    long lastReceivedPacket = 0;
    boolean bigPacket = false;

    //////////////////////////
    // Microprocessor Setup //
    //////////////////////////
    void setup() {

      pinMode(GREENLED1, OUTPUT);
      pinMode(GREENLED2, OUTPUT);
      pinMode(GREENLED3, OUTPUT);
      pinMode(YELLOWLED1, OUTPUT);
      pinMode(YELLOWLED2, OUTPUT);
      pinMode(YELLOWLED3, OUTPUT);
      pinMode(YELLOWLED4, OUTPUT);
      pinMode(REDLED1, OUTPUT);
      pinMode(REDLED2, OUTPUT);
      pinMode(REDLED3, OUTPUT);

      pinMode(LED, OUTPUT);
      Serial.begin(BAUDRATE);           // USB

    }

    ////////////////////////////////
    // Read data from Serial UART //
    ////////////////////////////////
    byte ReadOneByte() {
      int ByteRead;

      while(!Serial.available());
      ByteRead = Serial.read();

    #if DEBUGOUTPUT
      Serial.print((char)ByteRead);   // echo the same byte out the USB serial (for debug purposes)
    #endif

      return ByteRead;
    }

    /////////////
    //MAIN LOOP//
    /////////////
    void loop() {

      // Look for sync bytes
      if(ReadOneByte() == 170) {
        if(ReadOneByte() == 170) {

          payloadLength = ReadOneByte();
          if(payloadLength > 169)                      //Payload length can not be greater than 169
              return;

          generatedChecksum = 0;
          for(int i = 0; i < payloadLength; i++) {
            payloadData[i] = ReadOneByte();            //Read payload into memory
            generatedChecksum += payloadData[i];
          }

          checksum = ReadOneByte();                      //Read checksum byte from stream
          generatedChecksum = 255 - generatedChecksum;   //Take one's compliment of generated checksum

            if(checksum == generatedChecksum) {

            poorQuality = 200;
            attention = 0;
            meditation = 0;

            for(int i = 0; i < payloadLength; i++) {    // Parse the payload
              switch (payloadData[i]) {
              case 2:
                i++;
                poorQuality = payloadData[i];
                bigPacket = true;
                break;
              case 4:
                i++;
                attention = payloadData[i];
                break;
              case 5:
                i++;
                meditation = payloadData[i];
                break;
              case 0x80:
                i = i + 3;
                break;
              case 0x83:
                i = i + 25;
                break;
              default:
                break;
              } // switch
            } // for loop

    #if !DEBUGOUTPUT

            // *** Add your code here ***

            if(bigPacket) {
              if(poorQuality == 0)
                digitalWrite(LED, HIGH);
              else
                digitalWrite(LED, LOW);
              Serial.print("PoorQuality: ");
              Serial.print(poorQuality, DEC);
              Serial.print(" Attention: ");
              Serial.print(attention, DEC);
              Serial.print(" Time since last packet: ");
              Serial.print(millis() - lastReceivedPacket, DEC);
              lastReceivedPacket = millis();
              Serial.print("\n");
            }
    #endif
            bigPacket = false;
          }
          else {
            // Checksum Error
          }  // end if else for checksum
        } // end if read 0xAA byte
      } // end if read 0xAA byte
    }

One problem I have is the blocking while loop in the ReadOneByte function:

    byte ReadOneByte() {
      int ByteRead;

      while(!Serial.available());
      ByteRead = Serial.read();

    #if DEBUGOUTPUT
      Serial.print((char)ByteRead);   // echo the same byte out the USB serial (for debug purposes)
    #endif

      return ByteRead;
    }

I am trying to avoid this so I started drafting a basic state machine approach:

    #define BAUDRATE 57600

    // checksum variables
    byte generatedChecksum = 0;
    byte checksum = 0;
    int payloadLength = 0;
    byte payloadData[169] = {0};
    byte poorQuality = 0;
    byte attention = 0;
    byte meditation = 0;

    // system variables
    long lastReceivedPacket = 0;
    boolean bigPacket = false;

    int payloadIndex;

    int state = 0;
    const int STATE_WAIT_FOR_FIRST_A        = 0;
    const int STATE_WAIT_FOR_SECOND_A       = 1;
    const int STATE_WAIT_FOR_PAYLOAD_LENGTH = 2;
    const int STATE_WAIT_FOR_PAYLOAD        = 3;
    const int STATE_WAIT_FOR_CHECKSUM       = 4;
    const String stateNames[5] = {"waiting for first A","waiting for second A","waiting for payload length","accumulating payload","waiting for checksum"};

    void setup() {
      Serial.begin(BAUDRATE);           // USB
    }
    void loop() {}
    void parsePayload(){
      poorQuality = 200;
      attention = 0;
      meditation = 0;

      for(int i = 0; i < payloadLength; i++) {    // Parse the payload
        switch (payloadData[i]) {
        case 2:
          i++;
          poorQuality = payloadData[i];
          bigPacket = true;
          break;
        case 4:
          i++;
          attention = payloadData[i];
          break;
        case 5:
          i++;
          meditation = payloadData[i];
          break;
        case 0x80:
          i = i + 3;
          break;
        case 0x83:
          i = i + 25;
          break;
        default:
          break;
        } // switch
      } // for loop
      Serial.print("bigPacket:");
      Serial.println(bigPacket);
      if(bigPacket) {
        Serial.print("PoorQuality: ");
        Serial.print(poorQuality, DEC);
        Serial.print(" Attention: ");
        Serial.print(attention, DEC);
        Serial.print(" Time since last packet: ");
        Serial.print(millis() - lastReceivedPacket, DEC);
        lastReceivedPacket = millis();
        Serial.print("\n");
      }
      bigPacket = false;
    }

    void printState(){
      Serial.print("state:");
      Serial.println(stateNames[state]);
    }
    void serialEvent(){
      if(Serial.available() > 0){
        switch(state){
          case STATE_WAIT_FOR_FIRST_A:
            printState();
            if(Serial.read() == 170) state = STATE_WAIT_FOR_SECOND_A;
          break;
          case STATE_WAIT_FOR_SECOND_A:
            printState();
            if(Serial.read() == 170) state = STATE_WAIT_FOR_PAYLOAD_LENGTH;
          break;
          case STATE_WAIT_FOR_PAYLOAD_LENGTH:
            printState();
            payloadLength = Serial.read();
            Serial.print("payloadLength:");Serial.println(payloadLength);
            if(payloadLength > 169){
              Serial.println(payloadLength > 169);
              state = STATE_WAIT_FOR_FIRST_A;
              return;
            }
            generatedChecksum = payloadIndex = 0;
            state = STATE_WAIT_FOR_PAYLOAD;
          break;
          case STATE_WAIT_FOR_PAYLOAD:
            printState();
            if(payloadIndex < payloadLength){
              payloadData[payloadIndex] = Serial.read();
              generatedChecksum += payloadData[payloadIndex];
              Serial.print("payloadData[");Serial.print(payloadIndex);Serial.print(" of ");Serial.print(payloadLength);Serial.print("]: ");
              Serial.println(payloadData[payloadIndex]);
            }else{
              state = STATE_WAIT_FOR_CHECKSUM;
            }
          break;
          case STATE_WAIT_FOR_CHECKSUM:
            printState();
            checksum = Serial.read();
            generatedChecksum = 255 - generatedChecksum;
            if(checksum == generatedChecksum) {
              Serial.println("checksum MATCH! parsing payload");
              parsePayload();
              state = STATE_WAIT_FOR_FIRST_A;
            }else{
              Serial.println("checksum FAIL!");
              state = STATE_WAIT_FOR_FIRST_A;
            }
          break;
        }
      }
    }

As far as I can understand from the [serialEvent() reference][2] this function would be called only when a new byte is available. I've also added a condition to check if `Serial.available() > 0`.

I can see the messages I expect when parsing the data, but only small packets(usually 4 bytes long) end up having a correct checksum and never receive a payload with the useful EEG data I'm looking for.

How can I check that my approach is correct or not/ I'm not loosing bytes using `serialEvent()` instead of the blocking `while(!Serial.available())` ?
If so, how can I rewrite the while loop in a non blocking way ?

I've not super experienced with Arduino, but I started reading on interrupts. Would a `USART_RX` interrupt help at all ? (or would it do the same as serialEvent -> trigger when a new byte is available?)

**Update!**
Using Wirewrap's suggestion to use read() which returns -1 if there is no data, I've used [peek()][3] which does almost the same, except it doesn't remove the character peeked at from the buffer.
For reference here is the code used:

    #define BAUDRATE 57600
    #define DEBUGOUTPUT 1

    // checksum variables
    byte generatedChecksum = 0;
    byte checksum = 0;
    int payloadLength = 0;
    int payloadIndex;
    byte payloadData[169] = {0};
    byte poorQuality = 0;
    byte attention = 0;
    byte meditation = 0;

    // system variables
    long lastReceivedPacket = 0;
    boolean bigPacket = false;

    int state = 0;
    const int STATE_WAIT_FOR_FIRST_A        = 0;
    const int STATE_WAIT_FOR_SECOND_A       = 1;
    const int STATE_WAIT_FOR_PAYLOAD_LENGTH = 2;
    const int STATE_WAIT_FOR_PAYLOAD        = 3;
    const int STATE_WAIT_FOR_CHECKSUM       = 4;

    void setup() {
      Serial.begin(BAUDRATE);           // USB
    }
    void loop() {}
    void parsePayload(){
      poorQuality = 200;
      attention = 0;
      meditation = 0;

      for(int i = 0; i < payloadLength; i++) {    // Parse the payload
        switch (payloadData[i]) {
        case 2:
          i++;
          poorQuality = payloadData[i];
          bigPacket = true;
          break;
        case 4:
          i++;
          attention = payloadData[i];
          break;
        case 5:
          i++;
          meditation = payloadData[i];
          break;
        case 0x80:
          i = i + 3;
          break;
        case 0x83:
          i = i + 25;
          break;
        default:
          break;
        } // switch
      } // for loop
      if(bigPacket) {
        Serial.print("PoorQuality: ");
        Serial.print(poorQuality, DEC);
        Serial.print(" Attention: ");
        Serial.print(attention, DEC);
        Serial.print(" Time since last packet: ");
        Serial.print(millis() - lastReceivedPacket, DEC);
        lastReceivedPacket = millis();
        Serial.print("\n");
      }
      bigPacket = false;
    }

    void serialEvent(){
      if(Serial.peek() >= 0){
        switch(state){
          case STATE_WAIT_FOR_FIRST_A:
            if(Serial.read() == 170) state = STATE_WAIT_FOR_SECOND_A;
          break;
          case STATE_WAIT_FOR_SECOND_A:
            if(Serial.read() == 170) state = STATE_WAIT_FOR_PAYLOAD_LENGTH;
          break;
          case STATE_WAIT_FOR_PAYLOAD_LENGTH:
            payloadLength = Serial.read();
            if(payloadLength > 169){
              state = STATE_WAIT_FOR_FIRST_A;
              return;
            }
            generatedChecksum = payloadIndex = 0;
            state = STATE_WAIT_FOR_PAYLOAD;
          break;
          case STATE_WAIT_FOR_PAYLOAD:
            if(payloadIndex < payloadLength){
              payloadData[payloadIndex] = Serial.read();
              generatedChecksum += payloadData[payloadIndex];
              payloadIndex++;
            }else{
              state = STATE_WAIT_FOR_CHECKSUM;
            }
          break;
          case STATE_WAIT_FOR_CHECKSUM:
            checksum = Serial.read();
            generatedChecksum = 255 - generatedChecksum;
            if(checksum == generatedChecksum) {
              parsePayload();
              state = STATE_WAIT_FOR_FIRST_A;
            }else{
              state = STATE_WAIT_FOR_FIRST_A;
            }
          break;
        }
      }
    }

  [1]: http://developer.neurosky.com/docs/doku.php?id=mindwave_mobile_and_arduino
  [2]: http://arduino.cc/en/Reference/SerialEvent
  [3]: http://file://localhost/Applications/Arduino.app/Contents/Resources/Java/reference/Serial_Peek.html

title: How to avoid blocking while loop reading Serial?

Answers: 4

body:
I don't like `serialEvent()` because [it only checks to see if it should run that function after the whole loop is executed](https://github.com/arduino/Arduino/blob/master/hardware/arduino/avr/cores/arduino/main.cpp#L40-L45). With your new example, it's basically the same as the original (except you moved that code to the very bottom of the loop).

I'm not sure exactly how fast the data is sent, but you should first ask yourself if the data is sent fast enough that you don't even notice that it's blocking. Blocking code isn't bad itself (except maybe from a standpoint of the other device freezing up and stalling your program), but blocking code *that takes a long time* is bad.

Since you need five bytes, the best thing would be to wrap the blocking code in an if statement like this:

    if(Serial.available >= 5) {
      //Blocking code here
    }

It's simple and readable, yet effective.

body:
Interestingly enough, **Serial.read()** does not work like most of us think.

Serial.read() is not blocking, it always returns immediately with a byte 0-255 or -1 if there is no character to read.

From Arduino Reference
>**Description**
>
>Reads incoming serial data. read() inherits from the Stream utility class.
>
>**Syntax**
>
>Serial.read()
>
>**Parameters**
>
>None
>
>**Returns**
>
>the first byte of incoming serial data available (or -1 if no data is available) - int

body:
Since then I've figured out how to rewrite the code to be non-blocking, by replacing the while loop with states, accumulating one byte at a time.

I've written my first Arduino library with this occasion: [Mindwave][1].
Here's a basic example:

    #include <Mindwave.h>                   //import the library
    Mindwave mindwave;                      //start using it

    void setup() {
      Serial.begin(MINDWAVE_BAUDRATE);      //setup serial communication (MindWave mobile is set to 57600 baud rate)
    }
    //create a function to received new values as soon as they're avaialble
    void onMindwaveData(){
      Serial.print("attention: ");
      Serial.println(mindwave.attention()); //access attention value
    }
    void loop() {
      mindwave.update(Serial,onMindwaveData);//update using the data input(Serial in this case) and the function to call when data is ready
    }
It's non blocking, you can see the implementation [here][2]

This was used for the [Walk with Me][3] art installation.

![Walk with Me installation image 1][4]

![Walk with Me installation image 2][5]

![Bluetooth and DMX Shield for the Walk with Me installation][6]

  [1]: https://github.com/orgicus/Mindwave
  [2]: https://github.com/orgicus/Mindwave/blob/master/Mindwave.cpp
  [3]: https://hackaday.io/project/5969-walk-with-me
  [4]: https://i.stack.imgur.com/vvFjG.jpg
  [5]: https://i.stack.imgur.com/oFQ3N.jpg
  [6]: https://i.stack.imgur.com/RLNAa.jpg

body:
Nick Gammon, a moderator on the official Arduino site and a very active member of the Arduino community on Stackoverflow, has done a very nice post on [reading serial without blocking][1]. I've posted the relevant code.
    /*
    Example of processing incoming serial data without blocking.

    Author:   Nick Gammon
    Date:     13 November 2011.
    Modified: 31 August 2013.

    Released for public use.
    */

    // how much serial data we expect before a newline
    const unsigned int MAX_INPUT = 50;

    void setup (){
    Serial.begin (115200);
    } // end of setup

    // here to process incoming serial data after a terminator received
    void process_data (const char * data)
     {
     // for now just display it
     // (but you could compare it to some value, convert to an integer, etc.)
     Serial.println (data);
     }  // end of process_data

    void processIncomingByte (const byte inByte)
    {
      static char input_line [MAX_INPUT];
      static unsigned int input_pos = 0;

    switch (inByte)
      {

      case '\n':   // end of text
        input_line [input_pos] = 0;  // terminating null byte

        // terminator reached! process input_line here ...
        process_data (input_line);

        // reset buffer for next time
        input_pos = 0;
        break;

      case '\r':   // discard carriage return
        break;

      default:
        // keep adding if not full ... allow for terminating null byte
        if (input_pos < (MAX_INPUT - 1))
          input_line [input_pos++] = inByte;
        break;

      }  // end of switch

    } // end of processIncomingByte

    void loop()
    {
    // if serial data available, process it
    while (Serial.available () > 0)
      processIncomingByte (Serial.read ());

    // do other stuff here like testing digital input (button presses) ...

    }  // end of loop

  [1]: http://www.gammon.com.au/serial


body:
Arduino Day is so popular! Many boards are cheap during arduino day. So should I buy a [genuine arduino board][1] or [a sainsmart board?][2]

  [1]: https://day.arduino.cc/#/
  [2]: http://eepurl.com/biaWzT

title: Buy a genuine arduino board or a sainsmart board?

Answers: 2

body:
Buying an official board can be a good choice for a couple of main reasons. First of all, you're guaranteed a good quality board which conforms to the official schematic, and is definitely compatible with any relevant official software and hardware. If the board turns out to be faulty when you get it, you'll be able to get it replaced. Additionally, buying official boards means some of the money you spend goes towards funding future Arduino projects.

As you've no doubt seen, cloned (i.e. unofficial) boards based on Arduino are often much cheaper. Nonetheless, many of the boards are very good. Functionally, you might not see any difference whatsoever from the official/genuine boards. Some of them actually have some additional features which you might find useful depending on your project, such as switching the IO pins between 3.3v and 5v.

However, not all cloned boards are worth using. Some of them may have lower quality components. It's even possible that they weren't designed/constructed correctly in the first place. This could lead to a range of problems, from incompatibilities through to outright failure of the hardware. Given the geographic location of some of the manufacturers/sellers, you may not have any way to get a refund if something goes wrong.

If you choose to use a clone, look for a brand which other people have had success with. Also do your best to ensure the board uses the correct microcontroller (e.g. the Atmega328 for boards based on the Uno).

Ultimately, the decision is up to you. There's no 'right' answer necessarily.

body:
Going by the number of complaints seen about Sainsmart assemblies in the Arduino forum, I would suggest original.

You're also less likely to get a "go ask in the Sainsmart forum" reply when you ask for help in the Arduino forum.


body:
In the current project I'm programming simultaneously an UNO board and a Leonardo one.

Switching back and forth between the two boards in the **Tools** menu takes too much time because of the other 18 boards that I do not own anyway.

Is there a way to remove those boards from the Tools menu?

title: Remove unused boards from Arduino IDE

Answers: 2

body:
After some more investigation of the IDE folder, I found a text file called **boards.txt** in the following path.

     [Arduino Path]/hardware/arduino/boards.txt

EDIT: Be sure to make a copy of the file in case you mess up the following part.

Between two series of '**#**' characters there will be all the information on a specific microcontroller (e.g *uno.name=Arduino Uno*). Deleting every line of text between the two '**#**' series will have the desired effect of removing the board from the **Tools** menu.

body:
You can open two Arduino IDE windows, and use Tools / Board to set each of them to one of the two kinds of boards you are programming.   Ie, you can have multiple IDE windows open, with different options selected in each.  I've programmed an Uno and a Nano device with the same program from two different windows simultaneously (ie, RX lights blinking on both boards at the same time) without problems.

You can use one USB cable and one port, or can use a separate USB cable for each window.  You might need to use Tools / Port occasionally if the port number changes when you recable things.

I have the external editor option selected.  Text in each Arduino IDE window updates when I click Verify or Load, rather than each time I save the file in emacs.  I don't know how it works if you aren't using an external editor and have the same file open in two IDE windows.


body:
My arduino has these two capacitors

![enter image description here][1]

But I can't find any 47uf capacitors on the schematic. Is this not the value but instead a code? Where are these in the schematic?

![enter image description here][2]

  [1]: https://i.stack.imgur.com/0wRA6.jpg
  [2]: https://i.stack.imgur.com/psqR4.png

title: Where are these capacitors on the arduino schematic?

Answers: 1

body:
**What:** Looking at the schematic that you provided, it seems likely that they serve as C6 & C7.

**Why:** These are shown as 100 uF each and act as "filter" capacitors for IC4, the 5V regulator.
Within certain limits, such capacitors are not critical in value, and the manufacturer has probably decided that a factor of in the capacitance is probably acceptable.
They are probably correct :-).

**How to check:** You can check this yourself with an Ohm-meter set to the lowest Ohm range available - often = 200 Ohms max.

Turn off power to the board and leave it off for say 5 minutes to allow capacitors to discharge.
Locate I4 and find its input and output pins or tracks leading to them. You can often get ohmic connections at vias as the tracks change board layers.
IC4 pin1 will be grounded.
One lead of C6 & C7 are also grounded.
The pad you can see in your photo on the board edge side of the caaps is probably the -ve terminals (about 99%+ likely) (and they match the can markings)
and the "stippled" surface is almost certainly system ground.

If you can confirm that the two caps are connected to ground as and where described above, then:

Apply Ohm meter probes between the non ground lead of a capacitor and each non-ground pin in turn of IC4. One of them will be a low resistance connection if they are C6 & C7. Check the other capacitor - it should connect to the other side of IC4.
Reversing the meter leads in each case may give somewhat different readings for non-hard-connected points but should be low and consistent for hard-connected by a track points.


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

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

Answers: 1

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.


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

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

Answers: 2

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"


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

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

Answers: 3

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.


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

title: Android stops reading from bluetooth module

Answers: 2

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


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

title: How to share a library on Arduino Playground?

Answers: 1

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


body:
<!-- language-all: lang-C++ -->

I'm trying to configure a Zigbee sensor network. My "gateway (coordinator)" and "End devices" are made with XBeePro S2B model and configured in API mode "2". The "gateway (coordinator)" also has a SIM900 module, for uploading data to website (recieved on XBee), and Atmega 328p for codes (for "gateway (coordinator)" I'm using a Gboard device [here][1]), and for "End devices", I make/print a PCB with a atmega328p, XBee and PIR sensor.

The configuration works fine with several "End devices" (sincerilly, I have only tested with two "End devices", because it is expensive)...

The problem is when the "gateway (coordinator)" recieve data from more than one "End devices" **at the same time**. In this situation ("End devices" sending simultaneously) the "gateway (coordinator)" only recieves one packet (and only uploads that data to the website). I'm sure that I have a trouble with my code (sorry for the desestructurated and chaotic code, I'm a newbie).

Can anyone help me with the code?

code "gateway (coordinator)":

    #include <elapsedMillis.h>
    #include <SoftwareSerial.h>
    #include <Streaming.h>
    #include <XBee.h>
    int xbeeRecibido;
    char urlArreglo[100];
    uint8_t slCmd[] = {'S','L'};
    uint8_t dbCmd[] = {'D','B'};
    char adr_part[8];
    char rssiValor_part[8];
    String adr="";
    String rssiValor="";
    AtCommandRequest atRequest = AtCommandRequest();
    AtCommandResponse atResponse = AtCommandResponse();
    elapsedMillis timeElapsed = 0;
    unsigned long interval = 1800000 ;////en milisegundos  cada 30 min.
    String direccionRed;
    int bateria;
    String valorRssi;
    int actividadPir;
    String datosHttp; ///concatenacion de datos para enviar por HTTP
    int8_t answer;
    char data[512];
    int data_size;
    char aux_str[100];
    char aux;
    int x = 0;
    XBee xbee = XBee();//XBee object
    Rx16Response rx = Rx16Response();
    SoftwareSerial mySerial(2, 3); //PARA GPRS SIM900
    //int b00;  //este seria el primero, que se pierde al buscar el 0X7E
    int b01;
    int b02;
    int b03;
    int b04; //source network adress 64Bit
    int b05; //source network adress 64Bit
    int b06; //source network adress 64Bit
    int b07; //source network adress 64Bit
    int b08; //source network adress 64Bit
    int b09; //source network adress 64Bit
    int b10; //source network adress 64Bit
    int b11; //source network adress 64Bit
    int b12; //source network adress 16Bit
    int b13; //source network adress 16Bit
    int b14;
    int b15; //pir digital
    int b16; //bateria
    int b17; //checksum
    void setup() {
       pinMode(14, OUTPUT);////led debug en 14 ((A0)DEBUGGGG!!!!
       pinMode(6, OUTPUT);///para encender SIM900 ...en pin6 HIGH de arduino GBOARD
       digitalWrite(6, HIGH);///para encender SIM900 ...en pin6 HIGH de arduino GBOARD
        mySerial.begin(9600);
        Serial.begin(9600);
    ///////GPRS////////
        power_on();
        delay(3000);
        sendATcommand("AT+ipr=9600", "OK", 2000);///////MIO PARA BAUDERATE A 9600 (por defecto 0=auto..¿se apaga?)
        // sets the PIN code
        sendATcommand("AT+CPIN=****", "OK", 2000);
        delay(3000);
        while (sendATcommand2("AT+CREG?", "+CREG: 0,1", "+CREG: 0,5", 2000) == 0);
        sendATcommand("AT+SAPBR=3,1,\"Contype\",\"GPRS\"", "OK", 2000);
        sendATcommand("AT+SAPBR=3,1,\"APN\",\"gprsmov.pepephone.com\"", "OK", 2000);
        sendATcommand("AT+SAPBR=3,1,\"USER\",\"\"", "OK", 2000);
        sendATcommand("AT+SAPBR=3,1,\"PWD\",\"\"", "OK", 2000);
        while (sendATcommand("AT+SAPBR=1,1", "OK", 20000) == 0)
        {
            delay(5000);
        }
    ////FIN GPRS////
    lanzarHttpAutoControl();
    delay(15000);
    }

    void loop() {
    if (timeElapsed > interval)
     {
            lanzarHttpAutoControl();
            delay(15000);
     timeElapsed = 0;
     }
    if (Serial.available()==18) {//make sure the frame is all there
      if (Serial.read()==0x7E) {
         b01 = Serial.read();
         b02 = Serial.read();
         b03 = Serial.read();
         b04 = Serial.read(); //source network adress 64Bit
         b05 = Serial.read(); //source network adress 64Bit
         b06 = Serial.read(); //source network adress 64Bit
         b07 = Serial.read(); //source network adress 64Bit
         b08 = Serial.read(); //source network adress 64Bit
         b09 = Serial.read(); //source network adress 64Bit
         b10 = Serial.read(); //source network adress 64Bit
         b11 = Serial.read(); //source network adress 64Bit
         b12 = Serial.read(); //source network adress 16Bit
         b13 = Serial.read(); //source network adress 16Bit
         b14 = Serial.read();
         b15 = Serial.read(); //pir digital
         b16 = Serial.read(); //bateria
         b17 = Serial.read();  //checksum
         direccionRed =  String(b04, HEX);
         direccionRed +=  String(b05, HEX);
         direccionRed +=  String(b06, HEX);
         direccionRed +=  String(b07, HEX);
         direccionRed +=  String(b08, HEX);
         direccionRed +=  String(b09, HEX);
         direccionRed +=  String(b10, HEX);
         direccionRed +=  String(b11, HEX);
         actividadPir = b15;
         bateria = int(b16);
         digitalWrite(14, HIGH);//FOR DEBUG LED
         delay(1000);//FOR DEBUG LED
         digitalWrite(14, LOW);//FOR DEBUG LED
         xbeeRecibido = 1;
            } //fin if 0x7E
      }///fin recorrer bytes
       else {
             if (xbeeRecibido == 1) {///si se ha recibido info de xbee sensor
             colectorDatos();
             xbeeRecibido = 0;
            }
       }
    delay (10);
    }//fin loop

    void rss() {  ///PARA RSSI
       /* returns received signal strength value for the last RF data packet */
       union {byte B; char C;} atCmd[3];
       AtCommandRequest atCmdReq;
       AtCommandResponse atResp;
       byte respLen, *resp, dBm;
       strcpy(&atCmd[0].C, "DB");
       atCmdReq = AtCommandRequest(&atCmd[0].B);
       atResp = AtCommandResponse();
       xbee.send(atCmdReq);
       if (xbee.readPacket(5000)) {
           if (xbee.getResponse().getApiId() == AT_COMMAND_RESPONSE) {
               xbee.getResponse().getAtCommandResponse(atResp);
               if (atResp.isOk()) {
                   respLen = atResp.getValueLength();
                   if (respLen == 1) {
                       resp = atResp.getValue();
                       dBm = resp[0];
                       valorRssi = (String)dBm;
                   }
                   else {
                   }
               }
               else {
               }
           }
           else {
           }
       }
       else {
       }
    }///fin rss()

    void power_on(){
        uint8_t answer=0;
        // checks if the module is started
        answer = sendATcommand("AT", "OK", 2000);
        if (answer == 0)
        {
            // waits for an answer from the module
            while(answer == 0){
                // Send AT every two seconds and wait for the answer
                answer = sendATcommand("AT", "OK", 2000);
            }
        }
    }

    int8_t sendATcommand(char* ATcommand, char* expected_answer1, unsigned int timeout){
        uint8_t x=0,  answer=0;
        char response[100];
        unsigned long previous;
        memset(response, '\0', 100);    // Initialize the string
        delay(100);
        while( mySerial.available() > 0) mySerial.read();    // Clean the input buffer
        mySerial.println(ATcommand);    // Send the AT command
            x = 0;
        previous = millis();
        // this loop waits for the answer
        do{
            if(mySerial.available() != 0){
                response[x] = mySerial.read();
                x++;
                // check if the desired answer is in the response of the module
                if (strstr(response, expected_answer1) != NULL)
                {
                    answer = 1;
                }
            }
            // Waits for the asnwer with time out
        }
        while((answer == 0) && ((millis() - previous) < timeout));
        return answer;
    }

    int8_t sendATcommand2(char* ATcommand, char* expected_answer1,
    char* expected_answer2, unsigned int timeout){
        uint8_t x=0,  answer=0;
        char response[100];
        unsigned long previous;
        memset(response, '\0', 100);    // Initialize the string
        delay(100);
        while( mySerial.available() > 0) mySerial.read();    // Clean the input buffer
        mySerial.println(ATcommand);    // Send the AT command
            x = 0;
        previous = millis();
        // this loop waits for the answer
        do{
            if(mySerial.available() != 0){
                response[x] = mySerial.read();
                x++;
                // check if the desired answer 1 is in the response of the module
                if (strstr(response, expected_answer1) != NULL)
                {
                    answer = 1;
                }
                // check if the desired answer 2 is in the response of the module
                if (strstr(response, expected_answer2) != NULL)
                {
                    answer = 2;
                }
            }
         // Waits for the asnwer with time out
        }while((answer == 0) && ((millis() - previous) < timeout));
        return answer;
    }

    void colectorDatos(){ ///funcion para recolectar datos recibidos del xbee y gestionarlos para enviarlos por GPRS
        rss(); ////recupero rssi que se pone en variable valorRssi
        datosHttp = direccionRed +";"; ///cualquier valor del array, todos deverian tener mismo valor (direccion64bits)
        datosHttp += bateria;
        datosHttp += ";";
        datosHttp += valorRssi;
        datosHttp += ";";
        datosHttp += actividadPir; //pir
        envio(datosHttp); ///envio por gprs
    }///fin colectorDatos

    void lanzarHttpAutoControl() {
      adr="";
      atRequest.setCommand(slCmd);  // set command to SL to get low part of MAC address
      while (!sendAtCommand()) {};
      for (int i = 0; i < atResponse.getValueLength(); i++) {
        mySerial.print(atResponse.getValue()[i], HEX);
        sprintf(adr_part, "%lX", (unsigned long)(atResponse.getValue()[i]));
        if (atResponse.getValue()[i]<=0xF)
            adr += 0;
            adr += adr_part;
      }
      envio(adr); ///envio por gprs

    }

    void envio(String entrada){///envio GPRS...recibe String con datos (o control o sensor)
       memset(urlArreglo, 0, sizeof(urlArreglo));///a cero el array
        answer = sendATcommand("AT+HTTPINIT", "OK", 10000);
        if (answer == 1)
        {
            // Sets CID parameter
            answer = sendATcommand("AT+HTTPPARA=\"CID\",1", "OK", 5000);
            if (answer == 1)
            {
          sprintf(urlArreglo,  "AT+HTTPPARA=\"URL\",\"www.pestmonitors.com/dream/prueba_gsm_get.php?datos=%s\"",entrada.c_str());
          answer = sendATcommand(urlArreglo, "OK", 5000);
           delay(5000);
                if (answer == 1)
                {
                    answer = sendATcommand("AT+HTTPACTION=0", "+HTTPACTION:0,200", 10000);
                }
        else
        {
        }
        sendATcommand("AT+HTTPTERM", "OK", 5000);
        delay(5000);
          }
        }
    }

    int sendAtCommand() { // used here to sens AT command to the Xbee to get information such as the MAC address
      xbee.send(atRequest);
      if (xbee.readPacket(5000)) {
        if (xbee.getResponse().getApiId() == AT_COMMAND_RESPONSE) {
          xbee.getResponse().getAtCommandResponse(atResponse);
          if (atResponse.isOk()) {
            if (atResponse.getValueLength() > 0) {
              mySerial.println(atResponse.getValueLength(), DEC);
              for (int i = 0; i < atResponse.getValueLength(); i++) {
                mySerial.print(atResponse.getValue()[i], HEX);
              }
            }
            return 1;
          }
          else {
          }
        } else {
          mySerial.print(xbee.getResponse().getApiId(), HEX);
        }
      } else {
        if (xbee.getResponse().isError()) {
        }
        else {
        }
      }
      return 0;
    }

code "End devices":

    #include <Sleep_n0m1.h>
    #include <XBee.h>
    XBee xbee = XBee();
    uint8_t payload[] = { 0, 0 };
    XBeeAddress64 addr64 = XBeeAddress64(0x0, 0xFFFF);
    ZBTxRequest zbTx = ZBTxRequest(addr64, payload, sizeof(payload));
    ZBTxStatusResponse txStatus = ZBTxStatusResponse();
    boolean apagar;
    int battVolts;
    int PinEntradaBat = A0;
    int valorBateriaTotal;
    int valorBateria;
    int mapeoValorBateria;
    Sleep sleep;
    unsigned long sleepTime; //how long you want the arduino to sleep
    int salida = 7; ////pin salida 7 para DTR xbee
    int entradaInterrumpirSleep =2; ////pin desde pir para interrumpir/despertar
    boolean abortSleep; //cancel sleep cycle
    int modo;
    int cicloTiempoSleep;///establecer ciclo alarma
    int numeroCiclos; ///para retomar ciclo si falsa alarma
    boolean enviado; ///para comprobar si recepción de xbbe, sino, reenviar!
    uint8_t atdCmd[]={'D','5'};
    uint8_t value[]={4};///pongo DIO5 a output LOW
    uint8_t length=1;
    AtCommandRequest atRequest = AtCommandRequest(atdCmd, value, length);
    AtCommandResponse atResponse = AtCommandResponse();
    //boolean saltarPrimerPir = true; ////PARA NUEVO PIR, SALTAR LA ALARMA AL ARRANCAR ¿PORQUE?
    void setup()
    {
      analogReference(DEFAULT);
      enviado = true;
      numeroCiclos = 0;
      apagar = false;
      pinMode(salida, OUTPUT); //para DTR en xbee
      pinMode(6, OUTPUT); //para MOSFET (en digitalPin6 PWM)!!
      digitalWrite(salida, LOW); //EMITE 5V HACIA DTR, ENVIAR EN XBEE
      delay(120000);//2 minutos para evitar primer interrupt!y dar tiempo a comprobar tecnico la asociación
      abortSleep = false; //can be used to cancel the sleep cycle
      sleep.setCalibrationInterval(1);
      sleepTime = 1000;//set sleep time in ms, max sleep time is 49.7 days (1/2 1 min)
      modo = 0; //para empezar con modo CONTROL
      numeroCiclos = 0;
      Serial.begin(9600);
      xbee.setSerial(Serial);
      xbee.send(atRequest);// set command to ATD50 to stop LED Assoc...////DESCOMENTAR PARA APAGAR LED ASSOC!!!!!!
      delay(5000);
    }//fin setup

    void loop()
    {
    if (apagar == true) { ///APAGAR SI BATERIA MUY BAJA!!!!
      detachInterrupt(0);
      while (apagar == true) {
      }
    }
      if (modo == 0) {
        detachInterrupt(0);
        digitalWrite(salida, LOW); //EMITE 0V HACIA DTR, ENVIAR EN XBEE
        digitalWrite(6, HIGH); //EMITE 5V HACIA mosfet/regulador, ENCIENDE XBEE
        cicloTiempoSleep = 21600; //6 horas
        delay(10);
        enviarXbee(0);
        digitalWrite(salida, HIGH);//EMITE 5V HACIA DTR, ACTIVAR DTR (XBEE SLEEP)
        digitalWrite(6, LOW); //EMITE 0V HACIA mosfet/regulador, APAGAR
        delay(30000);///30seg de inactividad post envio control!
        attachInterrupt(0, interrumpirPir, RISING);
      } //fin modo0 CONTROL
      if (modo == 1) {
            detachInterrupt(0);
            digitalWrite(salida, LOW); //EMITE 0V HACIA DTR, ENVIAR EN XBEE
            digitalWrite(6, HIGH); //EMITE 5V HACIA mosfet/regulador, ENCIENDE XBEE
            modo = 0; //modo CONTROL
            numeroCiclos = 0;
            cicloTiempoSleep = 21600; //6 horas para enviar CONTROL despues de ACTIVIDAD
            delay(10);
            enviarXbee(1);
            digitalWrite(salida, HIGH);//EMITE 5V HACIA DTR, ACTIVAR DTR (XBEE SLEEP)
            digitalWrite(6, LOW); //EMITE 0V HACIA mosfet/regulador, APAGAR
            delay(120000);///2 minutos de inactividad post envio alarma! (para no enviar otra enseguida)
            attachInterrupt(0, interrumpirPir, RISING);
      }//fin modo1 ACTIVIDAD
      abortSleep = false;
      for (int i=0; i < cicloTiempoSleep; i++){ /////ARREGLO CON FOR PARA REITERAR 1000ms (1seg) x VECES (hace extraños el int0 con SleepDelay juntos)
            numeroCiclos = i;
            sleep.pwrDownMode(); //set sleep mode
            sleep.sleepDelay(sleepTime,abortSleep); //sleep for: sleepTime
            if (abortSleep == true) {
              break;
            }
       }//fin contador tiempo
      if (cicloTiempoSleep <= 1 || numeroCiclos == --cicloTiempoSleep) { ///estos dos -- restan 1 al valor de la variable
        modo = 0;
      }
    }//fin loop

    void interrumpirPir() // si disparo PIR por interrupt0 (isr)
    {
      if (numeroCiclos != 0) {/////AQUI EVITAR PRIMERA INTERRUPCION AL INICIARSE EL SENSOR/////
      abortSleep = true;
      cicloTiempoSleep = cicloTiempoSleep - numeroCiclos;
      modo = 1;
      }//fin saltar primer PIR
    }///fin interrumpir! ISR

    void enviarXbee(int valorPir) // si disparo PIR por interrupt0 (isr)
    {
    battVolts=getBandgap();
    valorBateriaTotal = 0;
    for (int e=0; e < 20; e++)
        {
           mapeoValorBateria = map(analogRead(A1), 0, 1023, 0, battVolts);
           valorBateriaTotal = valorBateriaTotal + mapeoValorBateria;
         delay(10);
        }
    valorBateriaTotal = valorBateriaTotal/20;
    if (mapeoValorBateria <= 95) {///APAGAR SI BATERIA MUY BAJA!!!!
    apagar = true;
    }
        payload[0] = valorPir; ///PIR
        payload[1] = mapeoValorBateria & 0xff;
        delay (10000);
        xbee.send(zbTx);
        //delay (15000);
        if (xbee.readPacket(5000)) {
          if (xbee.getResponse().getApiId() == ZB_TX_STATUS_RESPONSE) {
            xbee.getResponse().getZBTxStatusResponse(txStatus);
            if (txStatus.getDeliveryStatus() == SUCCESS) {
             // enviado = true;
            } else {
            //  enviado = false;
            }
          }
        } else if (xbee.getResponse().isError()) {
        } else {
        }
    }//end enviar xbee

    long leerBateria()//para ver estado bateria
    {
    }
    int getBandgap(void) // Returns actual value of Vcc (x 100)
       {
    #if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
        // For mega boards
        const long InternalReferenceVoltage = 1115L;  // Adjust this value to your boards specific internal BG voltage x1000
           // REFS1 REFS0          --> 0 1, AVcc internal ref. -Selects AVcc reference
           // MUX4 MUX3 MUX2 MUX1 MUX0  --> 11110 1.1V (VBG)         -Selects channel 30, bandgap voltage, to measure
        ADMUX = (0<<REFS1) | (1<<REFS0) | (0<<ADLAR)| (0<<MUX5) | (1<<MUX4) | (1<<MUX3) | (1<<MUX2) | (1<<MUX1) | (0<<MUX0);
    #else
        // For 168/328 boards
        const long InternalReferenceVoltage = 1056L;  // Adjust this value to your boards specific internal BG voltage x1000
           // REFS1 REFS0          --> 0 1, AVcc internal ref. -Selects AVcc external reference
           // MUX3 MUX2 MUX1 MUX0  --> 1110 1.1V (VBG)         -Selects channel 14, bandgap voltage, to measure
        ADMUX = (0<<REFS1) | (1<<REFS0) | (0<<ADLAR) | (1<<MUX3) | (1<<MUX2) | (1<<MUX1) | (0<<MUX0);
    #endif
        delay(50);  // Let mux settle a little to get a more stable A/D conversion
           // Start a conversion
        ADCSRA |= _BV( ADSC );
           // Wait for it to complete
        while( ( (ADCSRA & (1<<ADSC)) != 0 ) );
           // Scale the value
        int results = (((InternalReferenceVoltage * 1023L) / ADC) + 5L) / 10L; // calculates for straight line value
        return results;
       }
    int sendAtCommand() {
      xbee.send(atRequest);
      if (xbee.readPacket(5000)) {// wait up to 5 seconds for the status response
        if (xbee.getResponse().getApiId() == AT_COMMAND_RESPONSE) {// should be an AT command response
          xbee.getResponse().getAtCommandResponse(atResponse);
          if (atResponse.isOk()) {
            if (atResponse.getValueLength() > 0) {
              for (int i = 0; i < atResponse.getValueLength(); i++) {
              }
            }
          }
          else {
          }
        } else {
        }
      } else {
        if (xbee.getResponse().isError()) {
        }
        else {
        }
      }
    }

Thank you very much. I really appreciate your help.
  [1]: http://imall.iteadstudio.com/im120411004.html

title: Several XBee End devices sending simultaneously; Only one packet recieved on coordinator

Answers: 0


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

title: Unusual behaviour when moving data to PROGMEM

Answers: 1

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.