body: So maybe it's a very low class form of question, but please bear with me. I'm working on a project with 7 HC-SR04 ultrasonic sensors connected to one Arduino. I tried to unify the trigger and echo pin, but the sensing isn't good enough, so I dropped the Uno and convert it to Mega. My question is, do I need external power source for those 7 Sensors? And how do I connect all of them? Thanks

title: Do multiple ultrasonic sensors need an external power source?

Answers: 2

body:
Well, according to [the datasheet](http://www.micropik.com/PDF/HCSR04.pdf) the "working current" is 15mA.  Even if you had all 7 working at once, which I doubt you will - you'll be working through them in sequence I guess - that would be just 105mA - way below the 800mA the Arduino's on-board regulator can supply, and only a fifth of what a USB port can provide.

The datasheet doesn't mention the quiescent (idle) current, but it will be a tiny fraction of that 15mA and so can mostly be ignored.  Running the sensors in sequence, which is the most likely scenario, would use about the same amount of current as if you had 1 sensor - or 20 sensors.  Most of the current consumption would be while you are actively producing an ultrasonic chirp.

So no, you don't need an external power supply to run them all - just take them all from the Arduino's 5V pin.

body:
You will probably not have any kind of problem with the Arduino power source, while in the test bench. When using it for the Drone/Bot you seem to be working, make sure to have a stable power source to the Arduino, and, if possible, let your sensors have their own energy input.

I had previous experiences with the sensors not working properly because the Arduino was not getting enough energy through the Arduino's pins when mounted.


body:
I have a question about using the Arduino and Processing. I want to build a touch sensor using aluminum foil and connect it to an interface built in Processing. However i've come across a problem. I don't know how to send the serial data from the Arduino to Processing. This is the code I'm using to get the sensor value from the aluminum foil:

    #include <CapacitiveSensor.h>

    CapacitiveSensor   cs_4_2 = CapacitiveSensor(4,2);

    void setup(){
      Serial.begin(9600);
    }

    void loop(){
      long start = millis();
      long total1 =  cs_4_2.capacitiveSensor(30);

      Serial.print(millis() - start);
      Serial.print("\t");

      Serial.print(total1);
      Serial.print("\t");
      Serial.print('\n');

      delay(100);
    }
The foil is connected to dig pin 4 with a resistor of 1M in between and to dig pin 2 with a resistor of 1K. Pin 4 is the send pin, pin 2 is the receive pin. It all works just fine, in the serial monitor in the Arduino software I get the value of the time between refreshes and the sensor value. But how do I use this sensor value in a Processing sketch? I thought of maybe using Firmata on the Arduino, but then I wouldn't know how to use the CapacitiveSensor library and get the sensor values. Does anyone know how to get this to work? Help would be greatly appreciated!

title: Sending serial data to Processing

Answers: 3

body: SparkFun has [a tutorial](https://learn.sparkfun.com/tutorials/connecting-arduino-to-processing) where they explain in great detail how to create a project where your Arduino communicates with Processing on your PC.

body: You're already half way there - you're sending the data from the Arduino.  All you need to do now is read up on how to use Serial in Processing (hint: Arduino is based on Processing, so you should already know most of it) in order to read what you're sending.

body:
Try to use this code:

    // Graphing sketch

    import processing.serial.*;

    Serial myPort;        // The serial port
    int xPos = 1;         // horizontal position of the graph

    void setup () {
    // set the window size:
    size(400, 300);

    // List all the available serial ports
    println(Serial.list());
    // I know that the first port in the serial list on my mac
    // is always my  Arduino, so I open Serial.list()[0].
    // Open whatever port is the one you're using.
    myPort = new Serial(this, Serial.list()[0], 9600);
    // don't generate a serialEvent() unless you get a newline character:
    myPort.bufferUntil('\n');
    // set inital background:
    background(0);
    }
    void draw () {
    // everything happens in the serialEvent()
    }

    void serialEvent (Serial myPort) {
    // get the ASCII string:
    String inString = myPort.readStringUntil('\n');

    if (inString != null) {
    // trim off any whitespace:
    inString = trim(inString);
    // convert to an int and map to the screen height:
    float inByte = float(inString);
    inByte = map(inByte, 0, 1023, 0, height);

    // draw the line:
    stroke(127,34,255);
    line(xPos, height, xPos, height - inByte);

    // at the edge of the screen, go back to the beginning:
    if (xPos >= width) {
    xPos = 0;
    background(0);
    }
    else {
    // increment the horizontal position:
    xPos++;
    }
    }
    }

Also look at: http://www.arduino.cc/en/Tutorial/Graph


body:
I want to make a RC mixer mixing two channels of a receiver.

What I have: a delta model plane, two servos, a receiver and a Arduino Nano.

So I'd like to mix the aileron (two channels) with the elevator(one channel).

EDIT: What I've done: I read the input of the receiver and wrote it to the servos. The problem: The servo stutters and the arduino displays false inputs.

    int pin = A0;
    int pin1 = A1;
    unsigned long duration;
    unsigned long dur;

    unsigned long duration2;
    unsigned long dur2;

    #include <Servo.h>

    Servo myservo;
    Servo myservo2;

    void setup()
    {
      Serial.begin(9600);
   myservo.attach(9);
    }

    void loop()
    {
      duration = pulseIn(pin, HIGH);
      dur = duration;
      Serial.println(dur);
      myservo.writeMicroseconds(dur);
      delay(50);
    //  duration2 = pulseIn(pin1, HIGH);
    //  dur2 = duration2-980/4-200;
    //  Serial.println(dur2);
    //  myservo2.write(dur2);
    }

title: How to make an RC mixer with the arduino

Answers: 1

body:
You do not need to use long for values from pulseIn, using int will be sufficient.

Your code is not complete, at least there is a missing '}' at the end of setup.

The slower the baud rate (9600) actually the more it interferes with timing code, to a point.  PWM is all timing code.  I would suggest 57,600.

You never set the servos to any pins.  And is using Servo lib needed? I have always used [analogWrite][1] with no problems.

You are not using parenthesis on your math (currently commented). It will not give you the result you expect. But you are somewhat on the right track, subtract 1500 from each pulse read, that will give you -/+ range. How you mix that depends on how your radio is setup (servo reversing, which channel is which). Keep in mind ailerons is 1 channel, so left aileron = -rightAileron.  Elevator up = that + elevator.  so;

aileronLeft = airleronChannel + elevatorChannel<br>
aileronRight = -airleronChannel + elevatorChannel

You do realize this a [$3 part][2]?

update: I have always used analogWrite, but I also always use good equipment. I see cautions that cheapo servos might be damaged with analogWrite. You can read more [here][3]. It has always worked for me.

  [1]: http://www.arduino.cc/en/Reference/analogWrite
  [2]: http://www.hobbyking.com/hobbyking/store/__6321__TURNIGY_V_Tail_Mixer_Ultra_small.html
  [3]: http://forum.arduino.cc/index.php?topic=5701.0


body:
I want to get emails read from a Hotmail account using an Arduino Uno. Is there a way to do it with SSL or is there a way to disable SSL?

    #include <SPI.h>
    #include <Ethernet.h>
    // Use comments to enable or disable this define for debug messages
    #define DEBUG_POP
    // Use comments to enable or disable the deleting of the mail
    #define ENABLE_DELETE_POP

    // The mac address must be an unique number
    // A mac generator is used:
    //   http://www.miniwebtool.com/mac-address-generator/
    byte mac[] = { 0xDE, 0x36, 0x5F, 0x0A, 0x19, 0x83 };
    // change network settings to yours
    IPAddress ip(192, 168, 1, 117);
    IPAddress gateway(192, 168, 1, 1);
    IPAddress subnet(255, 255, 255, 0);

    // Set the server POP3 address, the port, the user and password.
    // The POP3 mail server is something like this:
    //     mail.yourdomain.com, pop.yourdomain.com, pop3.yourdomain.com
    // Using PROGMEM for these causes a fail when trying to connect and log in.
    const char pop_server[] = "pop3.live.com";
    const int  pop_port = 995;
    const char pop_user[] = "xxxxxx@hotmail.com";
    const char pop_pass[] = "xxxxxx";

    // The number of milliseconds timeout for parseInt() and find().
    // The response time for the Server can still be 10 seconds.
    #define POP_TIMEOUT 10
    #define POP_TIMEOUT_DEFAULT 1000

    EthernetClient client;

    void setup()
    {
     Serial.begin(9600);
     Serial.println(F("\nArduino POP3 email reader"));

     pinMode(13, OUTPUT);     // the system led is used for testing

     // When the Ethernet Shield is used, there is also a SD card connected
     // to the SPI bus. Disable the SD card with chip select at pin 4.
     pinMode(4, OUTPUT);
     digitalWrite(4, HIGH);

     // Start Ethernet. Use only the 'mac' parameter for DHCP
     // Use 'mac' and 'ip' parameters for static IP address.
     //  Ethernet.begin( mac, ip);
     //  Ethernet.begin( mac, ip, gateway, gateway, subnet);
     if (Ethernet.begin(mac) == 0)
     {
      Serial.println("Failed to configure Ethernet using DHCP.");
      // no point in carrying on, so do nothing forevermore:
      while (1);
     }
     Ethernet.begin(mac, ip, gateway, gateway, subnet);
     // print your local IP address.
     Serial.println(F("Ethernet started."));
     Serial.print(F("Local IP = "));
     Serial.println(Ethernet.localIP());

     Serial.println(F("Press 'c' to check mail."));
    }

    void loop()
    {
     // Create a buffer to receive the commands in (that is the Subject of the mail).
     char buffer[32];

     byte inChar = Serial.read();
     if (inChar == 'c')
     {
      // The getEmail gets the text of the mail Subject into the buffer.
      // The valid number of received characters are returned.
      // If the return value is < 0, it is an error.
      int n = getEmail(buffer, sizeof(buffer));

      if (n < 0)
      {
       Serial.print(F("Email POP3 failed, error = "));
       Serial.println(n);
      }
      else
      {
       if (n == 0)
       {
        Serial.println(F("Ready, nothing to do."));
       }
       else
       {
        // 'n' is > 0, a command received.
        Serial.print(F("Email checked, Command = \""));
        Serial.print(buffer);
        Serial.println(F("\""));

        // Check the commands.
        //
        // At this moment, a single command 'L' is used to set system led on or off.
        //    L=1   (set led on)
        //    L=0   (set led off)
        if (buffer[0] == 'L' && buffer[1] == '=')
        {
         digitalWrite(13, buffer[2] == '0' ? LOW : HIGH);
        }
       }
      }
     }
    }

    // getEmail
    // --------
    // Find an email on a mail server, using POP3.
    // The Subject should start with "ARDUINO " and the text
    // after that is copied into pBuf.
    //
    // The data in pBuf is only valid if the return value is not an error
    // (an error is return value less than zero).
    //
    int getEmail(char *pBuf, int nBufSize)
    {
     // nBytes is the number of bytes that is returned by getEmail.
     int nBytes = 0;

     // Connect to server
     // client.connect returns '1' if okay, or negative number if error.
     //    SUCCESS 1
     //    0     (error, unknown timeout, perhaps an error in the library)
     //    TIMED_OUT -1
     //    INVALID_SERVER -2
     //    TRUNCATED -3
     //    INVALID_RESPONSE -4
     //    -5    (there is no mail server at that IP address and port)
     // The string for the server must be a normal string in sram, no PROGMEM allowed.
     int nError = client.connect(pop_server, pop_port);

     // During testing, a value of zero was sometimes returned.
     // This is not according to the documentation and it is an error.
     // Therefor the non-error value '0' is turned into a negative number to
     // indicate an error.
     if (nError == 0)
      return(-200);

     // Only a value of 1 is okay.
     if (nError != 1)
      return(nError);

    #ifdef DEBUG_POP
     Serial.println(F("connected"));
     //Serial.println(nError);
    #endif
     // The server should respond with "+OK" and maybe more text after that.
     // Check if "+OK" can be read.
     // The parameter 'true' is to read also everything after the "+OK".
     if (!readOk(true))
      return -102;

    #ifdef DEBUG_POP
     Serial.println(F("command USER"));
    #endif
     client.print(F("USER "));
     client.println(pop_user);
     if (!readOk(true))
      return -103;

    #ifdef DEBUG_POP
     Serial.println(F("command PASS"));
    #endif
     client.print(F("PASS "));
     client.println(pop_pass);
     if (!readOk(true))
      return -104;

    #ifdef DEBUG_POP
     Serial.println(F("command STAT"));
    #endif
     client.println(F("STAT"));
     if (!readOk(false))
      return -105;

     // The whole line was like this: "+OK 3 15343"
     // It means that 3 emails are waiting with a total size of 15343.
     // At this moment, the "+OK" is read, but nothing else.
     // Check if there is a space after "+OK".
     char c = client.read();
     if (c != ' ')
      return -106;

     client.setTimeout(POP_TIMEOUT);       // set timeout lower for parseInt
     // Read the number of emails that are on the server.
     int nMails = client.parseInt();
     client.setTimeout(POP_TIMEOUT_DEFAULT);  // restore timeout to 1 second

     // Read the remaining of the response to STAT.
     readRemaining();

    #ifdef DEBUG_POP
     Serial.print(F("Number of emails="));
     Serial.println(nMails);
    #endif

     // Test if there are emails waiting.
     if (nMails == 0)
     {
      // No emails, but no error. Set buffer to empty string.
      nBytes = 0;               // the returned value
      pBuf[0] = '\0';           // set empty string
     }
     else if (nMails > 0)
     {
      // emails are waiting.
      // Scan the emails until the first is found with the keyword "ARDUINO " at the
      // beginning of the "Subject: ".

      boolean found_and_ready = false;
      for (int nMailNumber = 1; nMailNumber <= nMails && !found_and_ready; nMailNumber++)
      {
       // The command RETR <x> gets the whole mail.
       // The command TOP <x> <size> gets the header plus 'size' of the body.

    #ifdef DEBUG_POP
       Serial.print(F("command TOP "));
       Serial.print(nMailNumber);
       Serial.println(F(" 0"));
    #endif
       client.print(F("TOP "));
       client.print(nMailNumber);
       client.println(F(" 0"));

       // Use readOk with parameter 'false' to stop reading after "+OK".
       if (!readOk(false))
        return -107;
       // The header of the email is waiting to be read, use the Stream.find() to look for the Subject.
       // The text "Subject: " should be at the beginning of a line, but that is not tested.
       // The first found text "Subject: " is assumed to be the real subject.
       // I have checked many years of emails, and the text is always "Subject: ", and never "SUBJECT: ".
       // At the moment, it is not possible to use the F() macro for Stream.find
       // Only the email that starts with "ARDUINO " at the start of the Subject is used.

       client.setTimeout(POP_TIMEOUT);      // set short timeout for find().
       // find() returns true if found and false if not.
       boolean foundsubject = client.find("Subject: ARDUINO ");
       client.setTimeout(POP_TIMEOUT_DEFAULT);   // restore timeout to 1 second

       if (foundsubject)
       {
    #ifdef DEBUG_POP
        Serial.println(F("Found an email for me"));
    #endif

        // Read the remaining subject (that is the command for the Arduino) into a buffer.
        // Every line from the mail server should end with CR + LF,
        // but to be sure, both CR and LF are checked.
        // Alternative:
        //    client.readBytesUntil('\r', pBuf, nBufSize);

        // The last position in the buffer is reserved for the zero terminator.
        // So read data until (nBufSize-1).
        int i;
        for (i = 0; i < (nBufSize - 1) && client.available(); i++)
        {
         char c = client.read();
         if (c == '\r' || c == '\n')
          break;
         pBuf[i] = c;
        }
        // Add zero terminator
        pBuf[i] = '\0';
        nBytes = i;     // the number of received bytes is returned by the getEmail() function.

        // More text of the header could be following the Subject.
        // That is read and disregarded.
        readRemaining();

    #ifdef DEBUG_POP
        Serial.print(F("Subject = \"ARDUINO "));
        Serial.print(pBuf);
        Serial.println(F("\""));
    #endif

    #ifdef ENABLE_DELETE_POP
        // Delete the just read message.
    #ifdef DEBUG_POP
        Serial.print(F("command DELE "));
        Serial.println(nMailNumber);
    #endif
        client.print(F("DELE "));
        client.println(nMailNumber);
        if (!readOk(true))
         return -108;
    #endif

        // Everything is okay, the mail is read and deleted.
        // Ready for now, don't process the remaining emails.
        found_and_ready = true;
       }
       else
       {
    #ifdef DEBUG_POP
        Serial.println(F("No ARDUINO keyword in subject"));
    #endif
        // This email has no "Subject: ARDUINO ".
        // But the remaining text has still to be read and disregarded.
        readRemaining();
       }
      }
     }

    #ifdef DEBUG_POP
     Serial.println(F("Sending QUIT"));
    #endif
     client.println(F("QUIT"));

     // After "QUIT", the server still respons with "+OK",
     // but after that, the connection might get lost.
     // So don't read everything after "+OK" (use parameter 'false' for readOk).
     if (!readOk(false))
      return -109;

     client.stop();

    #ifdef DEBUG_POP
     Serial.println(F("normally disconnected"));
    #endif

     return(nBytes);
    }

    // Read the response from the mail server.
    // That is "+OK" if everything is okay.
    // Parameter 'readAll' is to read every character after the "+OK".
    boolean readOk(boolean readAll)
    {
     // Check the response "+OK" from the mail server
     // In most cases that is followed by a space and more text, but not always.
     // In case of an error the text "-ERR" is received.

     int loopCount = 0;
     char bufOk[4];
     Serial.print("Connected: ");
     Serial.println(client.connected());

     Serial.print("Client Available: ");
     Serial.println(client.available());
     // Wait for response of mail server, with a timout.
     while (!client.available())
     {
      delay(1);
      loopCount++;

      // if nothing received for 10 seconds, timeout
      if (loopCount > 10000)
      {
       client.stop();
    #ifdef DEBUG_POP
       Serial.println(F("\nTimeout"));
    #endif
       return false;
      }
     }

     // Read the first three bytes.
     client.readBytes(bufOk, 3);

    #ifdef DEBUG_POP
     Serial.write(bufOk, 3);
     Serial.println();
    #endif

     // Is it "+OK" ?
     if (strncmp(bufOk, "+OK", 3) != 0)
     {
      popFail();
      return false;
     }

     // When the text after "+OK" is not needed, everything
     // else can be read and disregarded
     // (or shown in the serial monitor during debugging).
     if (readAll)
      readRemaining();

     return true;
    }

    void readRemaining()
    {
     // This function is called after checking the "+OK".
     // It reads everything from the server, until no more text is
     // available.

     while (client.available())
     {
      char c = client.read();
    #ifdef DEBUG_POP_EXTRA
      Serial.print(c);
    #endif
     }
     return;
    }

    void popFail()
    {
     int loopCount = 0;

    #ifdef DEBUG_POP
     Serial.println(F("popFail"));
    #endif

     while (!client.available())
     {
      delay(1);
      loopCount++;

      // if nothing received for 10 seconds, timeout
      if (loopCount > 10000)
      {
       client.stop();
    #ifdef DEBUG_POP
       Serial.println(F("\nTimeout"));
    #endif
       return;
      }
     }

     client.stop();

    #ifdef DEBUG_POP
     Serial.println(F("disconnected due to fail"));
    #endif
    }

Output:

    Arduino POP3 email reader
    Ethernet started.
    Local IP = 192.168.1.117
    Press 'c' to check mail.
    connected
    Connected: 1
    Client Active: 0

    Timeout
    Email POP3 failed, error = -102

title: Arduino-uno sending email with Hotmail

Answers: 1

body:
Hotmail doesn't provide a non-encrypted POP3 service, which would normally run on port 110.

You have no choice but to use the SSL service.  However, you can't.  Or not easily.  SSL is quite a heavy protocol and it is highly doubtful the little Uno is capable of even coming close to being able to work with it.

The Due might have a chance, but again, unlikely.

You would be best off using a computer (server) to check the emails for you and provide a "digest" of information to the Uno instead.


body:
My project requires reading 5 serial devices (RFID readers) at the same time. I chose an Arduino Mega 2560 as it comes with 4 serial RX ports. For the fifth port I am using the SoftwareSerial library.

My loop() checks each Serial port to detect if an RFID tag is being read. This works perfectly.

However, I am powering the board from an wall wart. When the power is disconnected the sketch no longer runs. I must unplug RX0, plug in the power supply, and reattach RX0.

If the board ever loses power it will have to be reset manually which is not ideal.

Please help me understand Why is this happening? and how can I fix it?

title: How to avoid pulling the RX0 pin to reset sketch

Answers: 2

body:
It looks like your RFID readers are very chatty on startup, and the board is going into bootloader mode.

I'd consider either controlling the RFID reader's power using another pin (and a transistor or mosfet if the reader needs more than 20mA), or using a gate ( `AND` for instance, or a simple switch IC like the 4066) that you can control to disable the `RX0` input until program start.

Another thing I've done in the past is multiplexed multiple serial devices to one serial input.  The RFID readers probably have outputs that indicate a card presence, so use those and a multiplexor.  When the card presence is indicated, connect that serial port using the multiplexor, read the card and act accordingly, then wait for another card detect event.

body:
You can simply disable the bootloader rather than erasing it. Find out the current fuse settings using a fuse-detection program. Change the BOOTRST flag in the High fuse to be unchecked, referring to this page: [Engbedded Atmel AVR® Fuse Calculator](http://www.engbedded.com/fusecalc)

Write the High fuse back. Then it will ignore the bootloader and go straight to your code. Of course, to upload a new version you will have to put the BOOTRST fuse back, or you won't be able to use the bootloader to upload a new sketch.

One way of changing the fuse is to use my [Atmega chip stand-alone programmer sketch](http://www.gammon.com.au/uploader). This has an interactive "change fuses" option. To run this you just need a spare board (eg. a Uno) and 6 wires to connect the programming board to your target Mega2560.

Example wiring shown on the linked page. Note that you do **not** need the SD board to merely change fuses. Just the two Arduinos and the connecting wires are enough for that.

When you first run the sketch it should inform you of the current fuses. Look at the High fuse and follow my instructions above.

You should see something like this:

    Entered programming mode OK.
    Signature = 1E 98 01
    Processor = ATmega2560
    Flash memory size = 262144
    LFuse = FF
    HFuse = D8
    EFuse = FD
    Lock byte = FF
    Bootloader in use: Yes

In this case the High fuse was D8, which has the bootloader enabled. Using the Fuse Calculator site we can see that it should now be D9 which disables the bootloader.

---

An alternative way to change the fuse is to use Avrdude, if you have a stand-alone ISP programmer handy.


body:
I am interested in writing a simple C program *outside* of the Arduino IDE and respective libraries, but deploying it directly to an Arduino Due (which uses a SAM3X8E ARM MCU). I am trying to figure out what comms/serial protocols are used for:

* Flashing/deploying the program to the ARM MCU; and
* Connecting the program to a debugger

And, not just the protocols used, but what *tools* are compatible with these protocols, and henceforth, can be used for both use cases. How can I tell what my viable options are?

title: What protocols and tools does Arduino Due use for flashing and debugging?

Answers: 1

body:
The Due (more specifically the SAM3X) uses its own proprietary protocol. It's all embedded in the bootloader, which is hard wired in the ROM and can never be changed (idiotic if you ask me).

I know of two systems for communicating with it.  Atmel's SAM-BA program, and the open source [BOSSA](http://www.shumatech.com/web/products/bossa).  The command line version of BOSSA (bossac) is used by the Arduino IDE for programming.


body:
I've been working on some software to do REALLY basic composition of music.
Here's my code so far:

    #include "notes_sharps.h"

    int notes[] = {NOTE_B0,NOTE_C1,NOTE_D1,NOTE_E1,NOTE_F1,NOTE_G1,NOTE_A1,NOTE_B1,NOTE_C2,NOTE_D2,NOTE_E2,NOTE_F2,NOTE_G2,NOTE_A2,NOTE_B2,NOTE_C3,NOTE_D3,NOTE_E3,NOTE_F3,NOTE_G3,NOTE_A3,NOTE_B3,NOTE_C4,NOTE_D4,NOTE_E4,NOTE_F4,NOTE_G4,NOTE_A4,NOTE_B4,NOTE_C5,NOTE_D5,NOTE_E5,NOTE_F5,NOTE_G5,NOTE_A5,NOTE_B5,NOTE_C6,NOTE_D6,NOTE_E6,NOTE_F6,NOTE_G6,NOTE_A6,NOTE_B6,NOTE_C7,NOTE_D7,NOTE_E7,NOTE_F7,NOTE_G7,NOTE_A7,NOTE_B7,NOTE_C8,NOTE_D8};

    void setup(){
      Serial.begin(9600);

      for(int i = 0; i < 51; i++){
        Serial.println("%i's sharp is %i",notes[i], notes[i]+(notes[i]*0.05937));
      }
    }

    void loop(){}

This code just refuses to compile, no error messages, it simply leaves my computer dormant.
Here's the log:

`C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avr-g++ -c -g -Os -w -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -MMD -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10604 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR -IC:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino -IC:\Program Files (x86)\Arduino\hardware\arduino\avr\variants\standard C:\Users\anidude\AppData\Local\Temp\build38239327143584304.tmp\sharpscalc.cpp -o C:\Users\anidude\AppData\Local\Temp\build38239327143584304.tmp\sharpscalc.cpp.o
`

title: This specific code just refuses to compile?

Answers: 1

body:
As Majenko stated in the comments, your use of the println function is not valid as there exists no overload that takes char*, int, int as parameters.

You could get your program to work by replacing your println as following:

    for(int i = 0; i < 51; i++){
        Serial.print(notes[i]);
        Serial.print("'s sharp is ");
        Serial.println(notes[i]+(notes[i]*0.05937));
    }


body: I want to use the [Ino command line toolkit](http://inotool.org/) to build and upload my HEXes. It works well for the regular Arduino, however when I try to upload code to a Mini Pro 3.3V at 8 MHz, the code has the timing wrong. The serial output is garbled (I tried at different baud rates and was garbled each time) and `delay(1000);` seems to take double the time. I have selected the correct board (pro328 in my boards.txt), but it didn't seem to make a difference in the generated code. Has anyone used this and encountered a similar problem?

title: Problem using Ino build for 8 MHz

Answers: 2

body:
Per the [Quick start guide][1], Ino assumes the board is an Arduino Uno unless otherwise specified on the command line:

> All examples were done in assumption that you have Arduino Uno and it is available on default port. Now consider you have Arduino Mega 2560 and it is available on port `/dev/ttyACM1`. We have to specify this for our build steps as command-line switches.
>
> Board model may be set with `--board-model` or `-m` switch. Port is set with `--serial-port` or `-p` switch. So lets do it:
>
>     $ ino build -m mega2560
>     $ ino upload -m mega2560 -p /dev/ttyACM1
>     $ ino serial -p /dev/ttyACM1
>
> For the full list of board names refer to `ino build --help`.

So you might be able to do this by using

    $ ino build -m pro328
    $ ino upload -m pro328 ...

However I don't know what options Ino includes for boards (presumably it uses the boards file), so using `ino build --help` should give you the information you need to select a suitable board if `pro328` doesn't work.

Once that's done, the frequency setting should be taken care of for you.

  [1]: http://inotool.org/quickstart

body:
So it seems the F_CPU should be set up at compile time and I'm not sure if Ino does that or not (probably, or I'm missing something else).

However after pulling my hair for a day or so I discovered [PlatformIO](http://platformio.org/#!/) which has a much better functionality - my code works correctly, the lib manager is intriguing, is platform independent and seems it doesn't even require the Arduino environment to be installed (it can pull the required files itself).


body:
I am trying to use some Relative Humidity sensors (DHT11 and DHT22) with the ATMega1284 processor on a breadboard. I use libraries from Arduino playground (dht.h), Adafruit (DHT.h) and others. Even though both sensors and libraries work fine with Arduino Uno and Mega, they fail with ATMega1284, which produces an INVALID_VALUE error.

Connections are double checked, and other libraries such as Wire, OneWire etc work fine.

Does anyone have any experience with the ATMega1284 processor, or any suggestions?

title: ATMega1284 and Relative Humidity libraries

Answers: 1

body:
Per the library instructions, you will receive `INVALID_VALUE` in the following situations:

> The `readXX()` functions return:
>
> * `DHTLIB_OK` (0) : if the sensor sample and its checksum is OK.
> * `DHTLIB_ERROR_CHECKSUM` (-1) : if the checksum test failed. This means that data was received but may be incorrect.
> * `DHTLIB_ERROR_TIMEOUT` (-2) : if a timeout occured, communication failed.
>
> In case of a `DHTLIB_ERROR_TIMEOUT`, humidity and temperature will both get the value `DHTLIB_INVALID_VALUE`. In case of `DHTLIB_ERROR_CHECKSUM` the values of humidity and temperature are left unchanged as it is impossible to determine which byte failed in the checksum. It is up to the programmer to decide what to do. One can compare with previous value, but better reread the sensor.

So read the value returned by the `read11()` or `read22()` functions to verify that it's an `DHTLIB_ERROR_TIMEOUT` condition, and if so try to figure out why the library is having trouble talking to the device.


body:
I can't use this program on my Arduino Uno since the max is 16 bits. I need my water pump to run for 5 min, then wait for 60 min.

    int motorPin = A0;
    int blinkPin = 13;

    int watertime = 300000; // how long to water in miliseconds
    int waittime = 3600000; // how long to wait between watering

    void setup() {
        pinMode(motorPin, OUTPUT);
        pinMode(blinkPin, OUTPUT);
    }

    void loop() {
        digitalWrite(motorPin, HIGH);
        digitalWrite(blinkPin, HIGH);
        delay(watertime);
        digitalWrite(motorPin, LOW);
        digitalWrite(blinkPin, LOW);
        delay(waittime);
    }

---
Changed int to:

    #define watertime 300000
    #define waittime 3600000

But it does not work.

title: Need help rewriting a program

Answers: 5

body:
Use the `long` type instead

    long watertime = 300000; // how long to water in miliseconds
    long waittime = 3600000; // how long to wait between watering

body:
If did not misunderstand, you want a longer delay. Why don't you use a for loop in order to obtain such a delay.

    for(int i = 0; i < 50; i++) {
        delay(1000);
    }

This produces 50 seconds instead of 1 second. You can replace 1000 and 50 according to your needs. This is just an example.

body:
For any delays longer than a few seconds you really need to use a Real-Time Clock chip, like the popular DS1307 from Maxim. The Arduino's delay() function is only very roughly accurate, and even less so when used as you are using it.

If you can't get a DS1307 or something similar (there's plenty to choose from) or you Arduino has too much connected already to allow anything else to be added, you could use the `Time` library to simulate one.  The `Time` library is also useful if you do have an RTC attached.

* http://playground.arduino.cc/code/time

body:
I do not know if you plan on doing anything else on your arduino, but holding a delay inside the loop function is bad idea if you do, things need to happen outside of your code (any serial I/O for sure and others, right?).

That said, I like @zgrknr answer the best, although the others will also work. That answer allows using smaller numbers, that are easier to understand. Just make sure to keep your variables global, and not within loop or else they will get re-initialized every time.

As far as accuracy, do some real by the clock testing, and adjust your numbers, who cares if it is accurately counting as long as you can identify what numbers gives you the time period you want.

response to comment:

My firmware code looks like this, is yours different?

    int main(void)
    {
   init();
   initVariant();

    #if defined(USBCON)
   USBDevice.attach();
    #endif

   setup();

   for (;;) {
  loop();
  if (serialEventRun) serialEventRun();
   }
   return 0;
    }

body:
I believe it's better to put the Arduino to sleep instead of using the delay function.

You can use a library called [*Sleep_n0m1*](https://github.com/n0m1/Sleep_n0m1) for the purpose.

Modify your code like following.

    #include <Sleep_n0m1.h>

    int motorPin = A0;
    int blinkPin = 13;

    unsigned long watertime = 300000UL; // how long to water in miliseconds
    unsigned long waittime = 3600000UL; // how long to wait between watering
    Sleep sleep;

    void setup()
    {
        pinMode(motorPin, OUTPUT);
        pinMode(blinkPin, OUTPUT);
    }

    void loop()
    {
        digitalWrite(motorPin, HIGH);
        digitalWrite(blinkPin, HIGH);
        sleep.pwrDownMode();
        sleep.sleepDelay(watertime);
        digitalWrite(motorPin, LOW);
        digitalWrite(blinkPin, LOW);
        sleep.pwrDownMode();
        sleep.sleepDelay(waittime);
    }

Hope this would solve the problem.


body:
Hello guys (and gals)!

I'm trying to figure out how to program thresholds using my arduino board.

Essentially, to make this as simple as possible, this is what I have going on.

I am sampling a value every one second, I am taking the value and trying to make certain actions occur based on when this value crosses certain thresholds.

The value read every second will be a value between 0-150.

The thresholds will work something like this:

If value crosses over 20 and becomes 20 or higher, do an action.

If value crosses over 20 and becomes 19.9 or less, do a different action.

And then do the same for a threshold at 30, 40, 50, and 65.

I would need to have it so that if it reads a value of 15, and then a second later, reads a value of 23, it does an action. But if it reads 23, and then reads 24 a next, it needs to not do anything because it hasn't crossed over from one threshold to another. I only want an action to perform if a threshold is crossed either by increasing or decreasing past it.

So again, to reiterate;

If first value read is 34, and second is 42, do an action.

If first value is read at 57, and second at 44, do an action.

If first value is 24, and second value is 26, do nothing. (no threshold was crossed)

The next part would be figured out if a threshold was crossed twice, or more, to do that action twice or more times.

Any advice on how to code this?

Thanks in advance.

title: How to program thresholds?

Answers: 2

body:
The way you described it, the first and good solution I can approach it is [state machine.][1]

You have a lot of thresholds to check and very specific details such as going up at some level and doing something or nothing depending on the level.

What I advise you is creating the state machine for you code setting up all the thresholds and saving the actual *state* of your system into a variable. After you have this set up, coding is just a matter of switch/cases or if statements.

For example. The first part is to check if it goes until 20 and then keep with at least 20.

    switch (state) {
        case 1:
            if (value >= 20 && value < 30)
                 state = 2;
            break;
         case 2:
            if (value < 20)
                 state = 1;  // initial state
            else if (value >= 20 && value < 30)
                 state = 3; // or call a function
            break;
         case 3:
              doSomething();
              break;
    }

And you could have some delay or timer interrupt to check the value each 1s and repeat the state machine again and again. If you change or read the value inside an interrupt function call, make sure you declare the variable as **volatile** otherwise the compiler will optimize it and your machine won't work properly.

This way you can expand the idea and have all the thresholds set up.

  [1]: http://en.m.wikipedia.org/wiki/Finite-state_machine

body:
Thanks again for your contributions.

I've gone ahead and decided to go with the following code. Its purpose is to turn vol up or down based on current car MPH. I choose to define brackets that cover a range of values. When one bracket ends, another begins. I've also set the previous bracket to current bracket at the end of each loop so that the application knows where it was previously, so that if it hops above or goes under a defined bracket, it does the desired action.

I've used a random generator to supply the MPH for testing purposes for now and commented out a few things that disturbed the testing process. If you'd like to critique this code to make is better, please let me know.

Note: I've also borrowed some of this code from another individual (Matthew McMillan, http://matthewcmcmillan.blogspot.com) who wanted to figure out how to convert a vehicle speed sensor wire info into MPH. I needed this code in order to make use of the vehicle's speed.

    #include <SPI.h>
    #include <Wire.h>

    const int lightPin = 0;
    const int hardwareCounterPin = 5;
    const int samplePeriod = 1000; //in milliseconds
    const float pulsesPerMile = 4000; // this is pulses per mile for Toyota. Other cars are different.
    const float convertMph = pulsesPerMile/3600;
    unsigned int count;
    float mph;
    unsigned int imph;
    int roundedMph;
    int previousMph;
    int prevCount;

    // Declare brackets
    const int BracketA = 1;
    const int BracketB = 2;
    const int BracketC = 3;
    const int BracketD = 4;
    const int BracketE = 5;
    const int BracketF = 6;

    // Initialize Previous and Current Brackets
    int PreviousBracket = 1;
    int CurrentBracket = 1;

    void setup(void) {
      Serial.begin(9600);

      TCCR1A = 0; //Configure hardware counter
      TCNT1 = 0;  // Reset hardware counter to zero
    }

    void loop() {

      /////////////////////////////////////////////////////////////
      // This uses the hardware pulse counter on the Arduino.
      // Currently it collects samples for one second.
      //
      bitSet(TCCR1B, CS12); // start counting pulses
      bitSet(TCCR1B, CS11); // Clock on rising edge
      delay(samplePeriod); // Allow pulse counter to collect for samplePeriod
      TCCR1B = 0; // stop counting
      count = TCNT1; // Store the hardware counter in a variable
      TCNT1 = 0;     // Reset hardware counter to zero
      mph = (count/convertMph)*10; // Convert pulse count into mph.
      imph = (unsigned int) mph; // Cast to integer. 10x allows retaining 10th of mph resolution.

      int x = imph / 10;
      int y = imph % 10;

      // Round to whole mile per hour
      //if(y >= 5){
      //  roundedMph = x + 1;
      //}else{
      //  roundedMph = x;
     // }

      //Code to write your own MPH for testing purposes.
      //if (Serial.available() > 0) {
                    // read the incoming byte:
                   // roundedMph = Serial.read();
                   //}

      //If mph is less than 1mph just show 0mph.
      //Readings of 0.9mph or lower are some what erratic and can
      //occasionally be triggered by electrical noise.
      //if(x == 0){
      //  roundedMph = 0;
     // }

      roundedMph = random(1,80);

      // Don't display mph readings that are more than 50 mph higher than the
      // previous reading because it is probably a spurious reading.
      // Accelerating 50mph in one second is rocketship fast so it is probably
      // not real.
      if((roundedMph - previousMph) > 50){
        roundedMph = previousMph;
      }

      //Place the gatherered MPH value into a bracket
      //---------------------------------------------
      if(roundedMph >= 0 && roundedMph < 20) {
       CurrentBracket = BracketA;  //Value1
       Serial.println("I Choose Bracket A");
        }

      if(roundedMph >= 20 && roundedMph < 30) {
       CurrentBracket = BracketB;  //Value2
       Serial.println("I Choose Bracket B");
        }

      if(roundedMph >= 30 && roundedMph < 40) {
       CurrentBracket = BracketC;  //Value3
       Serial.println("I Choose Bracket C");
        }

      if(roundedMph >= 40 && roundedMph < 50) {
       CurrentBracket = BracketD;  //Value4
       Serial.println("I Choose Bracket D");
        }

      if(roundedMph >= 50 && roundedMph < 65) {
       CurrentBracket = BracketE;  //Value5
       Serial.println("I Choose Bracket E");
        }

      if(roundedMph >= 65) {
       CurrentBracket = BracketF;  //Value6
       Serial.println("I Choose Bracket F");
        }

     //Decide if bracket stayed the same, went up, or down.
     //---------------------------------------------------
     if(CurrentBracket == PreviousBracket) {
     //Do Nothing
     Serial.println("Nothing Changed");
     }

    if(CurrentBracket > PreviousBracket) {
     //Command for Vol Up
     int VolUp;
     VolUp = CurrentBracket - PreviousBracket;
    Serial.println("Volume Went Up One by ");
    Serial.println(VolUp);
    delay(2000); // Delay to not change Vol to fast if near threshold
    }

    if(CurrentBracket < PreviousBracket) {
      //Command for Vol Down
      int VolDown;
      VolDown = PreviousBracket - CurrentBracket;
     Serial.println("Volume Went Down One by ");
     Serial.println(VolDown);
     delay(2000); // Delay to not change Vol to fast if near threshold
     }
      previousMph = roundedMph; // Set previousMph for use in next loop.
      PreviousBracket = CurrentBracket; //Set PreviousBracket for use in next loop.
    }


body: I've created a circuit to turn on bulb using GSM module and Arduino. I want a mechanism(or programming) to know whether the bulb is on or off or fused. I've tried taking the input from the pins. But it only tells whether the pin is on or off but not the circuit as a whole.

title: How can I programming detect that a Bulb/LED is ON/OFF or a circuit is working as expected using Arduino?

Answers: 1

body:
This can be done using a few methods.  The simplest and least expensive option is to measure the current consumption of the device you want to verify correct operation of, and see if it's using enough, but not too much, current.

For instance, the following would work well in the arduino case of using an LED:

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

![schematic](https://i.stack.imgur.com/7ySWi.png)

<!-- End schematic -->

Connect the `Power` to 5V or to the pin you're controlling the LED with. Connect the `Sense` to an analog input such as A0.

If the LED isn't installed, or is broken as an open circuit, the sense would register 5V.  If the LED is broken as a shorted element, the sense would register 0v. If the LED is operating correctly, you would sense the voltage drop of the LED (which varies according to the LED's design), but it would be well above 0V and well below 5V.

For bulbs and other loads, use a much smaller resister for R1 (so the resistor doesn't affect the load as much) and it would be considered a current shunt.  Knowing the resister value, and the voltage at the `Sense` location will give you a current value using `Current = Voltage / Resistance`. Again, the load should be drawing current within an acceptable range during proper operation.  If it's not drawing enough current, or too much current, it may not be operating correctly.

This won't tell you if the LED is on, however it's a very reliable method to discover if it's working correctly, and you'll probably never run into a situation where the correct LED is installed and in the right current range, but not emitting light.


body:
I've written a simple program - it generates signals over `Port D` at 4 MHz:

    #include <Arduino.h>

    int main(void) {

     DDRD = B11111111;
     PORTD = B00000000;

     while (true) {
      PORTD = 0;
      PORTD = 5;
      PORTD = 10;
      PORTD = 15;
      PORTD = 20;
      PORTD = 25;
      PORTD = 30;
      PORTD = 35;
      PORTD = 40;
     }
     return 0;
    }

and this is the signal coming out on D4:
![Max Frequency][2]

I've modified the program by inserting NOP after each assignment to `POTRD`:

    #define NOP __asm__ __volatile__ ("nop\n\t")

    int main(void) {

     DDRD = B11111111;
     PORTD = B00000000;

     while (true) {
      PORTD = 0;NOP;
      PORTD = 5;NOP;
      PORTD = 10;NOP;
      PORTD = 15;NOP;
      PORTD = 20;NOP;
      PORTD = 25;NOP;
      PORTD = 30;NOP;
      PORTD = 35;NOP;
      PORTD = 40;NOP;
     }
     return 0;
    }

and now signal looks fine, but frequency is limited to 800 KHz:
![enter image description here][3]

What is the reason for interference at 4 MHz? Is there a limitation to maximal frequency on digital out? I do not really need it for some particular project, just wanted to know it.

  [1]: https://stackoverflow.com/questions/30201318/disturbed-digital-out-at-4mhz-on-arduino-nano
  [2]: https://i.stack.imgur.com/O3IfR.jpg
  [3]: https://i.stack.imgur.com/gKU53.jpg

I've asked this question on [stackoverflow][1], but then I've discovered this dedicated forum so... I've decided to try it out ;)

title: Disturbed digital out at 4Mhz on Arduino NANO

Answers: 2

body:
This is not a limitation of the Arduino: you can toggle a pin on every clock cycle. It's a synchronization problem between the generated signal and the triggering of the scope. Your scope displays several traces superimposed, and it synchronizes them on the rising edges, but since those are unequally spaced, it gets out of sync with the full period of the signal. By adding a few nops you reached a lucky synchronization in your second version of the code.

The simplest solution is to set the scope mode to _Single_ instead of _Normal_. Then it only displays a single trace and synchronization is not an issue anymore.

Another option would be to use one of the bits of `PORTD` as a trigger
signal. This bit should cycle only once inside the loop. `PD5` should
work in the current version of your code. Configure the scope for
external trigger and feed this signal into its TRIG input.

body:
Thank you - correct trigger solves my problem:
![enter image description here][1]

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


body:
I have several Arduinos connected to my Windows PC, and they appear as follows:

> COM7 (Arduino Uno)
> COM11 (Arduino Uno)
> COM13 (Arduino Uno)

So there's no way to tell which is which, and when I want to upload a sketch to one, I have to unplug the others to make sure my code goes to the right one.

Is there a way to change the "Arduino Uno" description?

(I found a similar question but that was about Mac specifically).

title: Can I change the USB device name of Arduino?

Answers: 2

body:
You'll have to change the software on the Arduino USB chip itself, and you may need to modify the drivers for the Arduino USB interface on the computer side.  It's not trivial, and probably not worth it.

However, Windows attempts to use the same serial port for the same devices in the same USB positions, so if you figure out which is which (blinking the LED at different frequencies) then you can mark the USB port itself with the com number that Windows uses when you plug an arduino into it.

If you use a hub, and you move that hub to a different port, the com numbers will change, but if you keep it in the same port, then it too will try to have them match what they have been in the past.

It's an annoyance, but it's a design decision by arduino.cc.  The old FTDI chips kept their assigned com port numbers because they have individual serial numbers and windows would attempt to reassign the same com port to the same chip each time it was plugged in, regardless of its location.  When Arduino.cc moved to a programmed MCU for the USB interface, they chose not to provide USB serial numbers, and thus windows has little option but to try to keep things straight by determining the location in the USB hierarchy that the device is connected, and try to keep com port assignments the same using that method.

body:
I have never tried it, but I suspect using zadig might work;
[http://zadig.akeo.ie/][1]

It lets you pick the driver and name for WinUSB and LibUSB devices.  Uninstall any existing driver first. And remember to pick the driver you wish to use when it asks. Also it is not real apparent, but you can edit the name of the device as it installs the driver.

Let us know if it works

  [1]: http://zadig.akeo.ie/


body: Recently I have noticed that there are two arduino sites, arduino.cc and arduino.org.  They both have the Arduino logo and both sell what seems to be official Arduino boards. Also, arduino.org came out with the Arduino Zero board first. What is the deal here? Has Arduino partnered with another site? Any ideas appreciated.

title: Difference between Arduino.cc and Arduino.org

Answers: 5

body:
This article can explain it better than I could paraphrase:
http://hackaday.com/2015/02/25/arduino-v-arduino/

Relevant excerpt:

> Arduino LLC [***arduino.cc***] is the company founded by Massimo Banzi, David Cuartielles, David Mellis, Tom Igoe and Gianluca Martino in 2009 and is the owner of the Arduino trademark and gave us the designs, software, and community support that’s gotten the Arduino where it is. The boards were manufactured by a spinoff company, Smart Projects Srl, founded by the same Gianluca Martino. So far, so good.
>
> Things got ugly in November when Martino ... renamed Smart Projects to Arduino Srl and registered ***arduino.org***
>
> According to this [Italian Wired article][1], the cause of the split is that Banzi and the other three wanted to internationalize the brand and license production to other firms freely, while Martino ... [wanted] to list on the stock market and keep all production strictly in the Italian factory.

  [1]: http://www.wired.it/gadget/computer/2015/02/12/arduino-nel-caos-situazione/

body:
The short of it is that there was a falling out within the Arduino people and now there are two groups laying claim to the "Arduino" name.

Arduino LLC runs arduino.cc. They are the steward of the Arduino IDE and libraries and own the "Arduino" trademark in the United States, and also owns the "Genuino" trademark outside of the United States. Arduino SRL (fka Smart Projects SRL) is the company that assembles(assembled) the majority of Arduino boards for Arduino LLC, runs arduino.org, and owns the "Arduino" trademark inside Italy and all of the other countries they have registered the "Arduino" trademark.

Arduino SRL recently decided that they are no longer beholden to Arduino LLC and has stopped paying licensing fees for using the Arduino name. Whether this is justified or not has not been fully tested in court yet.

body:
[arduino.org][1] is not only boards assembler, but is also who designs and engineers the arduino boards. They own the arduino trademark all over the world, except the USA, therefore [arduino.cc][2] owns the trademark only in the USA.

  [1]: http://www.arduino.org
  [2]: http://www.arduino.cc

body: Please take a look at [The Untold History of Arduino](http://arduinohistory.github.io).

body:
Update on the situation: on October 1st, 2016 a blog post at arduino.cc "[Two Arduinos become one][1]" announced that an agreement was found between arduino.cc and arduino.org. Two key points:

 - the creation of a foundation
 - the creation of a holding.

About the holding:

> At the end of 2016, the newly created “Arduino Holding” will become the single point of contact for the wholesale distribution of all current and future products, and will continue to bring tremendous innovations to the market.

About the foundation:

> In addition, Arduino will form a not-for-profit “Arduino Foundation” responsible for maintaining the open-source Arduino desktop IDE, and continuing to foster the open-source movement by providing support for a variety of scholarships, community and developer initiatives.

  [1]: https://blog.arduino.cc/2016/10/01/two-arduinos-become-one-2/


body:
I am interested in writing a simple Arduino program that will turn a servo back and forth (180 degrees each time) continuously.

I am looking at [these servos](http://www.amazon.com/VicTsing-10pcs-Helicopter-Airplane-controls/dp/B00KA393PK/ref=sr_1_1?s=wireless&ie=UTF8&qid=1431615089&sr=1-1&keywords=VicTsing+10pcs+micro+servo+motor+SG90) and am planning on following [this example](http://playground.arduino.cc/ComponentLib/servo).

Being so new to Arduino, I first wanted to confirm that the `SoftwareServo` library in that example will drive those particular servos. If it will not, then can someone begin by explaining to me *why* these servos are incompatible with the lib?

Assuming they are compatible, I am looking at the main example on that page (comments stripped out for brevity):

    #include <SoftwareServo.h>

    SoftwareServo myservo;

    int potpin = 0;
    int val;

    void setup() {
        myservo.attach(2);
    }

    void loop() {
        val = analogRead(potpin);
        val = map(val, 0, 1023, 0, 179);
        myservo.write(val);
        delay(15);

        SoftwareServo::refresh();
    }

My concerns:

* There seem to be 3 pins involved here: a potentiometer pin (`0`), an analog pin (`val`) and a servo pin (`2`). What is the purpose of each of these pins, and is this 3-pin wiring common across all/most servos?
* Is there anything "wrong" with defining `myservo.attach(2);` up *above* the `setup` function, and leave the `setup` function an empty no-op function?
* Where does the `map(...)` function come from? If it was defined inside `SoftwareServo` I would have expected its usage to be something like `SoftwareServo::map(...)`, etc.
* Why do we need the `delay` after calling `myservo.write(val);`? What would happen if this delay wasn't in there?
* According to that link, calling `SoftwareServo::refresh()` once every 50ms is necessary in order to: "*keep your servos updating.*" **But what does this mean, really?** Updating to what?!?

title: Arduino SoftwareServo by example

Answers: 2

body:
> There seem to be 3 pins involved here: a potentiometer pin (0), an analog pin (val) and a servo pin (2). What is the purpose of each of these pins, and is this 3-pin wiring common across all/most servos?

No, there is only 2 pins.  The value of the potentiometer attached to pin 0 is read and stored in the variable `val`.  That is then used to set the angle of the servo motor on pin 2.

> Is there anything "wrong" with defining myservo.attach(2); up above the setup function, and leave the setup function an empty no-op function?

Yes.  It'll never get called.  `setup()` is the first function to be called and its purpose is to perform any initialization routines, such as attaching the servo code to the pin the servo is connected to.  So you *have* to call that either from `setup()` or from a function which `setup()` itself calls.

> Where does the map(...) function come from? If it was defined inside SoftwareServo I would have expected its usage to be something like SoftwareServo::map(...), etc.

`map()` is part of the standard Arduino API.  http://www.arduino.cc/en/Reference/Map

> Why do we need the delay after calling myservo.write(val);? What would happen if this delay wasn't in there?

You don't need the `delay()` call, but you don't want to set the value of the servo too rapidly.  You really want to allow at least one PWM cycle between each call to ensure the values have been set properly.

> According to that link, calling SoftwareServo::refresh() once every 50ms is necessary in order to: "keep your servos updating." But what does this mean, really? Updating to what?!?

SoftwareServo is just what it says - a piece of software.  You have to run that software for it to work, and the `refresh()` function is that bit that you run.  If you don't call that then the PWM signal for the servo will never get generated and nothing will happen.

Oh, and yes those little servos should be fine.

body:
1- there is only two pins a servo pin which is D2 and an analog pin which is A0. D2 pin for writing analog value to servo. D2 pin is used for getting analog pin value.

2- map function is a default function like sin, cos or digitalRead so library inport not necesary.

3- delay function and waiting 50ms is used to wait servo response time. if you change servo angle too quickly servo will not respond accurately


body:
I am using an Arduino with 2048 bytes of SRAM. I have a complex project so that it is no longer obvious how much SRAM it would use in total (there is not one large dominant object but many different routines, many libraries most of which I have not written myself etc. Each of these uses some small buffers, global variables etc.).

Can I determine how much SRAM I have left in the live system?

title: Measure SRAM usage

Answers: 1

body:
Expanding on my previous comment... The RAM memory map of an AVR-based
Arduino looks like this:

    ┌──────┬─────┬──────┬──────────┬───────┐
    │ data │ bss │ heap │→  free  ←│ stack │
    └──────┴─────┴──────┴──────────┴───────┘

The data and bss sections are fixed, and their size can be known at
compile time. However, the stack and the heap grow and shrink
dynamically as the program runs. You can estimate the amount of free
memory at run time by measuring the gap between the heap and the stack.
The result may be pessimistic if the heap contains usable holes.

Here you have:

* [a very simple function](https://learn.adafruit.com/memories-of-an-arduino/measuring-free-memory) that does exactly that, and
* [a more complex version](http://playground.arduino.cc/Code/AvailableMemory) that also counts the holes in the heap.


body:
If I use `EEPROM.write(someAddr, someValue)` to write a value to an address, how long will that value "stick" to that address before being lost?

If I were to power down the Arduino, flash a whole new program to it, and power it on, could I still retrieve that old/cached value written from the previous program?

title: Is EEPROM persisted across program flashes?

Answers: 2

body: Only if the `EESAVE` fuse is programmed (it is unprogrammed by default). If not then the EEPROM will be erased when a chip erase command is performed.

body:
> how long will that value "stick" to that address before being lost?

The Atmega328 data retention is guaranteed by Atmel (the manufacturer) for 20 years at 85 degrees Celsius, 100 years at 25 degrees Celsius. Beware cheap Chinese clones usually use counterfeits chips, meaning those values are not going to be guaranteed any more

> If I were to power down the Arduino, flash a whole new program to it, and power it on, could I still retrieve that old/cached value written from the previous program?

While @ignacio answer is more detailed I believe you are interested in plain Arduino IDE programming along with standard Arduino boards, in which case the answer is **yes**, the data is not going to be erased.


body:
I am trying to make a connection between 2 Arduino's with the APC220 rf modules.

    void setup() {
        Serial.begin(9600);
    }

    void loop() {
       int value = 5;
       Serial.println(value);
       delay(1000);
    }

I uploaded this code to my Arduino Nano and Uno. I disconnected the rf modules for uploading the code.

I tried to run this program with an external power source (lipo 11.1V 2200mAh).
The Arduino is powered on(power led is on) BUT the tx led doesn't blink.

The only way to make it work is by using the usb and opening the serial monitor on my pc.

I tried to use a 10k resistor between tx and rx (or rx to ground) but the code won't run...

Can someone help me?

Solution : the arduino worked perfect. When you connect the arduino with an exernal power supply the tx and rx lights won't light up, Even when they are transmitting or receiving.

title: Arduino won't send serial data if connected with external power supply

Answers: 2

body: I think tx not activated without available serial connection. What is you rf module and what is the baud rate of RF module. Also can you share connection diagram or a test video. Alternativeliy you can look SoftwareSerial: http://www.arduino.cc/en/Reference/SoftwareSerial

body:
Solution : The Arduino worked perfectly. When you connect the Arduino with an external power supply the Tx and Rx lights won't light up, Even when they are transmitting or receiving.

---

I'm adding this as the solution to stop this being re-added as an unsolved problem.

---

That is correct. The Tx and Rx LEDs are connected to the Atmega16U2 processor, and thus only flash if there is serial comms via USB.


body:
I'm working on a project that will require two arduinos to be able to relay information to each other from long distances (up to about 10 miles or around 16 km).  WiFi won't be guaranteed to be available to either arduino as this is a wilderness application.

What are my options for long range wireless communication?  I haven't decided on an arduino model yet so if one particular model would be best for this application let me know.

title: Long range wireless communication between two arduinos?

Answers: 1

body:
Your range of options depends strongly on what your budget is, what country you are in, whether you are a licensed radio operator, whether cell service is available, etc.

### If you aren't licensed:

In the USA, unlicensed (or lightly licensed) radio options include GMRS ([General Mobile Radio Service](https://en.wikipedia.org/wiki/General_Mobile_Radio_Service)), FRS ([Family Radio Service](https://en.wikipedia.org/wiki/Family_Radio_Service)) and CB ([Citizens band radio](https://en.wikipedia.org/wiki/Citizens_band_radio)).  GMRS and FRS range typically is at most a few miles – ten miles is too much to hope for.  CB range would be ok but CB radios often are fairly large and antennas would be large, eg nine feet long.  I don't know whether it is legal to transmit digital data over GMRS/FRS/CB radio.

### If you are licensed:
[2-meter band](https://en.wikipedia.org/wiki/2-meter_band) radio might be a good choice.  Frequencies are 144 MHz to 148 MHz in the Americas and Asia, or 144 MHz to 146 MHz elsewhere.  Per wikipedia,
>The license privileges of amateur radio operators include the use of frequencies within this band  for telecommunication, usually conducted locally within a range of about 100 miles (160 km).

### If cell service is available:
Consider a [GSM](https://en.wikipedia.org/wiki/GSM) shield, eg the [Arduino GSM Shield](http://www.arduino.cc/en/Main/ArduinoGSMShield).

To access the cell network you would need to buy a [SIM card](http://www.arduino.cc/en/Guide/ArduinoGSMShield#toc4) for each GSM shield.

GPRS ([General Packet Radio Service](https://en.wikipedia.org/wiki/General_Packet_Radio_Service)) on GSM provides data rates between 10 and 240 kbs.  Other GSM protocols may be faster or slower.  Data rates depend also on whether 3G service is available or only 2G.


body:
I have a sensor which I am trying to communicate with over SPI using an Arduino UNO. It is my first time using SPI and I'm experiencing some problems which I'm hoping are just due to some misunderstanding on my part. I have written a simple code to perform one basic operation: Turn on the sensor's fan. The Arduino is being powered through the 2.1 mm barrel jack by a 1.5 A DC adapter. The 5V, GND, MOSI, MISO, SS and SCK pins on the Arduino are connected to the corresponding pins on the sensor. The sensor receives power from the Arduino, drawing up to 250 mA (with the fan on).

The manufacturer provides a list of commands corresponding to each function of the sensor. To turn on the fan, the command list gives the following information:

    Command_byte: 0x03
    Bytes: 0x03, 0x00
    Bytes_in: 0xF3, 0x03
    Time_between_current_and_next_byte: 1.7ms, NA
    Note: 1ms would be adequate delay between command byte and following byte

Based on my understanding of this, to turn on the fan, I need to send a command byte (0x03), then wait 1.7 ms and send another byte (0x00). My code for doing this is as follows:

<!-- language: lang-cpp -->

    #include <SPI.h>
    const int chipSelectPin = 10;

    void setup() {
      Serial.begin(9600);

      SPI.begin();
      pinMode(chipSelectPin, OUTPUT);
      SPI.setClockDivider(SPI_CLOCK_DIV32); //set clock to 500kHz
      SPI.setDataMode(SPI_MODE1);
      SPI.setBitOrder(MSBFIRST);
      delay(10000); // Let the sensor settle for 10 seconds

      digitalWrite(chipSelectPin, LOW);
      indata = SPI.transfer(0x03); //command byte for fan on
      Serial.println(indata);// value returned should be 0xF3
      delay(2);
      indata = SPI.transfer(0x00); //Turn on fan
      digitalWrite(chipSelectPin, HIGH);
      Serial.println(indata);// value returned should be 0x03
    }

    void loop() {}

When I send the command byte, the returned value (which gets printed to the terminal) is 243 which corresponds to the expected hex value of 0xF3. However, the second command does not turn on the fan and the second returned value is 231 which does not correspond to the expected hex value of 0x03.

I don't think it's a hardware issue because at least one of the returned values is correct and because the sensor does work when used with a different platform. I also experimented with different delays between bytes.

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

title: SPI: problems communicating with sensor using Arduino

Answers: 1

body:
Change your chipSelectPin. Pin 10 is exclusively used by SPI library. See [Arduino Uno description][1].

Similar issue has been discussed [here.][2]

  [1]: http://www.arduino.cc/en/Main/ArduinoBoardUno
  [2]: https://arduino.stackexchange.com/questions/10551/mqtt-vs-tinkerkit-sensor-shield/10567#10567


body:
I'm going to be writing some performance critical code and have started trying to get an understanding of timers and how much "work" the Due CPU can do per second.  To help get started with this, I wrote a bare sketch that simply increments a counter whilst a timer which ticks every second dumps the value of the counter to the serial log and then resets the counter.  Here's the code I'm using:

    #include <Arduino.h>

    void EnableTimer7TickEverySecond();

    volatile uint32_t gCounter = 0;

    void setup()
    {
     Serial.begin(9600);

     EnableTimer7TickEverySecond();

    //  while ( true )
    //  {
    //   ++gCounter;
    //  }
    }

    void loop()
    {
     ++gCounter;
    }

    void EnableTimer7TickEverySecond()
    {
     pmc_set_writeprotect(false);
     pmc_enable_periph_clk(ID_TC7);
     TC_Configure(TC2, 1, TC_CMR_WAVE |
      TC_CMR_WAVSEL_UP_RC | TC_CMR_TCCLKS_TIMER_CLOCK1);
     TC_SetRC(TC2, 1, 656000 * 64);
     TC_Start(TC2, 1);
     TC2->TC_CHANNEL[1].TC_IER = TC_IER_CPCS;
     TC2->TC_CHANNEL[1].TC_IDR = ~TC_IER_CPCS;
     NVIC_EnableIRQ(TC7_IRQn);
    }

    void TC7_Handler()
    {
     TC_GetStatus( TC2, 1 );

     Serial.println( (uint32_t)gCounter );

     gCounter = 0;
    }

When I run this, I get values averaging 446,000 in the serial log for the increments per second.  That is way lower than I was expecting.  On an ARM chip running at 84MHz, I'd expect at least 14 million increments as few ARM instructions take more than 2 clock cycles and an increment should involve a read from memory, addition and a write back to memory (approx 6 clock cycles by my reckoning).

The timer is configured correctly, the TX led flashes regularly at 1 second intervals as the Serial.println is called.  I've checked for overflow on the counter (oddly, I found that the number of increments when working with a uint64_t was slightly higher).  I've also tried not calling Serial.begin() until I'm about to write the value to the log (and then only writing the value once) and whilst there is a slight increase in "performance", it doesn't account for the whole difference between expectation and reality.

My best guess would be that loop() is called on some sort of timer or has a built in default delay, so it occurred to me that if I comment out the counter increment in loop() and instead comment in the infinite while loop in setup(), I should be able to counteract any delay caused by how frequently the Arduino IDE calls loop().  I have seen other examples that never bother with loop() and just stick all their code in setup().

I do see a performance increase with this setup, but only to around 9 million, not the 14+ million I would expect. Oddly though, sometimes, randomly, the value is 2 or 3 times the "usual" value.  Not between 2 and 3 times, but exactly 2 or 3 times.  This happens regardless of whether I am incrementing the counter inside the loop() function or my own loop inside setup().  It is not a case of the timer "skipping", the output is written every second like clockwork.

So, my questions are:

 - What does the Arduino library do to make loop() so inefficient?

 - Is there any harm in keeping all your code inside an infinite loop in
   setup() and never returning out of it?

 - Why would I sometimes see the number of increments being 2 or 3 times
   higher than usual?  Could the counter be getting cached (despite
   being marked as volatile) and not reset properly?  If so, how can I
   prevent this?

title: Help needed understanding Due performance

Answers: 1

body:
> What does the Arduino library do to make loop() so inefficient?

Alot.  For a start it's a function, so it has to push registers onto the stack before it runs, and pop them off afterwards.  Secondly there is the "serial event" system outside the loop.  In main.cpp in the core you can see how loop is called:

    setup();

    for (;;)
    {
        loop();
        if (serialEventRun) serialEventRun();
    }

> Is there any harm in keeping all your code inside an infinite loop in setup() and never returning out of it?

If you don't use serial events, no harm whatsoever.

> Why would I sometimes see the number of increments being 2 or 3 times higher than usual? Could the counter be getting cached (despite being marked as volatile) and not reset properly? If so, how can I prevent this?

My guess is the operations you are using are not atomic.  This is, the interrupt is able to be fired right in the middle of doing the series of instructions that perform the increment. The temporary registers end up not being the same as they were at the start of the operation, and consequently the value is corrupted.  You should wrap the increment in a *critical section* (i.e., disable interrupts before it, and enable them afterwards).

To better analyse the speed of execution you can look at the generated assembly code of your program.  If we look at the disassembled `main()` function for the bit where it loops you can get this:

    80596: f7ff fe05  bl 801a4 <loop>
    8059a: 4b04       ldr r3, [pc, #16] ; (805ac <main+0x30>)
    8059c: 2b00       cmp r3, #0
    8059e: d0fa       beq.n 80596 <main+0x1a>
    805a0: f7ff feec  bl 8037c <_Z14serialEventRunv>
    805a4: e7f7       b.n 80596 <main+0x1a>
    805a6: bf00       nop

`loop()` consists of this:

    801a4: 4b02       ldr r3, [pc, #8] ; (801b0 <loop+0xc>)
    801a6: 681a       ldr r2, [r3, #0]
    801a8: 3201       adds r2, #1
    801aa: 601a       str r2, [r3, #0]
    801ac: 4770       bx lr
    801ae: bf00       nop

If we feed that into `main()` where it calls `loop()` the finished code looks like:

    80596: f7ff fe05  bl 801a4 <loop>
    801a4: 4b02       ldr r3, [pc, #8] ; (801b0 <loop+0xc>)
    801a6: 681a       ldr r2, [r3, #0]
    801a8: 3201       adds r2, #1
    801aa: 601a       str r2, [r3, #0]
    801ac: 4770       bx lr
    801ae: bf00       nop
    8059a: 4b04       ldr r3, [pc, #16] ; (805ac <main+0x30>)
    8059c: 2b00       cmp r3, #0
    8059e: d0fa       beq.n 80596 <main+0x1a>
    805a0: f7ff feec  bl 8037c <_Z14serialEventRunv>
    805a4: e7f7       b.n 80596 <main+0x1a>
    805a6: bf00       nop

So that is what gets executed for every single iteration of `loop()`.  If we (incorrectly) assume that each instruction takes 1 clock tick, that's 13 ticks.  84,000,000 / 13 = ~6.4 million loops per second.

Now - if we map the instructions against actually how many clock cycles they take, we can get a clearer picture:

    bl                  1+P  (P = 1 to 3)
    ldr (pc relative)   2
    ldr (word)          2
    adds                1
    str (word)          2
    bx                  1+P  (P = 1 to 3)
    nop                 1
    ldr (pc relative)   2
    cmp                 1
    beq.n               1 or 1+P (P = 1 to 3)
    bl                  1+P (Only if serial event runs)
    b.n                 1 or 1+P (P = 1 to 3)
    nop                 1

So taking a worst case scenario where P = 3 (pipeline re-fill clock counts, that is), and no serial event running, we can calculate a total number of clock cycles of 4+2+2+1+2+4+1+2+1+4+0+4+1 = 28.

84,000,000 / 28 = 3,000,000 loops per second.

But hang on - that's still much more than you're seeing.  That's because you're still only looking at the small picture.  You're looking at just your sketch and forgetting what else there is going on.

Every millisecond the `SysTick_Handler()` gets called which does various tasks, including calling the `TimeTick_Increment()` routine to deal with `millis()`.  That's 1,000 times per second, and that eats into your processing time somewhat.

Another important point is *it can't be incrementing while you're running your interrupt*.  The more you do in your interrupt (*and using serial is a very heavy-weight thing to do in an interrupt*) the less of your 1-second slice you get for doing your incrementing.

As an experiment, why not try disabling all the interrupts except just the one you are using for your timer and see how it changes the value.


body:
I'm trying to send an email using an Arduino Uno and a Sparkfun CC3000. When I plugged in the arduino to the computer with the code I wrote for it, all wireless communication in the room I was in went down. This includes both computers that were there, my cell phone, even my Pebble Watch got disconnected. Any idea on why this happened and how to fix it? I replicated this numerous times to make sure it wasn't a fluke.

Here is my code

    PingTest.ino
    CC3000 Ping Test
    Shawn Hymel @ SparkFun Electronics
    February 1, 2014
    https://github.com/sparkfun/SFE_CC3000_Library

    Connects to the access point given by the SSID and password and
    waits for a DHCP-assigned IP address. Pings the give website or
    IP address and waits for a response.

    The security mode is defined by one of the following:
    WLAN_SEC_UNSEC, WLAN_SEC_WEP, WLAN_SEC_WPA, WLAN_SEC_WPA2

    Hardware Connections:

     Uno Pin    CC3000 Board    Function

     +5V        VCC or +5V      5V
     GND        GND             GND
     2          INT             Interrupt
     7          EN              WiFi Enable
     10         CS              SPI Chip Select
     11         MOSI            SPI MOSI
     12         MISO            SPI MISO
     13         SCK             SPI Clock

    Resources:
    Include SPI.h and SFE_CC3000.h

    Development environment specifics:
    Written in Arduino 1.0.5
    Tested with Arduino UNO R3

    This code is beerware; if you see me (or any other SparkFun
    employee) at the local, and you've found our code helpful, please
    buy us a round!

    Distributed as-is; no warranty is given.
    ****************************************************************/

    #include <SPI.h>
    #include <SFE_CC3000.h>
    #include <SFE_CC3000_Client.h>
    #include <Client.h>
    #include <Temboo.h>
    #include "TembooAccount.h" // Contains Temboo account information

    // Pins
    #define CC3000_INT      3   // Needs to be an interrupt pin (D2/D3)
    #define CC3000_EN       9   // Can be any digital pin
    #define CC3000_CS       10  // Preferred is pin 10 on Uno

    // Connection info data lengths
    #define IP_ADDR_LEN     4   // Length of IP address in bytes

    // Constants
    char ap_ssid[] = "comcast";                  // SSID of network
    char ap_password[] = "gooddays";          // Password of network
    unsigned int ap_security = WLAN_SEC_WPA2; // Security of network
    unsigned int timeout = 30000;             // Milliseconds
    char remote_host[] = "www.sparkfun.com";  // Host to ping
    unsigned int num_pings = 3;    // Number of times to ping

    // Global Variables
    SFE_CC3000 wifi = SFE_CC3000(CC3000_INT, CC3000_EN, CC3000_CS);
    SFE_CC3000_Client client = SFE_CC3000_Client(wifi);

    int numRuns = 1;   // Execution count, so this doesn't run forever
    int maxRuns = 10;

    void setup() {

      ConnectionInfo connection_info;
      IPAddress ip_addr;
      IPAddress remote_ip;
      PingReport ping_report = {0};
      int i;

      // Initialize Serial port
      Serial.begin(115200);
      Serial.println();
      Serial.println("---------------------------");
      Serial.println("SparkFun CC3000 - Ping Test");
      Serial.println("---------------------------");

      // Initialize CC3000 (configure SPI communications)
      if ( wifi.init() ) {
        Serial.println("CC3000 initialization complete");
      } else {
        Serial.println("Something went wrong during CC3000 init!");
      }

      // Connect and wait for DHCP-assigned IP address
      Serial.print("Connecting to: ");
      Serial.println(ap_ssid);
      if(!wifi.connect(ap_ssid, ap_security, ap_password, timeout)) {
        Serial.println("Error: Could not connect to AP");
      }

      // Gather connection details and print IP address
      if ( !wifi.getConnectionInfo(connection_info) ) {
        Serial.println("Error: Could not obtain connection details");
      } else {
        Serial.println("Connected!");
        Serial.print("IP Address: ");
        for (i = 0; i < IP_ADDR_LEN; i++) {
          Serial.print(connection_info.ip_address[i]);
          if ( i < IP_ADDR_LEN - 1 ) {
            Serial.print(".");
          }
        }
        Serial.println();
      }

      // Perform a DNS lookup to get the IP address of a host
      Serial.print("Looking up IP address of: ");
      Serial.println(remote_host);
      if ( !wifi.dnsLookup(remote_host, &remote_ip) ) {
        Serial.println("Error: Could not lookup host by name");
      } else {
        Serial.print("IP address found: ");
        for (i = 0; i < IP_ADDR_LEN; i++) {
          Serial.print(remote_ip[i], DEC);
          if ( i < IP_ADDR_LEN - 1 ) {
            Serial.print(".");
          }
        }
        Serial.println();
      }

      // Ping IP address of remote host
      Serial.print("Pinging ");
      for (i = 0; i < IP_ADDR_LEN; i++) {
        Serial.print(remote_ip[i], DEC);
        if ( i < IP_ADDR_LEN - 1 ) {
          Serial.print(".");
        }
      }
      Serial.print(" ");
      Serial.print(num_pings, DEC);
      Serial.println(" times...");
      if ( !wifi.ping(remote_ip, ping_report, 3, 56, 1000) ) {
        Serial.println("Error: no ping response");
      } else {
        Serial.println("Pong!");
        Serial.println();
        Serial.print("Packets sent: ");
        Serial.println(ping_report.packets_sent);
        Serial.print("Packets received: ");
        Serial.println(ping_report.packets_received);
        Serial.print("Min round time (ms): ");
        Serial.println(ping_report.min_round_time);
        Serial.print("Max round time (ms): ");
        Serial.println(ping_report.max_round_time);
        Serial.print("Avg round time (ms): ");
        Serial.println(ping_report.avg_round_time);
        Serial.println();
      }

      // Disconnect
      if ( wifi.disconnect() ) {
        Serial.println("Disconnected");
      } else {
        Serial.println("Error: Could not disconnect from network");
      }

      // Done!
      Serial.println("Finished ping test");

    }
        TembooChoreo SendEmailChoreo(client);
    void loop() {
      if (numRuns <= maxRuns) {
        Serial.println("Running SendEmail - Run #" + String(numRuns++));

        //TembooChoreo SendEmailChoreo(client);

        // Invoke the Temboo client
        SendEmailChoreo.begin();

        // Set Temboo account credentials
        SendEmailChoreo.setAccountName(TEMBOO_ACCOUNT);
        SendEmailChoreo.setAppKeyName(TEMBOO_APP_KEY_NAME);
        SendEmailChoreo.setAppKey(TEMBOO_APP_KEY);

        // Set profile to use for execution
        SendEmailChoreo.setProfile("Testofsoftware");

        // Identify the Choreo to run
        SendEmailChoreo.setChoreo("/Library/Google/Gmail/SendEmail");

        // Run the Choreo; when results are available, print them to serial
        SendEmailChoreo.run();

        while(SendEmailChoreo.available()) {
          char c = SendEmailChoreo.read();
          Serial.print(c);
        }
        SendEmailChoreo.close();
      }

      Serial.println("\nWaiting...\n");
      delay(30000); // wait 30 seconds between SendEmail calls
    }

title: CC3000 Blocking All Wireless Communication

Answers: 2

body:
not a direct answer but the [sparkfun hookup guide][1] connects pin 8 (SDCS) to the chip select for the SD card. If this line is floating, I'm not sure of the impact.

  [1]: https://learn.sparkfun.com/tutorials/cc3000-hookup-guide

body:
Because of the limited information given any answers given will be by nature limited. However, I can suggest several troubleshooting tips.

----------
## Tips ##

 1. Verify that username and password used are exactly right(punctuation, spaces, etc.). Where you put`comcast` you should put the name of the network not the name of the provider. I am not sure if you have done this or not.
 2. Make sure network is in fact WPA2.
 3. In order to debug the issue make sure if you are getting nothing through serial to set it to the baud rate of `115200`.
 4. If you are using the breakout board make sure you correctly wired it and check any solder points:
![wiring][1]
 5. Make sure you have the correct libraries installed.  Also, try sample code from the examples. Libraries can be found [here][2].

----------
Many of these seem obvious but can through someone off. So try these and let me know the results. A lot of information about setup can be found [here][3].

**EDIT** Try removing the

    if ( wifi.disconnect() ) {
        Serial.println("Disconnected");
      } else {
        Serial.println("Error: Could not disconnect from network");
      }
block. It appears that you are disconnecting before going into the main loop. This would obviously make it impossible to send an email. The reason pining would work sometimes would be that wifi.disconnect() is called sometimes but not all the time. To narrow the issue try an example code from the library.

  [1]: https://i.stack.imgur.com/7kL9c.png
  [2]: https://github.com/sparkfun/SFE_CC3000_Library
  [3]: https://learn.sparkfun.com/tutorials/cc3000-hookup-guide


body:
I run my 12V car battery trough a trimpot into my pro micro, micro controller.
I am using (voltPinValue1 * 0.01465) to get the Volt out of analog in. I have trimmed the pots and getting the right V.

But now I want to calculate for how long I can run for, example the stereo and some LED:s, but don't know how.. Does anybody know how I can do this??

Sorry for my English

Thanks! //Rasmus

title: Calculate how much battery power left

Answers: 1

body:
You really need to know the current being drawn rather than the instantaneous voltage. A voltage drop profile of a battery changes depending on the current draw, and just using the voltage is very very hard indeed.

You could measure the voltage over time, and try and calculate the slope of the voltage and attempt to predict when it would reach a specific pre-determined cut-off point, but since that change in voltage will be non-linear it's not really something that can easily be calculated.

But, if you can measure the current instead, and you know the Ah of the battery, then you can get a better estimate of how long the battery will run until it's considered flat.


body:
So, I was working on a project where I needed to get a random object from a stack, so to make sure my design was correct, I made a dummy program that does nothing but fill a stack with data, then print it out.
![enter image description here][1]

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

why in the world is nothing coming out of the stack but -1s??

Here's the stack.h file.

http://pastebin.com/vjhNLpNu

title: Stack isn't popping off correct data?

Answers: 2

body:
You're not telling it how big your stack should be, and it defaults to 0 entries, which means nothing gets stored.

    class Stack
    {
    private:
        int *p;
        int top,length;

    public:
        Stack(int = 0);  <<== CONSTRUCTOR - DEFAULT SIZE IS 0
        ~Stack();

        void push(int);
        int pop();
        void display();
    };

When you make your Stack object you must give it a size for the number of entries in the stack:

    Stack stack(4);

body:
You never allocate space for the stack.

The way it's written, you need to pass the stack size into the constructor, and then it's fixed for the lifetime of the object; i.e. it won't grow automatically when you call `push()`. You're not passing anything into the `Stack` constructor, so the parameter is defaulting to `0`, meaning it has zero size.

The solution is to declare the stack something like this:

    Stack stack(10);

(10 is just an arbitrary size -- use whatever you expect to need.)

Incidentally, there isn't an effective safeguard in your code to handle an empty stack. The result is that you're technically getting undefined behaviour at the moment when you call `push()` (it's writing to arbitrary memory locations).


body: I've connected a SIM900A GSM module to Arduino and the circuit works standalone on a 12V power supply. The problem is when I provide the 12V power supply, both GSM module and Arduino starts but the Arduino don't initializes the program for GSM module and hence the send or receive message functions don't work. Also when I first power on the GSM module and let it initialize first and then power on the Arduino, everything works fine. How to deal with this problem?

title: How to power on Arduino a few seconds later after GSM module initialization?

Answers: 2

body:
Let the 12 V charge a large capacitor over a resistor. The time to charge to 63% is RxC. Place a 5 V zener diode parallel to the capacitor, so that doesn't damage the microcontroller. Then either connect to the microcontroller's reset, or, and this is "nicer", use a MAX809 reset controller. The latter will keep the output low until a precise threshold is reached, there's for instance a 4.00 V version. Use that output to keep the microcontroller reset for some time.

Not sure how much delay you want, but a 10 uF capacitor and a 100k resistor will give you (from the top of my head) about half a second before the voltage on the capacitor reaches 4 V.

body:
It sounds like your problem is that the GSM module needs time to initialize before it is ready to be talked to by the Arduino.

A crude way of providing this would be to use the `delay()` function in the Setup() of your sketch.  The argument to that is an `unsigned long` number of milliseconds (thousandths of a second) so it can produce delays far longer than you need.

But a more sophisticated solution would be to repeatedly try to talk to the module and check for an expected response.  Apparently, with at least some of these, if you disable baud rate detection they will announce themselves with a prompt when they are ready - you could wait for that.  But I think repeatedly trying until you get a response is going to be the most robust.


body:
I'm trying to convert a class header file from another c++ project to arduino, which in my mind involves replacing cout with Serial.println.

When I try to recomplile with all of these changes, I get this error from the compiler:

    error: 'Serial' was not declared in this scope
         Serial.print(p[i]);

Can someone explain this to me?

title: Can I use Serial.println() in a class?

Answers: 1

body:
You have to `#include <Arduino.h>`, or compile with the `-include Arduino.h` flag. The Arduino IDE normally does that for you, but you have to do it yourself if you are working outside the IDE.

There are a couple of Arduino Makefiles floating around the Web which, just like the IDE, take care of this for you.


body:
I have an arduino nano which is powered through unregulated 5V (pin 27). For debugging purpose, I'd like to connect the USB port to my computer in order to use the Serial.Print function. The external 5V will stay connected. Will this cause damage ?

edit : I forgot to mention that the external power supplied to pin 27 is regulated with a switching DC-DC converter (measured 5.1V). Sorry it was not clear in my question.

Here is my circuit :

![Schema](https://i.stack.imgur.com/avlw4.png)

The switching regulator is not exactly the one in the schema.

Is using the circuit with the battery power supply + usb connection to my computer will damage something ?

title: Is supplying 5V from both external 5V and USB harmful?

Answers: 2

body:
Since the external 5V supply is not regulated, it may cause some problems. It is possible that a small voltage difference will appear if and when the external voltage fluctuates from the 5V level. What you should do is short-circuit the 5V of the USB to pin 27.

And in general, add a 5V regulator circuit to feed the Arduino nano, like this one: ![http://www.techulator.com/attachments/Resources/10562-75631-V-Voltage-Regulator.jpg][1]

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

body:
No, it probably won't damage anything, as the PC's USB port is protected from overvoltage by the D1 schottky device on your arduino board.

**Update, my previous answer contained the following paragraph, which is not related to your problem**

> But you should take care of some things.
>
>  1. Make sure, the voltage applied to your +5V-Net is regulated properly elsewhere. I.e. choose a laboratory PSU or another good
> source.
>  2. Avoid having both your PC and your 5V-supply connected to line voltage. Ground levels may differ due to Y-capacitors present in the
> switching PSUs. Those provide a AC voltage of half your line voltage
> to DC ground (only with 0.3 to 0.7 mA, but enough to cause
> disturbances on your signals at 55 volts in the US or 115 V in the EU)
>  3. If you have to use two switching PSU for both PC and arduino, provide an equipotential bonding between your PC's mass (e.g.
> VGA-port-screw) to your arduino's PSU's ground directly, to prevent
> leakage currents from the Y-capacitors wandering around in your
> circuitry.

**Update according to your enhanced question**

You are using a battery powered DC-DC supply for your Arduino. So, my previous notes do not apply to your problem.

 - 5.1 V seem exact enough to drive your arduino safely. No need for additional stabilisation measures
 - D1 (see genuine arduino schematic) separates USB-Power from +5V and prevents current flowing in reverse direction over your USB connection.
 - Arduino circuitry and USB port have common GND so there are always well defined voltage levels.

In my opinion, there's nothing with your setup, which may harm your circuitry or your PC.

Depending on the maximum power of your DC-DC converter you may consider adding a fuse to protect converter and components in case of short circuit.


body:
im working on a project which requires alo i/o pins. For that reason i bought a pcf8574P 8bit I/O expander which uses the I2C protocol. The problem is how to combine the Rasp PI and the arduino.

## For example:

I want the Rasp to send data to the Arduino. Currently i'm using serial but i wanted to switch over to I2C because it better, simpler, and faster however how can i use 2 I2C when the Atmega 328P supports only 1 I2C bus?

The plan goes like this:

The PI is master of the arduino and it sends the data. Arduino is the slave

Arduino is master of the IO expander and the expander is slave

## Possible solutions:

 1. Use the Serial protocol to send the data and use the I2C for the expander
 2. Make the arduino master of the PI and the expander which i'm not sure if its possible

title: I2C with an arduino, a PI and an IO expander

Answers: 0


body:
I have two XBees S2, one is configured as an API coordinator connected to Arduino and the other as an AT router.

The coordinator sends a frame to the router to switch on a LED. I want to switch off that LED with a button and the router send a message to the coordinator to tell him that it switch off the LED.

How can I do this?

I have one Arduino with the coordinator. I'm asking what I have to put in the script to make the coordinator receive the data.

Here is my code, how the coordinator sends the data to the router:

    String inputString;
    int led = 13;
    void setup() {
    pinMode(led, OUTPUT);
    Seria.begin(9600);
    }
    void loop() {
    while (Serial.available() ) {
    // get the new byte:
    delay(3);
    char inChar = Serial.read();
    // add it to the inputString:
    inputString += inChar;
    }
    if (inputString.length() >0) {
    Serial.println(inputString);
    if (inputString == "on"){
    digitalWrite(led,HIGH);
    setRemoteState(5);

    }
    inputString="";
    }
    }

    void setRemoteState(char value){
    Serial.write(0x7E); // start byte
    Serial.write((byte)0x0);
    Serial.write(0x10);
    Serial.write(0x17);
    Serial.write((byte)0x0);
    // id of recipient or use 0xFFFF for broadcast
    Serial.write((byte)00);
    Serial.write((byte)00);
    Serial.write((byte)00);
    Serial.write((byte)00);
    Serial.write((byte)00);
    Serial.write((byte)00);
    Serial.write(0xFF);
    Serial.write(0xFF);
    // 16 bit of reciepent
    Serial.write(0xFF);
    Serial.write(0xFE);

    Serial.write(0x02);

      Serial.write('D');
      Serial.write('2');

     Serial.write(value);

    long sum = 0x17 + 0xFF + 0xFF + 0xFF + 0xFE + 0x02 + 'D' + '2' + value;
    Serial.write(0xFF - ( sum & 0xFF) );
    Serial.print(sum,HEX);
    }

title: How does coordinator XBee receive data from router?

Answers: 2

body:
When you have one working as AT mode, it puts out whatever comes in, it is also called transparent mode.

You should first define which mode you want to use them and start coding.

If you choose AT, load the firmware for both and use Arduino to check the commands and execute tasks (supposing it is connected to the router).

If the task was done correctly, you send an okay message, otherwise, send error. This is a simple task in AT mode, just use Serial:

    if (led == 1)
       Serial.println("ok");
    else
       Serial.println("error");

If you choose API mode, it is a little bit different, where you have to mount the packet for sending data and put a message inside it. There are some [libs][1] out there you can achieve this.

On the other side, the coordinator will receive the message and interpret it.

If it is in AT mode, just read the serial. In API, you have to decode the packet and check the payload field where the data is located.

  [1]: https://code.google.com/p/xbee-arduino/

body: To change the state of digital pin 2,D2 set the "value" to 0x05 to switch it HIGH and set the "value" to 0x04 to switch the pin LOW


body:
I'm looking to directly program an ESP8266 WiFi Module with out using a FTDI (USB-Serial interface) as suggested in this excelent [tutorial](https://www.openhomeautomation.net/control-a-lamp-remotely-using-the-esp8266-wifi-chip/). The real purpose is to have access to the GPIO ports of the module.

I heard (from [this page](http://hackaday.com/2009/09/22/introduction-to-ftdi-bitbang-mode/)) that one can use an Arduino UNO as an intermediate interface for burning the bootloader onto an AVR (e.g. ATmega168 or ATmega328). That is, using the ArduinoISP code example in the IDE.

Is it possible to use an Arduino UNO as temporal bridge to program the ESP8266? Can anyone please suggest some tutorial? Thanks

title: Simulate a FTDI using an Arduino UNO

Answers: 1

body:
The simplest way is to unplug the ATMega328P from the board (or otherwise disable it) and just use the ATMega16U2 by connecting the ESP8266 to pins 0 and 1 of the Uno.  No programming required at all then - the ESP8266 just takes the place of the ATMega328P.

If you really want to "pass it through" the ATMega328P then you will need to make a transparent pipe for the serial data.  That would involve nominating two more pins on the Uno to be a new serial connection, and using SoftwareSerial to interface with those pins.  Then you have a simple loop which reads from one port and writes to the other, and the same in reverse of course.  Make sure you have the baud rates right.  I don't know how well SoftwareSerial would perform at the (commonly) 115200 baud the ESP8266 works at.

EDIT: (Interfacing to a 3.3-V system)

Since the ESP8266 works at 3.3V, while the ATMEGA16U2 is powered at 5V, you might need to adapt the level of the ATMEGA16U2's TXD line (which is connected to the "RX" input line of the ATMEGA328P/Arduino Uno Board), to 3.3V.

To do this, connect a  1.5 kOhm resistor between the RX pin and ground. In fact, the connection between ATMEGA16U2 and ATMEGA328P is done using an 1kOhm series resistor. This, together with the 1.5k Ohm resistor, will create a resistor divider, which converts the 5V output to 3V.

See schematics below.
[![Suggested modifications][1]][1]

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