text:
Sketch not running as expected
I wrote this sketch along with an HC - SR 04 Ultrasonic transducer and a DC motor. Whenever the HC-SR 04 reads any distance less than 15 cm, the motor stops, otherwise it keeps running.
The problem is whenever I upload the sketch, the motor runs for a short while and stops. Then when I open my serial monitor, the motor runs until an object crosses the 15 cm threshold and stops right after the limit is crossed. But when I again put the object outside of the 15 cm range, the motor should start running again, but it doesn't.
I am using a this motor driver and a simple DC motor(12V).
Here's the code-
int trigPin1 = A0;
int echoPin1 = A1;
int distance1 = 0;
int E1 = 10;
int brake1 = 7;

void setup() {
  pinMode(trigPin1, OUTPUT);
  pinMode(echoPin1, INPUT);
  pinMode(brake1, OUTPUT);
  pinMode (E1, OUTPUT);
  Serial.begin(9600);
}

void loop() {
  analogWrite(E1, 153);
  distance1 = getDistance(trigPin1, echoPin1);
  printDistance(1, distance1);
  delay(250);
  if(distance1 <=15){
    digitalWrite(brake1, HIGH);
  }
  else{
    analogWrite(E1, 153);
  }

}

int getDistance (int initPin, int echoPin) {
  digitalWrite(initPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(initPin, LOW);
  long pulseTime = pulseIn(echoPin, HIGH);
  int distance = pulseTime / 58.2;
  return distance;
}

void printDistance(int id, int dist) {

  Serial.print(id);
  if (dist >= 120 || dist <= 0 ) {
  Serial.println(" Out of range");
  }
  else{
   Serial.print("\t");
   Serial.print(dist);
   Serial.println(" cm");
}
}

What mistake am I doing? Moreover I am currently running it with one motor, I'll add another later on along with more sensors, so the motors are controlled by the left or right sensor. How do I make my code work with them?
Thanks...

It was too damn simple...
I just had to add a line inside the else block in the loop function.
digitalWrite(brake1, LOW);

This was happening because the first time the threshold limit was crossed the brake1 pin was left HIGH and was never set to LOW again, which caused a permanent brake in the motor.
I'm too damn stupid. But I still don't have any idea how will I use this code with multiple sensors and motors.


text:
Porting ATMega8 AVR based program to Intel Curie Processor
I'm currently trying to port a program called 'ArduinoUSBLinker' to work on my Arduino 101 (which has an Intel Curie CPU instead of the standard ATMega CPU).
The program is used to flash ESCs without the need of additional hardware.
Arduino USB Linker
Unfortunately the code is mainly based on the ATMega's built in AVR timers,
which uses several different predefined variables such as TCCR0,TCCR1,TCTN2…
These are not available (or are they?) in the Curie Module. Since the Arduino 101 has timer functionality, I was wondering if there is a way to translate those into the Curie Timer library.

Those variables are the addresses of physical registers on the AVR that manipulate its timer/counters. Most other processors will have equivalent, but not likely identical, hardware. You'll need to port functionality, not the code.
You'll need to reverse-engineer (worst-case) the code you're trying to port (assuming you aren't intimately familiar with it, e.g., you designed it), develop a spec for it (at least in your head), and write to that spec for the Curie.
If the overall job is not (too heavily) processor-specific, you may be able to write it to be portable by writing the job-specific code in, e.g., in C, and call well-defined functions (in C or assembler) for the CPU-specific ones, that could easily be replicated on another processor.

source: Stack Exchange

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

sort: votes


text:
GSM GPRS for sending an sms
I want to know if it is possible to send an SMS from a SIM900 using Arduinos to another SIM900.
Problem: When the gsm is connected to the network, it does not send an sms; my airtime balance remains the same.
Here is the code I used:
#include <SoftwareSerial.h>
SoftwareSerial SIM900 (9,10);

void setup()
{
   serial.begin(9600);
   SIM900.begin(9600);
   delay(5000);
}

void loop()
{
   sendSMS();

   while(SIM900.available()!=0)
     {
        Serial.println(SIM900.read());
     }
}

void sendSMS()
{
    SIM900.println("AT+CMGF=1\r");
    delay(100);
    SIM900.println("AT+CMGS=\"+27769384488"\r");
    delay(100);
    SIM900.println("Hello");
    delay(100);
    SIM900.println((char)26);
    delay(100);
    SIM900.println();
    delay(5000);

}

Yes, it is possible.
Your code doesn't show any sign of board powering on and initialization.
SIM900 has some LED that show status - make sure you are connected to GSM network.
Please check this tutorial: https://www.youtube.com/watch?v=RUGV_64lQX8

Thanks for respond, I have used Hash include SoftwareSerial.h   #include <SoftwareSerial.h> but the website refused to display it, i was powering it using the button in it.  Is this the only initialization used?

I had worked on GSM long back ago and sometimes it becomes very difficult to debug the problem. However u need to just check whether the AT commands are being sent properly to the GSM module. I had tried using Software Serial but it did not work for me but when I switched to the usual Serial port it worked like a charm. Few things that you need to check are:

Check the baud rate of GSM module. Does it match with the baud rate of Software Serial.
Do a if-else check to see whether the commands are actually being sent to the GSM module. The println() returns the number of bytes written so you can do like this in your sendSMS() function.

  int a; //To store the number of bytes written
  a=SIM900.println("AT command to be sent");
  if(a)
  {
  Serial.println("Command sent");
  }
  else
  {
  Serial.println("Command not sent");
  }

Now upload the code and open the serial monitor to see whether the command is actually being sent to the GSM module or not.

You also need to check whether the format of your AT command is correct. Because you need to send \n(newline) and\r(carriage return) at the end of every AT command to ensure proper operation. For this you need to read the response sent back by the GSM module after every command. This can be done by reading the Software serial port and the printing the response onto the Serial monitor.
You also need to check whether your GSM module has detected the SIM card. Usually this is indicated by an onboard LED that blinks after every 3 seconds.

I think your code is pretty much correct but try to ensure that everything is setup properly as I said.
Here is my code but I used Serial port instead:

  void setup()
  {
    Serial.begin(9600);
    delay(10000);  \\For initialization purpose
  }
  void sendSMS()
  {
    Serial.println("AT+CMGF=1");
    delay(5000);
    Serial.println("AT+CMGS=\"Phone number with international code\"");
    delay(5000);
    Serial.print("Hello");
    delay(5000);
    Serial.println((char)26);
    delay(5000);
  }
  void loop()
  {
    sendSMS();
    do
    {
    }while(1);
  }

This code will send the SMS once so you need to reset the board for sending another SMS or you can remove the do while loop for continuous operation.You can adjust the delay accordingly.

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


text:
How to upload one program into several Arduinos at once?
I am trying to upload a single program to a number of Arduinos one by one. But it is time consuming. So I would like to know if there is any way to upload the code at once to multiple Arduinos.
I have tried as follows:
3 Arduino with all the Rx, Reset, Vcc, Gnd line connected to each other. Only pin left is Tx line. So I just connect the Tx line of one arduino and program it and so on.
Is there any other way?

Are you programming them for the first time or doing a update?
If is the first programming, I cant see another way.
Otherwise, If is a update and your Arduino have a Wifi module you could try something like an update on the air, where you put your new firmware in a server for example and all devices updates yourself automatically or by a command.
Google for Arduino OTA (on the air) you will get a lot of source code and examples of doing that.

Thank You for valuable time.
This is not about OTA.Its for first-time code uploading.

Arduino uses a microcontroller from Atmel and uses a programming tool that is designed for development use and not for production programming.
What you are looking for are tools that are called "production programming tools". Atmel has a nice documentation which describes their different programming solutions: link.


text:
Accepting strings and integers via UART
My intention is to write a code that asks a user to enter the name and then the age. The code should then simply display the persons name and age. To do that, I have written a simple code. I find it difficult to get it to work.
char temp = 0;
char ArrayName [50];
int positionArray = 0;
int age =0;

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

void loop() {

    positionArray = 0;
    Serial.println ("What is your name?");

    do {

        while (Serial.available()==0);
        temp = Serial.read ();
        ArrayName [positionArray++] = temp;
    } while (temp != '\r');

    ArrayName [--positionArray] = '\0';

    Serial.print ("Your Name is: ");
    Serial.println (ArrayName);

    // clear the UART Buffer
    while (Serial.available()==1){
        temp = Serial.read();
    }

    Serial.println ("What is your age?");
    while (Serial.available()==0);
    temp = Serial.read ();
    age = temp;

    Serial.print ("You are ");
    Serial.print (age);
    Serial.println (" Years old.");

    while (Serial.available()==1){
        temp = Serial.read();
        delay (10);
    }

}

The error I receive is that the program already outputs age without me even typing it.  Would it be possible to know the error?
I use both NL and CR to send in characters to Arduino and the Arduino IDEs default UART terminal.
EDIT:
Listening to advice gotton from answers I got the code to work but in a very weird way. My new code works! but it proves the clearing of buffer cannot be done by just reading it. This is in contrast to Arduino documents. My new code is as follows.
char temp = 0;
char ArrayName [50];
int positionArray = 0;
int age =0;

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

void loop() {

    positionArray = 0;
    Serial.println ("What is your name?");

    do {

        while (Serial.available()==0);
        temp = Serial.read ();
        ArrayName [positionArray++] = temp;
    } while (temp != '\r');

    ArrayName [--positionArray] = '\0';

    Serial.print ("Your Name is: ");
    Serial.println (ArrayName);

    // clear the UART Buffer **WHY IS THIS CODE NOT EFFECTIVE?**
    while (Serial.available() >= 1){
        temp = Serial.read(); // performing dummy reads untill buffer empty.
    }

    temp = Serial.read();
    delay (1000);
    temp = Serial.read();
    temp = Serial.read();
    temp = Serial.read();

    Serial.println ("What is your age?");
    while (Serial.available()==0);
    temp = Serial.read ();
    temp = temp - 48;
    age = temp*10;
    delay (1000); // providing the user a day to enter next digit of age

    if (Serial.available()){
        temp =  Serial.read ();
        temp = temp - 48;
        age = (int) temp + age; //whatever that is added have to be of same type. Else they need to be cased to same type.
    }

    Serial.print ("You are ");
    Serial.print (age);
    Serial.println (" Years old.");

    while (Serial.available() >=1 ){
        temp = Serial.read();
        delay (10);
    }

}

In what way does it "not work"?

As we don't know what you are using as a terminal program we can't comment specifically on your choice of EOL characters.
It is likely you are receiving everything in ASCII code.  That is, when you type the number 1 you are actually getting the ASCII equivalent (0x31) from your terminal.
This is fine when you are working with character strings.  But when you want to work with numbers that are to be used in equations you need to 1) make sure that the user is only entering a number (check to make sure the values are from 0x30 to 0x39) and 2) subtract the ASCII value for '0' from the value you received from the terminal.  That is, subtract 0x30.
It should now be obvious that you can only enter 1 digit at a time when using a terminal.  That you will have to reconstruct the number as the user types each digit.  For example the number 13 is a 1 and a 3 and you will have to multiply the 1 by 10 then add it to the 3.
Since this is such a common conversion, there are Arduino libraries that do this for you.  Consider using ParseInt for this purpose.
Added later...
In the modified code, consider the possibility the terminal program is sending both a Carriage Return (aka: CR, 0x0D, \r) and Line Feed (aka: LF, 0x0A, \n) each time the Enter key is pressed.  And that the code is only waiting for the CR.
The delays are necessary as UART communication, as most communications, takes a finite amount of time.  And additional characters, if any, and even if autonomously sent, will take a finite amount of time to arrive.
Consider "looking" for the LF character after finding for the CR character and removing the added delays.

Great answer. Thank you.
Could you also please tell me why my code automatically moves to accepting age without me even typing it? I'm clearing the UART buffer by reading it untill it becomes empty prior to asking the user for age. Still, the code goes on and spits out the age of the user without me even typing it.
Thank you for teaching me my error and telling me that I need to handle user inputs for integers as single ASCII charactors.

You did not repeat your code design when entering a string of characters when you coded up the part of your program to enter the age.  You basically said: "If there is something from the terminal read it.  Otherwise skip reading anything."  As you can't type that fast (time between pressing the enter key and typing the 1st digit of the age), the program continued on to the end.

If you are a beginning programmer, I would recommend you do all your own parsing and ASCII to integer conversion.  It is good experience.  As your programs become more complex, you can benefit from using libraries to keep you programs "clean" and their purpose obvious.

no I have stated "while (Serial.available()==0);" just after I asked to enter age. therefore shouldn't the program halt there until I type something? I mean at that point the program is supposed to stop there and wait  till I type something am i right? At times, it take the new line charactor ASCII 10 as age. I do not understand how it takes a new line charactor as age because I am clearing the buffer by reading before asking for age.

Thank you. I am sort of a moderate level I believe. but I really want to know whats happening behind. THats the reason I want to make this work. but its not as easy as it sounds I guess.

After this line: "// clear the UART Buffer",  try changing  "  while (Serial.available()==1){    " to "  while (Serial.available() >= 1){    "

Im sorry it did not work. I tried it. same result.

the question is just after Serial.println ("What is your age?"); I have included the line
while (Serial.available()==0). Therefore it cannot proceed if the buffer is empty. Aparently reading it didnt make it empty.

Stack Exchange isn't a good place to debug code.  But, going on, my next suggestion is to print out the character read after each and every read.  I would use "Serial.print(temp, HEX)" so everything (including control characters) are printed as hex number.  Then look them up in the ASCII table to find their exact meaning.  You might have some other bugs but once you get this working you can spot and fix them.

Sorry I didnt know that. I would not post this type of questions here again.
Okay. I will do that and see.
thank you a lot for your help

I made the code work as per your advice. Unfortunately, it requires a weird delay and I do not understand why. Please telll me if you could understand already why it is so.

Let us continue this discussion in chat.


text:
Arduino with wifi shield and 5AA batteries current draw
Arduino uno with official Wifi Shield take 5 Volts.
Arduino lights up as it should when powered but the WiFi shield is dead the l9 doesn't light up but works fine when arduino is connected to usb cable.
I use 5 battery holder 5x1.5V = 7.5 V ; 2000 mAH
50 mA - Arduino
300 mA - WiFi shield

350 mA * 5h = 1750 mAh

5xAA = 7.5V ; 2000 mAh

Am I missing here something? It should last in the worst case scenario 5 hours with new batteries at 2000 mAH (which I think they have more but I do not have them on me right now).

We are not the arduino help desk.

@OlinLathrop I'm asking if I did the calculations correctly? if that makes sense

Ignore Olin. He's stuck in the fifties.

What does the 5V rail show when on batteries and the wifi shield connected?

@Passerby I wish I had access right now to all the equipment I'm a student I'm using it all at lab so I just wanted to know if my calculations made sense. I will retry tomorrow with fresh batteries and do all sorts of measurements.

Your calculations are missing the essential issue: When you plug in the USB cable, the computer can supply a large amount of current (up to 500 mA) on the 5V bus. When you use your 7.5V battery pack, you're relying on the Arduino's tiny on-board regulator to supply power to the 5V bus, and it can't handle more than a few 10s of mA of external load before it overheats and shuts down.

@davetweed not true. The 5V reg could handle a few hundred mA, closer to 700 before issues, with a low VIN. The 3.3V reg is the weak one.

@cde: What you say may have been true for early Arduinos, but today's Arduino UNO only has a tiny SMT regulator with no heatsink.

@DaveTweed - the PCB itself is a non-trivial heatsink.  Especially given that the input is barely above the dropout voltage, thermal issues are probably not the problem.  Rather, most likely the battery pack is outputting a lower voltage than imagined and the regulator is in dropout.

As a general answer, yes. AA alkaline should be more around 2500~3000 mAh depending on quality. 5x AA in series would result in 7.5 Volts and 2500 mAh.
But that's only for almost fully charged batteries. AA batteries can range from 1.6V to 0.8V "dead for most purposes". As they drain, the voltage drops.
What may be happening is that you are powering the Arduino through its power jack, which goes through a diode, causing a 0.7V drop. Then it goes to the linear regulator which has a very high drop out voltage. Or even via the VIN pin, bypassing the diode. But as the battery drains, the voltage drops below the regulator ' s limit.
The Arduino microcontroller can easily work below 5V. The shield might not.

thank you for reply! I definitely use jack I will try going straight for VIN pin tomorrow is there a simple way I could put a connector on a jack to get positive and negative? So I won't have to cut off the connector?

@higeath there are plenty of pigtails on ebay. If I recall correctly, you need a 2.5mm female dc jack.

4xAA = 6.0V connected to a standard diode like 1n4001 = ~5.4V (within the specs for an AVR), connect directly to Vdd (+5V on arduino's). Unless there's a reason you need to use a 7.5V pack. Bypass the protection diode & Vreg = less wasted energy on heat/diode drops. IIRC, the WIFI/Ethernet shields can spike to 500mA or so, so that may also be causing extra drain. If your code constantly uses the WIFI radio, it will cause more current spikes as opposed to using the WIFI less in your code. Your avg current will decrease and battery life will go up. You'll save batteries by using 4 instead of 5 and not cause the 5V regulator to drop out and cause power issues by bypassing its input at Vin and connecting the 6V pack with a series diode to drop it to ~5.4V and connecting to +5V on an Arduino. It will also help with Vdrop when the WIFI has a current spike.
Also note that as any battery discharges, it's more of a slope than straight line and then dead, even for lithium packs. look at this link, good info for you to understand.
http://www.powerstream.com/AA-tests.htm


text:
EEPROM - Storing Static Data
I'm trying to store four items to EEPROM.  I can do one item no problem, I just don't know how to make the jump to multiple items.
My code:
#include <EEPROM.h>
char sgrpID[31] = "acpilot's arduino";
char addrID[51] = "123 any street rd";
char zpcdID[11] = "12345";
char gwayID[31] = "what a cool toy!";

void setup()
{
  Serial.begin(9600);
  for (int i = 0; i < 6; i++) {
    EEPROM.write(i, sgrpID[i]);
    EEPROM.write(i, addrID[i]);
    EEPROM.write(i, zpcdID[i]);
    EEPROM.write(i, gwayID[i]);
  }
}

void loop() {
  Serial.println(sgrpID);
  Serial.println(addrID);
  Serial.println(zpcdID);
  Serial.println(gwayID);
  delay(99999);
}

I want to be able to call on these in a sketch and post them to a db along with dynamic data of some flavor (TBD).
Am  on the right path?  Any help, corrections, or general guidance is appreciated.  I've moved beyond the "novice" stage of basic Arduino programming but an completely new to EEPROM.  If in doubt, SLOWER AND LOUDER is by far the best way to communicate key EEPROM concepts to me.
I have reviewed the Arduino EEPROM library but I was reading Greek.  I keep reading it and I'm sure at somepoint I'll recognize a pattrn and start to "get it."

Some things I noticed in your code:

You are writing everything to the same address (is that intentional?)
You are only writing the first 6 six bytes of your arrays (I am pretty sure that is intentional)
You are declaring these arrays to be bigger than what you are putting in them (this is again probably intentional, but I am just guessing)

So here is an example of how I would handle the eeprom:
#include <EEPROM.h>

char sgrpID[31] = "acpilot's arduino";
char addrID[51] = "123 any street rd";
char zpcdID[11] = "12345";
char gwayID[31] = "what a cool toy!";

//These are the definitions of what goes where in memory
//You do not want everything to have the same number
const size_t SGRP_ID_EE_START = (0);  //Zero is good address to start
//To get the next address we merely add the size of the first item
//With the address of the first item
const size_t ADDR_ID_EE_START = (sizeof(sgrpID) + SGRP_ID_EE_START);
//And so on and so forth
const size_t ZPCD_ID_EE_START = (sizeof(addrID) + ADDR_ID_EE_START);
const size_t GWAY_ID_EE_START = (sizeof(zpcdID) + ZPCD_ID_EE_START);

//Use this function to write a char array to the EEPROM at
//The address "address" (and the size of "len")
void WriteEepromArray(size_t address,char* arr,size_t len){
  for (size_t x = 0; x < len; x++){
    EEPROM.write(address+x,arr[x]);
  }
}
//Use this function to load your char array with values from
//The EEPROM
void LoadFromEeprom(size_t address,char* arr,size_t len){  //Be aware that this function modifys the data pointed to by "arr"
  for (size_t x = 0; x < len; x++){
    arr[x] = EEPROM.read(address+x);
  }
}

void setup()
{
  Serial.begin(9600);
  //Some sample writes
  //               starting address----array-----size of the array
  WriteEepromArray(SGRP_ID_EE_START   ,sgrpID   ,sizeof(sgrpID));
  WriteEepromArray(ADDR_ID_EE_START   ,addrID   ,sizeof(addrID));
  WriteEepromArray(ZPCD_ID_EE_START   ,zpcdID   ,sizeof(zpcdID));
  WriteEepromArray(GWAY_ID_EE_START   ,gwayID   ,sizeof(gwayID));
  //Use the following to load:
  LoadFromEeprom(SGRP_ID_EE_START,sgrpID,sizeof(sgrpID));
  Serial.println(sgrpID);   //Now it should be loaded

}

The comments I hope help....otherwise comment below with what I left out.

Answers to your bullets: no; that's an error, should be the length of the string, not just 6 bytes; yes, I'm allowing for longer names than what I'm using.
I follow the flow but some of the commands are new.  I don't know what this means, for example:
for (size_t x = 0; x < len; x++){
arr[x] = EEPROM.read(address+x);.
If I need to recall the "sgrpID", for example, and use it in a sketch do I simply use:
for (size_t x = 0; x < len; x++){
arr[x] = EEPROM.read(sgrpID+x);?

I've spent many hrs trying to get a Serial.println() out of this and i haven't a clue as to what I'm doing wrong.  Can you dumb it down more than you already have?  I'm doing something like "WriteEepromArray(size_t GWAY_ID_EE_START,char* gwayID,size_t len)"...with no luck.  I understand for the most part what's going on (or supposed to happen), I just can't make it spit a string back out.

@acpilot To read the eeprom do LoadFromEeprom(SGRP_ID_EE_START   ,sgrpID   ,sizeof(sgrpID));.  This will then cause the sgrpID array to be loaded with whatever was in the eeprom.  Try that.....if that doesn't work let me know......

@acpilot PS: If you were wondering what the size_t was all about.....that is just a type (like int or char) whose max value is the maximum size of an array.....so it makes sense to use that in a loop.....but in order to have a simpler view of it just imagine that it says int there.

Serial.println(LoadFromEeprom(GWAY_ID_EE_START,gwayID, sizeof(gwayID))); // generates "invalid use of void expression."  Evidently this means that the void, as I've written it, will not return a value.  Do you see an error?  I've been trying different things for a few hours...I promise that I'm not just fishing for a spoon fed answer.  I see where you're going and am trying to wrap my head around it.  Also tried defining "#define MemLoadGway = LoadFromEeprom(GWAY_ID_EE_START,gwayID, sizeof(gwayID));" and see a similar error: "in expansion of macro 'MemLoadGway' invalid use of void expression."

I also tried as a String(MemLoadGway); and String(LoadFromEeprom(GWAY_ID_EE_START,gwayID, sizeof(gwayID))); without success.

@acpilot Added an example of reading....hope that helps

I see.  I was going about it all wrong.  It works perfectly.  The new problem is the quantity of data being sent over WiFi causes and incomplete post to the db, but that's a topic for another post.  Thank you DarthRubik.  You condensed what would have taken me weeks into mere days.

@acpilot Glad I could help


text:
Possible Arduino Uno c++ compiler bug?
I recently gave the students in my Arduino-based programming class a project to write some simple unit tests and fix the bugs that they encountered as they did.  The class in question mostly stores a bunch of Arduino-style String objects, with various getters and setters and a couple of constructors.
The test code that they're supposed to write involved creating two instances of the class (on the stack) and verifying that the constructors set the values correctly.  When I went through the exercise myself, everything worked.
When the students repeated the exercise, the first object worked.  The second object returned empty strings.  If they commented out the first object, the second object began working.  I couldn't find any obvious mistakes that could explain these failures.
After staring at their code for about ten minutes to make sure I wasn't losing it, I compared Arduino IDE versions to make sure my machine was running the same version.  It was.
Next, I unplugged one of their Arduino Uno devices and plugged in my Mega 2560.  The exact same source code passed the unit tests as expected.  That means the test failures were caused by some subtle difference between the Arduino Uno and the Mega 2560—either in the hardware or in the compiler.
Before I file a bug against the Arduino Uno compiler (v1.6.7, though I don't see anything in the 1.6.8/1.6.9 release notes that imply any compiler changes since then), I wanted to make sure I wasn't missing something subtle.  Could somebody take a look at this and see if I missed anything?
I've included a condensed version of the class in question below (with irrelevant bits removed).  You can see the complete set of exercises at:
https://sites.google.com/a/cabrillo.edu/cs-11m/schedule/unit-testing-exercises
The tests failed unexpectedly after they added the second AddressBookEntry object.
Class Declaration (partial)
class AddressBookEntry {

  public:
    AddressBookEntry(void);
    AddressBookEntry(String title, String firstName,
                     String middleName, String lastName,
                     String suffix);

    String title(void);
    String firstName(void);

...

  private:
    String _title;      // Mr.
    String _firstName;  // Barack
    String _middleName; // Hussein
    String _lastName;   // Obama
    String _suffix;     // Sr.

    String _addressLine1; // The White House
    String _addressLine2; // 1600 Pennsylvania Ave.
    String _city;         // Washington
    String _state;        // DC
    String _zip;          // 20500
    String _plusFour;     // 0001   (from 20500-0001)

    String _homePhone;    // Unknown
    String _mobilePhone;  // Unknown
    String _workPhone;    // 202-456-1414

Implementation (partial)
#define assert(condition) { \
  if (!(condition)) { \
    Serial.print(__FILE__); \
    Serial.print(":"); \
    Serial.print(__LINE__); \
    Serial.println(": Assertion failed: " #condition); \
    while (1); \
  } \
}

bool AddressBookEntry::runTests(void)
{
  Serial.println("Running tests.\n"); Serial.flush();

  AddressBookEntry testEntry("Mr.", "Jim", "Bob", "Murphy", "Sr.");

  Serial.println(testEntry.title());
  Serial.flush();

  assert(testEntry.title() == "Mr.");
  assert(testEntry.firstName() == "Jim");
  assert(testEntry.middleName() == "Bob");
  assert(testEntry.lastName() == "Murphy");
  assert(testEntry.suffix() == "Sr.");
  testEntry.setMiddleName("Phil");
  assert(testEntry.middleName() == "Phil");

  AddressBookEntry obamaEntry("Mr.", "Barack", "Hussein", "Obama", "");

  assert(obamaEntry.title() == "Mr."); // fails
  assert(obamaEntry.firstName() == "Barack"); // fails
  assert(obamaEntry.middleName() == "Hussein"); // stopped checking here.
  assert(obamaEntry.lastName() == "Obama");
  assert(obamaEntry.suffix() == "");

  Serial.println("All tests passed.\n"); Serial.flush();
}

AddressBookEntry::AddressBookEntry()
{
  _title = "";
  _firstName = "";
  _middleName = "";
  _lastName = "";
  _suffix = "";

  _addressLine1 = "";
  _addressLine2 = "";
  _city = "";
  _state = "";
  _zip = -1; // Deliberate bug
  _plusFour = -1; // Deliberate bug

  _homePhone = "";
  _mobilePhone = "";
  _workPhone = "";
}

AddressBookEntry::AddressBookEntry(String title, String firstName,
                                   String middleName, String lastName,
                                   String suffix)
{
  _title = title;
  _firstName = firstName;
  _middleName = middleName;
  _lastName = lastName;
  _suffix = suffix;

  _addressLine1 = "";
  _addressLine2 = "";
  _city = "";
  _state = "";
  _zip = -1; // Deliberate bug
  _plusFour = -1; // Deliberate bug

  _homePhone = "";
  _mobilePhone = "";
  _workPhone = "";

String str = "";
  Serial.println(str + "title is \"" + title + "\"");
}

String AddressBookEntry::title()
{
  return _title;
}

String AddressBookEntry::firstName()
{
  return _firstName;
}

... // remaining getters are similar

Calling Code (from setup() function)
  Serial.begin(9600);
  AddressBookEntry myEntry;
  myEntry.runTests();

That's a lot of strings. Sounds like a lack of RAM to me.

I agree with @Majenko, the most likely culprit is RAM which is why it's compiling on the Mega, since it has much more RAM than the Uno.

This is really not an appropriate application for a tiny embedded system with only 2048 bytes of RAM and an inability to make ordinary access to constants stored in flash.

That means the test failures were caused by some subtle difference between the Arduino Uno and the Mega 2560—either in the hardware or in the compiler.

Not a subtle difference - a big difference.  The Mega2560 has considerably more RAM than the UNO (8kB compared to 2kB).
All those strings are using RAM. Lots of RAM.  Your Mega2560 has enough RAM to cope (just), but the UNO just dumps its stack in a heap all over the floor1 at the mere thought of trying to handle that quantity of string data.

1: That's a technical way of describing the stack and the heap meeting and, if there were no protection, colliding into each other.

That's certainly possible, but I would expect to get some sort of error if the String class tried to allocate memory and failed, rather than a silent misbehavior like this.

@dgatwood - how would you expect a tiny embedded system to communicate a runtime error?  Without an MMU, even detecting one requires extra code, nevermind that there's no established way to report the situation as it is not a safe assumption that "Serial" is "stderr".  This exercise is one you should probably have your students build to run on the development machines - save the embedded target for tasks that fit it, and contexts where you are prepared to keep the limitations constantly in mind.

You mean at the String class level, I assume, by detecting a NULL pointer exception.  I would have expected the code to die much sooner than that, the moment the heap allocator failed to find space.  That's usually considered a fatal error, and if the allocator is already detecting the error, it would make more sense to spew an error on the serial port and spin forever than to silently fail in unpredictable ways.  But maybe that's just because I'm used to kernel code, where if an allocator fails and is allowed to return NULL, somebody's disk is going to get wiped....

Okay, the more I study this, the more baffled I am by what I'm seeing.  if I add the following line to a function: String x = "Mr.";, the global variable space remains constant, as expected, but if I add this line: assert(obamaEntry.title() == "Mr."); in the same function, it adds 48 bytes to the global variable size, despite not adding any global variables.  Something is not right here.  At best, that should have constructed some temporary String objects on the stack, then immediately discarded them, but global storage shouldn't have changed at all.  Yet it did.  A lot.

Never mind.  I figured it out.  The strings in the assert macro were ballooning the global storage.  I wrapped them in F(), and suddenly my global storage shrank by more than 1k.  Ugh.  What an ugly hack to work around what should have been the default codegen behavior....

You should learn the difference between Harvard and Princeton architectures and why things like the F() macro are needed.

I fully understand the difference between the architectures.  I also understand that as long as it is possible for the compiler to support the F() macro, there can be no reason why the equivalent code couldn't automatically be generated by the compiler, rather than requiring additional decoration.  And there's similarly no reason that it can't be considerably more robust when done in that fashion.  The only argument against doing so is efficiency, which is why it would make sense to make that a compiler switch—optimizing between speed and time.


text:
Over voltage protection for Arduino
If an external voltage of 7 volts is applied to the external voltage input on the Arduino and the power from the USB port remains connected, is there a protective circuit that will protect the Arduino?  Thank you.

Protect it from what?

yes there is. power will be drained from external source(altough 7 volts is around the limit and arduino may switch to usb power) and arduino will still operate at 5v, same as usb. in any case your arduino and usb will be safe.

The opamp that turns off the mosfet, to disable USB-Vcc, is set to 6.6Volt.

glad to help. Generally speaking, if a given answer satisfies you then you should mark it as accepted. See also faq about accepting answers. Thank you


text:
Arduino SoftwareSerial - can't get data from NEO 6M-GPS module
I am using Mikael Hart's TinyGPS (v.13) library and example code to talk to my module. The LED on the GPS module is lit and flashing which I assume means it is receiving data from the GPS satellites. The module seller claims that the module has a default baud of 38400.
I'm pretty sure it's wired up correctly:

And my sketch says:
SoftwareSerial ss(4, 3);

So I read this as Orange (Rx) to pin 4 and Brown (Tx) to pin 3.
Any help appreciated

RX of the Arduino (pin 4, according to the SoftwareSerial statement) goes to the TX of the GPS.  Arduino pin 3 (ss TX) goes to the GPS RX.
And you should use pins 8 & 9 instead.  That would let you use AltSoftSerial, the best choice when you can't use HardwareSerial (i.e., Serial).
If you can't use pins 8 & 9, then NeoSWSerial is a better choice than SoftwareSerial.
And while I'm promoting NeoSWSerial, I'll mention a library I wrote, NeoGPS...  It's faster and smaller than all other GPS libraries, and very configurable.  It also has several diagnostic programs and a Troubleshooting section in the docs.

Thanks - I'll give it ago and report back. Your answer came a little after I'd put everything away for the day. . The chip specif library in particular sounds very useful.


text:
Connecting Arduino to internet through HC-06 and then smartphone
Can I use HC-06 to connect the Arduino to a smartphone (which I am already doing) and thereafter take the data to the internet?

Yes, but not in quite the way you think.
In this case the smartphone is acting exactly like the PC when you have the Arduino plugged in to it. You have a serial connection. Theoretically you can:

Send a request to the smartphone over the serial bluetooth connection
Write some software on the smartphone to interpret that request and perform some action depending on what the request is

That way the smartphone is then acting like an incredibly expensive and bulky ESP8266.

Is there an app that can perform this action for me like receiving the bluetooth serial data like 'blueterm' does and sends the data on some condition?

I am not aware of one. There may be one though. You will have to search Play.

old thread I know..
You can use MIT App Inventor to write/make an app for your Android phone.
This will do several things:

pair with your Arduino/BT device.
take data sent from the Arduino/BT device and parse it
do what you like with that data at that point, save to a database..etc. send info to a map (like google maps)..etc

You havent stated what you want to do with the data after it reaches the phone.
Alternately.. you may be able to get rid of the BT device.. and use an ESP8266 wi-fi module and connect directly to a 3rd party web script/service and dump the data directly to the 'internet'


text:
Current Arduino STL Libraries
I was going to update this question but I thought that this was different.
I have been trying to get std::vector to work with the latest Arduino. I have tried downloading several libraries found online but I can not get one of them to compile correctly. So here is my question, does anyone CURRENTLY know of a Arduino STL Library that is working?
StandardCplusplus: As stated above I tried to use this library but run into problems with the new/delete functions.
Andy Brown's AVR-STL Library doesn't even seem to come close to compiling.
If anyone has a working copy of these two I would love to have a copy or if you can tell me how to get them to compile. Otherwise I really need to find a way to get Vectors working, does anyone have any ideas?
Edit
I didn't want to answer this question so it is still active as I am sure there will be additions to this. Anyways I FINALLY got a library to work (for now, so far). I downloaded the StandardCplusplus library and found that in order to get any of the stl functions to work you have to add an include to the "StandardCplusplus.h" file before EVERY use, not just in the first file as stated in the Wiki on the Project page.
So I was able to get vectors to work using the following:
#include "StandardCplusplus.h"
#include <iterator>
#include <vector>

vector<int> test;

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

   test.push_back(1);
   test.push_back(2);
   test.push_back(3);
   test.push_back(4);
}

void loop(){
   for (int i = 0; i < test.size(); i++){
      Serial.println(test[i]);
   }
}

I would still like to know of other working STL Libraries as it seems that there are tons of outdated and old libraries out there.

I was wondering the same. At school, we once used the "GNU-GCC" toolchain to cross-compile for AVR targets.
We could use all fancy vector & queue things, but I'm uncertain if it required any additional steps (which I forgot).

You may try the original C++ libraries? They would be poorly optimized though, but I'm curious if they will perform reasonable. C++ should be portable to other platforms, though, microcontrollers do have their limits.

@Paul I really am not sure were to start trying to port the original libraries, I am pretty new to Arduino and AVR Programming and I am still feeling out the limitations. I do know however that other people have been successful in using vector and other STL functions. I just have to figure out how to do it repeatably. Another thing I noticed when using the above library I get intermittent compiler errors so I am thinking that there are still issues.

You are probably having a hard time finding good libraries because dynamic memory is rarely used on micro controllers with such small amounts of RAM

@BrettAM I realize that there are issues when dynamic memory is used incorrectly but at the same time they did have CAD systems on the old 286 processors and these AVR's are not too far from those ;-) I am not looking to run streams I am only looking for vectors

@AndyBraham. Those old 286 machines had MMU, multilevel interrupts, 1 MB addressable memory (DOS, real mode), DMA transfer, 16 bits registers, separate address and data buses and FPU (via co-processor).

I maintain an Arduino plugin that's a port of uClibc++ (just like the defunct StandardCplusplus library). It's available in the Arduino library manager for Arduino versions 1.6.10 and higher. It's called ArduinoSTL.

Thank you for the suggestion but I am running into a problem with your library. I simply tried to include the "ArduinoSTL.h" file into a blank sketch but I receive a error in iterator.cpp "The system cannot find the file specified.". Any idea what file might be missing from my setup? I am using Eclipse Neon

You must include it via Arduino's GUI Sketch -> Include Library -> ArduinoSTL. If it's not in the list you can install it from the built-in library mager: Sketch -> Include Library -> Manage Libraries...

Pity there's no C++11. Your <type_traits> header is lacking great many functions.

It's a pity it doesn't compile, at least with PlatformIO 5.0.2 and Atmel megaAVR 1.3.0.
I get an error that In file included from .pio/libdeps/nano_every/ArduinoSTL/src/ArduinoSTL.h:12:0,                  from .pio/libdeps/nano_every/ArduinoSTL/src/ArduinoSTL.cpp:1: .pio/libdeps/nano_every/ArduinoSTL/src/serstream:307:9: error: '::Stream' has not been declared

pay you attention which kind of arduino do you use. it can compile for Mega but not for Leonardo for example


text:
Arduino + WiFi 101 Gerber Files
Is it possible to get the Gerber files for the Arduino Uno r3 and the WiFi 101?  I've been teaching myself the SW side of this hobby (with much help from SE Arduino) and I'd like to better understand, or at least get some exposure to, the HW side.
Are the Arduino Uno and WiFi 101 Gerber files available to the general public or are they considered IP?  I am under the impression that it is open source but I'm not sure where the OS boundary ends.

On the Arduino UNO and Wifi shield websites in the Documentation section you can download the Schematic (PDF) and PCB layout (Eagle) files. The page already says

The Uno is open-source hardware! You can build your own board using
  the follwing files

With the free version of Eagle, you can open it and export to gerber file format.

Thank you for explaining it to me.  I'll take a look.  I did see Eagle files I just didn't know what they were.


text:
Arduino uno, 2x parallax continous servos (BOE), wifi shield power draw
I am unable to properly connect those things together with batteries:
Arduino Uno
Parallax continuous servo
Arduino wifi shield

5xAA batteries are connected through power jack to arduino which I assumed would power both arduino and the wifi shield and then I have 1 9 volt battery to power 2 servo motors.
With this setup it seems like I can only get to run 1 servo at a time.
Here is a picture how it looks like: https://i.stack.imgur.com/7mGKe.jpg
I'm really desperate for any advice/guidance when it comes to powering this thing.

9v is too high for servos and risks destroying them. 5x AA is not enough for an Arduino's input except when they are new.

9V batteries can only supply  very little current. So two servo's is too much.
Just use another set of multiple AA batteries for the servo's.


text:
How to implement an alternating current using only two PWM pins on STM32 Nucleo L053R8?
I am an arduino rookie and definitely not an expert in electronics, even if I do know the physics that is behind it.
Before burning my object of experience, I prefer to ask my silly question to the community.
Context :

I do use a bare stm32 based Nucleo L053R8 board which is arduino compatible.
I want a 1 minute long loop during which I send a 1.5V@20mA impulsion during 1 second and a -1.5V@20mA impulsion 30 seconds later.

Question :

can I simply use and wire two arduino PWM-able pins only to implement that alternating polarity low current? Or will it fail because of unsinked current?

A Nucleo board is not considered an "Arduino" within the meaning of this site - some of them have a physically compatible shield connector, but unless you are running fairly unsupported 3rd party software that you have neglected to mention, they are not software compatible with Arduino, which means your question is not on topic here.  Typically the native development environment for a Nucleo is mbed.

I agree. My Nucleo board is not a real Arduino board, not even fully compatible. By the way, my board has a physically similar shield connector. And yes, I do use mbed.

It's quite hard to understand what you want from your question, it's quite "woolly".
However, I will note:

It's not possible to output a negative voltage from a normal microcontroller.
Getting a specific voltage (accurately) from PWM requires good filter design and a feedback system to keep the voltage within bounds.

I say it's not possible to output a negative voltage - that is with respect to ground. Depending on what you are feeding this voltage into you may not need to reference to ground. In this case it is possible to reference the voltage to another IO pin (steady state, output, not PWM). With it set HIGH the PWM pin's filtered voltage will be below that IO pin's voltage and thus appear, with respect to that IO pin, to be negative.  With the IO pin LOW it will appear, with respect to that IO pin, to be positive.
Once you have filtered your PWM signal you will need the output voltage from it to be monitored by an analog input. That can measure the voltage and make sure that your PWM is set to the right duty cycle. Note that the required duty cycle for any one specific voltage will depend largely on the filtering and the load on the output at the time. You will most likely need some form of PID algorithm to constantly adjust the PWM duty cycle. Also remember that your measured voltage will always be with respect to groud, so you will need to subtract your output reference voltage (the output state of your reference IO pin - high or low) from your measured voltage to get the voltage as seen with respect to the IO pin.

The last 2 sentences in the 2nd paragraph are unclear and incomplete, i think: "With the IO pin (LOW?), it will appear..."


text:
Serial is freezing arduino
I'm using a LinkIt ONE Arduino-like to send sensor data via MQTT.
It always worked very well, then out of the blue, it stopped printing anything using Serial.print();
But if I ommit the "Serial.begin(9600);" line, the code runs normally, sending sensor data via MQTT, even if I can't see debug output.
This shows the problem is on the Serial handling.
Since I can't show the entire code here, here's two test cases:
1.
void setup(){
  Serial.begin(9600);
  Serial1.begin(9600);
  while(!Serial); //Wait until Serial is ready before printing
}

void loop() {
  Serial1.println("This came from serial 1"); //does nothing
  Serial.println("This came from serial 0");  //works
  delay(1000);
}

It shows me the following output:

This came from serial 0
This came from serial 0
Thi

Looks like the module freezes before the third iteration.
But if I omit the lines that aren't printed, from Serial1:
2.
void setup(){
  Serial.begin(9600);
  while(!Serial);  //Wait until Serial is ready before printing
}

void loop() {
  Serial.println("This came from serial 0");  //works
  delay(1000);
}

No output is shown on Serial monitor.
What is the reason behind this? Since Serial1 prints nothing, why can't I remove it?
Observations:
I tested the code in two LinkIt ONE modules of the same model.
I tested it in Arduino SDK 1.6.8, 1.5.6r2 and 1.6.5.
Edit:
Just made another test using the code below. It blinked two times showing that
Serial.begin(9600); runs
while(!Serial); runs (it didn't freeze the module waiting for Serial to initialize)
But Serial.println(); freezes
void setup(){
  pinMode(13, OUTPUT);
  blink();
  Serial.begin(9600);
  blink();
  while(!Serial); //Wait until Serial is ready before printing
}

void loop() {
  Serial.println("This came from serial 0");  //works
  blink();
  delay(1000);
}

void blink(){
  digitalWrite(13, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1000);               // wait for a second
  digitalWrite(13, LOW);    // turn the LED off by making the voltage LOW
  delay(1000);
}

If the test code you posted is truly failing, you either have some external problem, or you have an issue you need to take up with the vendor of this non-Arduino board.

@ChrisStratton I have another friend that has the same board and will make a test using the same code, this is extremely weird because I tested it in two different boards and 3 different versions of Arduino IDE. Anyway, I'll keep you posted.

@ChrisStratton I reinstalled arduino IDE from scratch on version 1.6.9 and installed the lastest firmware version available 1.1.21, from board manager, that solved the problem. Should I put this as an answer to my own question?

If the problem is solved, then by all means post an answer.

The problem was solved by:

making a clean install of Arduino IDE 1.6.9
uploading the LinkIt SDK on board manager from version 1.1.17 to 1.1.23.

Then the Serial function returned back to normal.

I have bit similar problem. I thing, this is arduino bug.
When start serial port, must be take out data from Rx. When read buffer overflow my arduino freeze. I can't run delay because when arduino wait, serial port can receive lot of data -> overflow -> freeze. Instead of delay I use own function wait(milis):
void wait(unsigned long wait_time){
  unsigned long start_time;
  start_time=millis();
  while ( millis() < (start_time+wait_time) ){
    if (serial.available() > 0) serial.read();
  }
}

Not true.  See http://arduino.stackexchange.com/questions/1726/how-does-the-arduino-handle-serial-buffer-overflow

This shows the problem is on the Serial handling.

The problem isn't actually in Serial, it's somewhere else.  Many things are able to make the Arduino hang in mid-write.  Show us the any code that you have written, plus links to the libraries you are using, and you'll have your answer in short order.
I will guess that you have a low-RAM condition, perhaps exacerbated by heap usage.  Do you use String?  I notice you're not using the F macro to save RAM.

You seem to be overlooking the fact that the code is not running on an Arduino.  It is running on an entirely different, marginally source compatible board with orders of magnitude more resources.  The F() macro exists in response to the ATmega's unusually pure Harvard architecture.

@ChrisStratton, Right, this board doesn't need F.  However, I will stand by the guess (low RAM) and the request for the whole program.  I hope you aren't suggesting that "more resources" keep him from using RAM poorly?  Or that his trivial excerpt contains the problem?  Seems like an XY question to me...

You really should look up how much ram the board has before you make such extremely unlikely guesses and then insist on "standing by" them - debugging is about facts and evidence not unfounded guesses.  Also keep in mind that we have code in the question that can allegedly cause the problem.

A made a test using the F macro, and it did not work. Then, I made another test using the following code:

Nevermind, I will edit the question.


text:
Use terminal command to verify software
I've seen that it is possible to use terminal command to verify software instead of using the IDE. Something like arduino --verify lab.ino.
Is there a way to do so on Mac OS?
Thank you

I managed to verify code from terminal by invoking /Applications/Arduino.app/Contents/MacOS/Arduino --verify lab.ino BUT this command automatically starts the IDE and exits it afterwards. Even with an IDE instance open it will start a new one. This is annoying since it will switch the active workspace away, but it kinda works. See arduino manpage.

Use AVRDude, and set the op field to v for verify. E.g.:
/Applications/Arduino.app/Contents/Java/hardware/tools/avr/bin/avrdude -C/Applications/Arduino.app/Contents/Java/hardware/tools/avr/etc/avrdude.conf -v -patmega328p -carduino -P/dev/cu.usbserial-A703114N -b57600 -D -Uflash:v:/var/folders/tp/grrlc56j3z7057f12_7f1_0r0000gn/T/build7a7055aab8d0564b6a7844b201562ffe.tmp/CV-turner.ino.hex:i

change /dev/cu.usbserial-A703114N to your serial port.
change /var/folders/tp/grrlc56j3z7057f12_7f1_0r0000gn/T/build7a7055aab8d0564b6a7844b201562ffe.tmp/CV-turner.ino.hex to your hex file.
More info on avrdude at http://www.nongnu.org/avrdude/user-manual/avrdude_4.html#Option-Descriptions
Sample output would be:
avrdude: Version 6.0.1, compiled on Apr 14 2015 at 16:30:25
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2009 Joerg Wunsch

         System wide configuration file is "/Applications/Arduino.app/Contents/Java/hardware/tools/avr/etc/avrdude.conf"
         User configuration file is "/Volumes/Lion-Data/home/.avrduderc"
         User configuration file does not exist or is not a regular file, skipping

         Using Port                    : /dev/cu.usbserial-A703114N
         Using Programmer              : arduino
         Overriding Baud Rate          : 57600
         AVR Part                      : ATmega328P
         Chip Erase delay              : 9000 us
         PAGEL                         : PD7
         BS2                           : PC2
         RESET disposition             : dedicated
         RETRY pulse                   : SCK
         serial program mode           : yes
         parallel program mode         : yes
         Timeout                       : 200
         StabDelay                     : 100
         CmdexeDelay                   : 25
         SyncLoops                     : 32
         ByteDelay                     : 0
         PollIndex                     : 3
         PollValue                     : 0x53
         Memory Detail                 :

                                  Block Poll               Page                       Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
           eeprom        65    20     4    0 no       1024    4      0  3600  3600 0xff 0xff
           flash         65     6   128    0 yes     32768  128    256  4500  4500 0xff 0xff
           lfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           hfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           efuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           lock           0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
           signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

         Programmer Type : Arduino
         Description     : Arduino
         Hardware Version: 2
         Firmware Version: 1.16
         Vtarget         : 0.0 V
         Varef           : 0.0 V
         Oscillator      : Off
         SCK period      : 0.1 us

avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.00s

avrdude: Device signature = 0x1e950f
avrdude: safemode: lfuse reads as 0
avrdude: safemode: hfuse reads as 0
avrdude: safemode: efuse reads as 0
avrdude: verifying flash memory against /var/folders/tp/grrlc56j3z7057f12_7f1_0r0000gn/T/build7a7055aab8d0564b6a7844b201562ffe.tmp/CV-turner.ino.hex:
avrdude: load data flash data from input file /var/folders/tp/grrlc56j3z7057f12_7f1_0r0000gn/T/build7a7055aab8d0564b6a7844b201562ffe.tmp/CV-turner.ino.hex:
avrdude: input file /var/folders/tp/grrlc56j3z7057f12_7f1_0r0000gn/T/build7a7055aab8d0564b6a7844b201562ffe.tmp/CV-turner.ino.hex contains 7902 bytes
avrdude: reading on-chip flash data:

Reading | ################################################## | 100% 3.34s

avrdude: verifying ...
avrdude: verification error, first mismatch at byte 0x0002
         0x64 != 0x6a
avrdude: verification error; content mismatch

avrdude: safemode: lfuse reads as 0
avrdude: safemode: hfuse reads as 0
avrdude: safemode: efuse reads as 0
avrdude: safemode: Fuses OK (H:00, E:00, L:00)

avrdude done.  Thank you.

Notice the verification error, first mismatch at byte 0x0002
PS. you need an actual hex file, not an ino file. Different compilers and different versions of the Arduino IDE can produce slightly different hex files, for the exact same C-program.

I'm not sure that's what he's after - I think he wants to "verify" (i.e., compile) his sketch from the command line.

@Gerben I am sorry but I dont have an arduino, I realy just want to verify my code. I am coding for a project and just want to commit verified code.


text:
Unable to reset arduino with RESET pin
I am using a custom built arduino UNO for some personal projects. I am using a custom optiboot bootloader given by Nick in this post. This was done to prevent the three LED flashes on digital pin 13.
I have noticed a weird thing with the setup. During normal operation, I am able to reset it by pulling the reset pin low. Sometimes, my microcontroller freezes due to noise and I am unable to reset it by pulling the reset pin low. However powering it off and back on still works.
I am wondering what could be a possible cause for this. Is it the custom bootloader or whether power on reset is different as compared to normal reset? Is there a way to ensure atmega328 always resetting through reset pin? Can noise affect the chip and make it behave in such a way?
After some google searches, I found an issue where people disable the reset pin functionality by setting a fuse but this doesn't seem to be that case because I am able to reset the chip during normal operations.
Updates and edits:
@Nick - Bootloader seems to be working fine. I have ruled out any issues due to the bootloader that you provided because I am having similar issues with original ones as well.
Custom arduino has all the necessary circuit elements - including reset pin pullup 10K resistor and 1N4148 protection diode. I am able to program and run the code without any trouble.
Sometimes, due to electromagnetic noise, the atmega locks up. GPIO doesn't work. Here is a separate question explaining this.
During tests, I leave the board running and wait for that hang-up to occur. During this time period, I deliberately try to induce noise in ac lines (by switching on/off appliances, turning the fan regulator knob etc). When it hangs up, I try to reset it by pulling the reset pin low using a wire. Sometimes it resets and sometimes it doesn't. When it doesn't, the only way out is to power it down and power it up back again.

Could you please clarify what you mean by freezing due to noise? Is it possible that this noise upsets more than your code (i.e. causes a brown-out condition that isn't checked for, corrupting the DDRB register or more)?

@sekdiy Brown-out levels have been raised to 2.7V and mcu is getting brownout reset on separate test and everything starts working as expected. I am not sure about DDRB register corruption. Can that thing disable RESET pin from functioning? And will a power cycle set the things straight?

Can you clarify if the bootloading isn't working, or if this affects the sketch running? That is, after you upload the sketch (say in the morning) and later in the day you have trouble resetting the board?

On your custom Uno (so it isn't really a Uno, eh?) do you have a pull-up resistor on /RESET? Also do you have a diode on /RESET?

@NickGammon - I updated the question to answer your questions.

@Whiskeyjack AFAIK the pin is not software driven.. Usually on other uC (e.g. PIC) you can set the reset pin function to off using the fuses. Are the fuses the same as the UNO ones? Moreover if you have these random freezes I suggest you to use the integrated watchdog, so you won't have to manually reset it

@frarugi87 - I tried internal WDT and it failed to reset during those freezes. As a last resort I was using another ESP module present on the same esp to keep checking whether arduino is alive or not and reset it whenever it freezes. In some cases it works but in others it doesn't because grounding the reset pin isn't helping anymore. I thought nothing will be as robust as resetting it externally using reset pin but now, only power cycle seems to be 100% reliable. Implementing power cycle is a difficult option.

@Whiskeyjack sorry, but.. Where does the ESP come from? You never mentioned it...

Weird problem. Why don't you use the reset-button, by the way? I've had wires in the headers not properly making contact in the past. But why don't try to fix the source of the problem; i.e. the power source. Try using a different AC-power adapter.

@frarugi87 - Sorry, I didn't mention it because I felt it shouldn't affect the scenario. The issue is simple - I am pulling reset pin LOW but I am not able to reset the atmega328p.

@gerben - I tried it with another power supply. Faced the same issue.

A possible thing is that a high voltage on /RESET is putting it into high-voltage programming mode, however the diode I mentioned, and that you say you are using, should prevent that. Perhaps if you posted the schematic for your custom design.


text:
Opening webpage using ESP8266 in Arduino
I am trying to open the webpage in ESP8266 via Arduino Mega.
I have successfully opened the webpage if I use the AT command in the Serial Monitor
The output is perfect
+IPD,382:HTTP/1.1 200 OK
Server: nginx
Date: Sun, 08 May 2016 06:44:47 GMT
Content-Type: text/html
Connection: close
Vary: Accept-Encoding
X-Powered-By: PHP/5.5.26
Set-Cookie: PHPSESSID=rnsmo0b4kq07c5mi3mdsu280g4; path=/
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Pragma: no-cache

S|R190|W5|O31.0|T0|A24|CLOSED

As you can see the output is fine.
Now If I issue commands using Arduino Serial1.print() and read the output using following code:
 while( Serial1.available() )
 {
     inChar = Serial1.read();
     Serial.write(inChar);
     //delay(1);         //could play around with this value if buffer overflows are occuring
 } // while

The output skips character randomly
+IPD,386:HTTP/1.1 200 OK
Server: nginx
Date: Tue, 17 May wed-y: HP/.5.26
SetCooie:PHPESSD=7kameos5kd7aqcn4e54; pth=
Epirs: hu, 19Nov198 0852:0 GT
ach-Cotro: n-stre,no-ach, mst-evaidate,pos-chck=, pe-ceck0
raga: o-cche
F~SR19|W5O310|T90|ENDLOSD

I have tried different values of delay() but of no help.
My baudrate is 9600 for both arduino Serial and ESP8266 Serial1
Can you please tell me what can be the reason.
Thanks

Can you share with us the At commands to access a web page ?

First things first: never use a delay when reading from serial.
You are just blindly trying to read data and send it out to another port. That's not going to work unless you know how much data you need to read.
And that information is handed to you on a plate - you just need to interpret it.
You are required to read the serial data as it comes in and decide what it means, then do different things depending on that data.  For instance, when you read the characters +IPD you know you have an IP Data response to be interpreted.  Just after that comes a comma, and following that a number. That number is how many bytes you then have to read to get your data. So you keep looking and reading until you have received all the data you should be receiving.

If you notice the output does contain END This is the flag that shows that entire response has been read. The problem is that data is being skipped in middle randomly. Cache-Control is read like ach-Cotro with skipped characters.

My guess is it's something happening outside your while loop. That loop won't read the whole of the output - it will just read snippets as they become available, and other things in your program that may consume serial bytes are getting in the way. Follow my instructions and read the output properly.

I changed the code like you said and it is working fine. I think Serial.print() is coming in way of reading Serial1.read() I first read output in array and then print and it shows fine.

authors: ابو زهراء العراقي


text:
Cannot connect device with nRF8001 Bluetooth LE to Windows 10 PC
I've built a device using an IMUduino board, which is supposed to be similar to Arduino Leonardo board with a nRF8001 bluetooth. I was able to connect my device to an Android phone using the nRF UART v2.0 app, I tested some examples and it worked with success.
I would like to connect the device to a Windows 10 PC via bluetooth. I have installed the driver of the nRF8001, and I am able to pair both PC-UART. However, when I open the Master control Panel, I cannot find any Master emulator, the menu is empty. Master control panel version is 3.10.0.14.
Is there any way to connect a device with nRF8001 to a Windows 10 PC?
Thanks.


text:
Find remote ip address TCP
Found this "Remote IP of TCP Socket" at:
https://e2e.ti.com/support/wireless_connectivity/simplelink_wifi_cc3000/f/851/t/380635
I am trying to log the remote ip address of a client.  Using Ethernet, I have accomplished remote ip address logging.  Trying to do the same with the Adafruit CC3000 library.
Answer provided; does not respond every time with the correct "client.IP". When it is wrong; client.IP is always "client.IP: 0.0.0.0.0" which occurs more frequently than the correct "client.IP" of my computer.  Why is does this happen?  Is there a solution?   Answer is on the right track; need additional help, so client.IP is correct every time.
Edit:  File modified is Adafruit_CC3000_Server.cpp  Only change was to the clientIndex value.  Will this cause an impact on client connecting?  File is contained in "Arduino Stack Exchange.zip" linked in this post and is located in the Adafruit_CC3000 folder of the zip.  Changes are commented.
Modified files with client ip  returned.  https://drive.google.com/open?id=0Byo8QWKyqAT9TUt4d0FteENQS2s CC3000.zip
William

As a guess one of three things may be happening: you are trying to get an address without a valid connection, the address was never saved, or it was saved but overwritten before you try to obtain it.  You may need to figure out how to instrument or debug the code to determine which.

I found that if I set clientIndex = 2; every time I get correct client ip address.  Are there any adverse effects to setting clientIndex  equal to 2?  What happens to other clientIndex values?

Where exactly did you make this change?

This function is not built-in so you'll have to modify the library slightly. This is one way to do it, I think:

Navigate to the class Adafruit_CC3000_ClientRef in the file Adafruit_CC3000_Server.h. In the class definition, just before the private methods and attributes are defined, you will add a new public attribute as follows:
uint8_t ip_addr[4];  // assuming a typical IPv4 address

It will hold the IP address of each ClientRef instance as the connection is accepted.
Go to Adafruit_CC3000_Server::acceptNewConnections() near the end of Adafruit_CC3000_Server.cpp. A few lines will be added to get the IP address from the CC3000 and store it temporarily in the appropriate struct:
static sockaddr tSocketClientAddr;  // file scope
static socklen_t addr_len;

// Accept new connections and update the connected clients.
bool Adafruit_CC3000_Server::acceptNewConnections() {
  bool newClientCreated = false;
  // For any unconnected client, see if new connections are pending and accept
  // them as a new client.
  for (int i = 0; i < MAX_SERVER_CLIENTS; ++i) {
    if (!_clients[i].connected()) {
      // Note: Because the non-blocking option was set for the listening
      // socket this call will not block and instead return SOC_IN_PROGRESS (-2)
      // if there are no pending client connections. Also, the address of the
      // connected client is not needed, so those parameters are set to NULL.
      cc3k_int_poll();
      addr_len = sizeof(tSocketClientAddr);
      int soc = accept(_listenSocket, &tSocketClientAddr, &addr_len);
      if (soc > -1) {
        _clients[i] = Adafruit_CC3000_Client(soc);
        newClientCreated = true;
      }
      // else either there were no sockets to accept or an error occured.
    }
  }
  return newClientCreated;
}

You'll also edit the getClientRef() method in Adafruit_CC3000_Server.cpp:
Adafruit_CC3000_ClientRef Adafruit_CC3000_Server::getClientRef(int8_t clientIndex) {
  if (clientIndex != -1) {
    Adafruit_CC3000_ClientRef newClient =  Adafruit_CC3000_ClientRef(&_clients[clientIndex]);
    // at least 2 (family) + 2 (port) + 4 (ip_addr) bytes expected
    // also check if address is standard ipv4
    if ((addr_len >= 8) && (tSocketClientAddr.sa_family == AF_INET)){
       // copy address into array; in network byte order
       memcpy(newClient.ip_addr, &(tSocketClientAddr.sa_data[2]), 4);
    }
    return newClient;
  }

  // Couldn't find a client ready to read, so return a client that is not
  // connected to signal no clients are available for reading (convention
  // used by the Ethernet library).
  return Adafruit_CC3000_ClientRef(NULL);
}

Save all the files.
Now the address is stored in an array for each client and can be accessed from your sketch. For example, you can access the address in your sketch like this:
In the loop() of the the HttpServer example:
 Adafruit_CC3000_ClientRef client = httpServer.available();
 if (client) {
   Serial.println(F("Client connected."));
   for (int i = 0; i < 3; i++){
     Serial.print(client.ip_addr[i]);
     Serial.print('.');
   }
   Serial.println(client.ip_addr[3]);
   // other code
 }

Completely untested. Good luck.

Comments are not for extended discussion; this conversation has been moved to chat.

@NickGammon by moving the followup you have basically broken this question and answer - it doesn't work, but the history to understand it isn't here either, which breaks the whole everything should be right here, not in external references spirit of stack exchange.

@ChrisStratton - what are you talking about? What followup? You mean the comments?

Yes the comments, which are the way people are supposed to respond to answers that almost but not completely work.  How else would this question be resolved - start over from scratch with no benefit from the effort already expended?  Just give up and close it?

The "effort already expended" is safely archived in chat, @ChrisStratton. See the link Nick posted above. If you care to refer to it when editing this answer or posting your own, you'll find it readily accessible.


text:
Can this Motor shield support other arduino functions?
http://www.flipkart.com/grab-em-l293d-motor-driver-arduino-shield/p/itmehvzzpzj4wyby?pid=ETYEHVZZFFHRFMFG
I want to ask whether this shield will allow me to use the free pins of arduino for other functions?

Anything that's not connected to something on the shield can be wired to something else of your choice. The trick, though, is to know what is connected to where on the board. Is there a schematic?

@Majenko Schematic is what I was searching for but I could not find any, all i could dig up is this page,

Then all you can do is buy one and inspect it closely and follow tracks around. It looks to use a shift register it its core, so will be using very few pins.

@Majenko Alright thanks, the only problem is I have already spent 90 percent of my pocket money, so I wanted to double check anyways thanks, I shall order it

As Majenko said, most pins probably aren't used. The only problem is to access the unused pins. As the shield goes into the female headers on the UNO, those are no longer accessible. Looking at the board, they only added some throughholes for pins A0-A5.

@Gerben I got the shield delivered and actually it came with female header seaters on the top which can make it stackable. Thanks for the help though

Yes, this motor shield can allow other components to be used. You just have to make sure that the pins being used by the shield are not used by you for other tasks. Generally all shields are designed such that they do not hamper the productivity of arduino. What use would only a motor driver be? Therefore they ensure that they do not block other pins.


text:
Arduino IDE unable to see serial connection on OS X El Capitan
For some reason the Arduino IDE is unable to see my Arduino Uno even though it is connected. I have reinstalled the Arduino software, but no luck come of it. I connected the Arduino to my friends mac, who's could see it.. I am very confused and greatly appreciate any help.

Thanks,
Shaun

I ran into a similar problem years ago on an ATMega128 (before Arduino) and you just have to be aware of alternative functions for the port. In this case PD0 is Hardware Serial RX which is a receive pin.
Here's some relatively older code based around the same idea:

Yes, you can use the RX/TX pins as regular IO. Just don't call the Serial.begin() in your code, and make sure you call a pinMode() for them.

from: http://www.societyofrobots.com/robotforum/index.php?PHPSESSID=b928292f91c78b57b5683484af0f635e&topic=12396.msg93239#msg93239
Another interesting post, fourth post: http://www.nerdkits.com/forum/thread/536/
where they disable the serial functionality once the code begins, downside (a above) you will lose serial comms, so it depends on how much you need them.
UCSR0B = 0;

I'm not sure how successful that would be in today's arduino, I know a lot (if not all) of the prior functionality is maintained, but I haven't used them in a long while.
The pin should become active again as the bootloader will automatically reenable it upon reset (although I haven't personally tested it). It will just make debugging that little bit harder if you need to.
As I mentioned in my comment, if you have another pin available to you, use that instead.

In case someone else has this problem..
Turns out, you can't be connect to pin D0 whilst using serial.

That's not entirely true, but in essence you're on the mark. May I suggest you have a read of the data sheet of the ship you're using. An aptly placed pull up/down resistor (I can't remember which off the top of my head) and using the pin in a particular orientation will also be 'ok'. A lot of external boards use jumpers for this exact reason to a) enable the pin to e used for serial programing/connection yet b) also used within the project. If you have another pin available for ease of use, yes, use that. But do and try and make your answers more complete


text:
Program around this while loop not working as expected
int i=0;
while(i == 0){
  if(digitalRead(saveSwitch) == HIGH){
    Serial.print("New coordinates saved \n");
    lat1 = gps.location.lat();
    Serial.print("Latitude");
    Serial.println(lat1);

    lng1 = gps.location.lng();
    Serial.print("Longitude");
    Serial.println(lng1);
    i = 1;
  }
}

Why isn't leaving the while loop?

Is it ever triggering the if() and printing?  If it is, what's outside this code? and does it dump it right back into the while(){}?   Maybe put a Serial.println() after the while(){} to prove you aren't misdiagnosing the unseen code.

I've printed the value of i and it's 1 after my switch goes high. I even used i++; to see if it increases, but it only increases once and after that it just prints out the lat and lng every time the switch goes high. Edit: nothing outside the while loop gets executed after i is set to 1.

Then it is getting out of the while loop.  Your problem is in the unseen, surrounding code.

All right, I'll look into the whole code and tell you what I find by tomorrow.

If you want i to maintain its state outside of the posted code, perhaps you should move the i=0; statement outside of its current scope.

Is that code from the loop() function? How many lines is the whole function? Can you add them all if it's beyond 100 lines?

Why isn't leaving the while loop?

There's a good chance that the code is  leaving the while loop, repeatedly.  However, if the code that's shown is in (eg) the loop() function, i will be reset to 0 each time the function runs, which will cause the while loop to start again.
As noted in Dave X's comment, you can move int i=0; to a higher scope. Moving it to file scope, for example, will allow it to retain its value through repeated function calls.  For example, if the code shown is in loop(), you could put int i=0; just before void loop() {.
Note, having generically-named variables like i declared at a high level is a bad idea, a blunder, a programming faux pas.  An alternative is to leave its declaration within loop() but add the static keyword so that i is allocated only once, rather than being reallocated and reinitialized at each execution of loop().  For example:  static int i=0;.

Instead of setting i=1, you could use a 'break' command to break out of the while loop.  That way you don't need 'i' at all, you can just do 'while(true)'


text:
Connector for I2C sensor
Im about to develop some home automation. It should be possible to connect new sensors to the main computer. Thats a Arduino.
What can be used as a connector for the I2C sensors? It should be customer friendly. So something like RJ11 or USB. What can be used for that?
Is it possible to send data wirelessly from a I2C sensor?
Regards

What can be used as a connector for the I2C sensors? It should be customer friendly. So something like RJ11 or USB. What can be used for that?

Almost anything you like. Whatever is easy to get hold of and use. You only need 4 wires, and they are all low voltage, so nothing too fancy is needed.

Is it possible to send data wirelessly from a I2C sensor?

No. But you can connect the I2C sensor to an Arduino then use that with a wireless interface of some form to send the data wirelessly.
One thing for you to know though:
I2C is not suitable for long distance communications. A few inches to a foot or so is about the limit. Anything longer and you will start running into communication problems. For longer distance communications you need to use a more reliable protocol.

Thanks a lot Majenko.
So i could use USB or RJ11? And would that work only work with a very short cable? So no 4m cable?
If i go for wireless, would i then be able to use like a Arduino Nano?

You could use those connectors if you choose, yes. But no 4m is not really on for I2C. Yes, you could use an Arduino Nano.

If i should find sensors that could be used with 4m of cable, what kind of sensors type is that?

Probably expensive and specialised. Most sensors are designed to be interfaced with something close by - often within the same circuit board or one closely connected. Normally you would take a sensor, add a small microcontroller, and some kind of transceiver (radio, RS-485, whatever) to transfer the data over a long distance. It's not the role of the sensor to do that sort of thing.

So i guess the easiest way is to make it wirelessly :-)
Thanks a lot for the help


text:
Arduino Pro mini to CH340G Connection problem
I have worked with Arduino UNO but recently I bought a new Arduino Pro mini 5v 16M and a CH340G converter to work with. I have searched google to connect pins but I found examples that explains this way :
GND to GND
VCC to VCC
Converter RDX to Arduino Pro Mini TXO
Converter TDX to Arduino Pro Mini RXI
My problem is that my Arduino Pro Mini (328p) has pins TXD and RXD (not RXI , not TXO) or maybe I have no knowledge about TX,RX, IN and OUT.
Can someone please help me to connect these wires?

Generally, lines with names like TX, TXO, and TDX are for serial-data transmit, and  lines with names like RX, RXI, and RDX are for serial-data receive.
Connect transmit on the CH340G board to receive on the Pro Mini, and vice versa.
For typical serial-converter programmers (I don't know specifically about the CH340) you need to connect CTS (Clear to Send, if the programmer has it) to the pin next to BLK on the Pro Mini, and RTS to GRN (DTR).  The RTS-to-DTR (Request to Send, Data Terminal Ready) connection lets the programmer auto-reset the Pro Mini to start programming.
See yourduino.com's ProMiniPinout.png diagram.

Thank you very much for this detailed answer. RTS-to-DTR connection helped me so much :)

try reversing the tx/rx lines, if the PRO Mini and serial adapter are chinese, you may want to try using your UNO as ISP programmer. See here for a hint/ex:
https://www.arduino.cc/en/Tutorial/ArduinoISP


text:
How do I use Microduino (mCookie) on Linux?
I'm interested in getting the mCookie working in Linux — specifically, in Fedora 23. The Arduino IDE (version 1.6.4) is already available. I'm very familiar with Linux, fine with C, and completely new to Arduino.
The tutorials for Windows or Mac describe installing a customized version of the IDE along with drivers. Do I need special drivers on Linux? On the projects' GitHub site, I found the examples and a directory called 'avr' which has promising subdirectories like "bootloaders" and "libraries", along with files boards.txt and platform.txt.
Can I download this stuff and add it to the existing "system" arduino package somehow? How, and what will I need?

I'd tag this [tag:mcookie] and/or [tag:microduino] if I could....

First you will need the arduino 1.6.x package from updates, not the 1.0.x package from fedora. Then:

You will be adding a URL to the new Additional Boards Manager URLs option: https://github.com/wasdpkj/Microduino-IDE-Support/raw/master/package_Microduino_index.json

source
This tutorial tells you where and how to add that URL to the preferences, as well as how to actually install the required support files.

As of this writing, the platform configuration supplied as part of the above won't work out of the box in Linux; you will also have to edit ~/.arduino15/packages/Microduino/hardware/avr/1.6.7/platform.txt to:

replace compiler.path={runtime.tools.avr-gcc.path}/bin/ with just compiler.path=/usr/bin/
on the line starting recipe.ar.pattern=, change {archive_file_path} to {build.path}/{archive_file}

Hopefully this will be fixed in future versions.

You probably also want to prevent ModemManager from probing the serial device with this udev rule, just replace the vendor and product IDs as appropriate:
SUBSYSTEM=="usb-serial", ATTRS{idVendor}=="xxxx", ATTRS{idProduct}=="xxxx", ENV{ID_MM_DEVICE_IGNORE}="1"

Nice, thanks! This resulted in an error: Could not find boards.txt in /home/mattdm/.arduino15/packages/Microduino/hardware/avr/1.6.7. Is it pre-1.5? and exit on startup. However, when looking at that directory, there's an avr subdirectory with boards.txt in; I moved everything up one level and now it seems to be working....

@mattdm: That would seem to be a problem with their files; I also see all boards.txt files (on my system) directly in the architecture-appropriate directories rather than in any subdirectories.

I guess I'll file a bug report.

Ugh, that also hardcodes compiler.path={runtime.tools.avr-gcc.path}/bin/ in ./packages/Microduino/hardware/avr/1.6.7/platform.txt, when it should be (I think) just compiler.path=/usr/bin/ ... fixed that, and now I've got an error about {archive_file_path}. I've got some further research to do here, I see.

So, from here, that should be replaced with {build.path}/{archive_file}. Now a really simple sketch compiles but does not seem to actually upload. That's the next step, I guess. :)

Whoo. Final step was "bad USB cable replaced". :)


text:
How to serve multiple connections with an ESP8266 and an Adruino?
I want to make a server using an ESP8266 (12e) and an Arduino Nano.
I have got everything hooked and I created a minimal "Hello World" example, based on a number of samples found on the web, which is working fine... as long as the ESP does not receive multiple requests simultaneously.
I am using SoftwareSerial on pins 8 and 9 of my Arduino Nano.
As long as I send one request at the time, things work fine.
If I use two browsers and send two requests with little interval, things go wrong, and that figures: the sendData() method just reads from the serial connection. It will consume the new request while waiting for an "OK" from the initial request...
Is there any sample code or library (for ESP + Arduino (nano)) that can handle correctly multiple concurrent connections?
Thanks
My code:
/*
  Software serial multple serial test
 */
#include <SoftwareSerial.h>

#define DEBUG true

SoftwareSerial esp8266(8, 9); // RX, TX

void setup() {

  Serial.begin(9600);
  esp8266.begin(9600); // your esp's baud rate might be different : 115200

  Serial.println("Setup...");

  /*
  sendData("AT+RST\r\n",2000,DEBUG); // reset module
  sendData("AT+GMR\r\n",1000,DEBUG); // get version
  sendData("AT+CWMODE=2\r\n",1000,DEBUG); // configure as access point
  sendData("AT+CIFSR\r\n",1000,DEBUG); // get ip address
  sendData("AT+CIPMUX=1\r\n",1000,DEBUG); // configure for multiple connections
  sendData("AT+CIPSERVER=1,80\r\n",1000,DEBUG); // turn on server on port 80
  */

  sendData("AT+RST\r\n", 2000,DEBUG);
  sendData("AT+GMR\r\n", 1000, DEBUG);

  sendData("AT+CWMODE=1\r\n",1000,DEBUG); // configure as station
  sendData("AT+CWJAP=\"******\",\"*******\"\r\n", 6000, DEBUG);
  sendData("AT+CIFSR\r\n",1000,DEBUG); // get ip address
  sendData("AT+CIPMUX=1\r\n",1000,DEBUG); // configure for multiple connections
  sendData("AT+CIPSERVER=1,80\r\n",1000,DEBUG); // turn on server on port 80

  Serial.println("Setup ready.");
}

//WIRE RESET TO HIGH!!?

void loop() { // run over and over

if(esp8266.available()) // check if the esp is sending a message
  {

    if(esp8266.find("+IPD,"))
    {
     delay(1000);

     int connectionId = esp8266.read()-48; // subtract 48 because the read() function returns
                                           // the ASCII decimal value and 0 (the first decimal number) starts at 48

     String webpage = "
Hello World!
";

     String cipSend = "AT+CIPSEND=";
     cipSend += connectionId;
     cipSend += ",";
     cipSend +=webpage.length();
     cipSend +="\r\n";

     sendData(cipSend,1000,DEBUG);
     sendData(webpage,1000,DEBUG);

     String closeCommand = "AT+CIPCLOSE=";
     closeCommand+= connectionId; // append connection id
     closeCommand+="\r\n";

     sendData(closeCommand,250,DEBUG);
    }
  }

}

String sendData(String command, const int timeout, boolean debug)
{
    String response = "?";
    int pos = -5;

    Serial.println("--------------");
    Serial.println(" sending "+command);

    esp8266.print(command); // send the read character to the esp8266

    long int _timeout = timeout + millis();

    while( (_timeout) > millis())
    {
      while(esp8266.available())
      {
        // The esp has data so display its output to the serial window
        char c = esp8266.read(); // read the next character.
        response+=c;
        pos+=1;
        if(pos>=0 && response.substring(pos) == "\r\nOK\r\n"){
          //WE GOT OK -> stop waiting
          _timeout=0;
        }
      }
    }

    if(debug)
    {
      Serial.println(" response: "+response);
    }

    return response;
}

NodeMCU can be an alternative. All in one package: WiFi, faster CPU, lots of RAM.

I might not have understood what you are trying to do, but if it is to use the ESP8266 to allow the Nano to connect to WIFI and act as a web server then I believe you are doing this the hard way.
The ESP8266 is an 80 or 160MHz microprocessor with 64KB Program Ram + 96KB data RAM.  You are using a 16/32MHz microprocessor to generate pages and pass them to it.  I would recommend that you investigate using the Arduino IDE to program the ESP8266 in "Arduino C" it comes with a set of examples that include webservers (which is what I think you are trying to do).  Keep the Nano if the ESP8266s 10 digital and one analogue ports aren't enough to interface to you hardware.

I will need more than one analog input... Could I still use the ESP module as "master", as "Server" and query the Arduino's analog ports over serial connection?

@mvermand if your case allows to read in the analog values one by one (not parallel), you could just use a multiplexer to achieve this - I just did that using an ESP and the HCF4051 - you need 3 control pins to address one of the 8 channels, and then open that to the ESPs ADC. Works just fine and stable.

the esp8266 certainly doesn't have 4 MB of RAM, the highest amount of free RAM I've seen was around 40 kB.

@MightyPork - Quoted the wrong number, corrected it now, but its still more than an Arduino Uno.

I had the same experience. When you send data by an AT command and receive something from another connection at the same time, then the ESP chip starts to behave unexpectedly. Sometimes it sends the data but does not respond with OK. Sometimes it does not send. And sometimes it ignores received data (missing +IPD message).
The AT firmware works only well with single telnet-style connections. I mean half-duplex communication where it never happens that more than one sender is "talking" at the same time.
I hoped that this issue becomes solved over time, but the modules that I bought recently (with AT Firmware 1.4) are still not better. However, I did not notice any unexpected auto-reset or hangup anymore in my 2-Week test loop. At least that became better.

The issue has been solved since SDK 1.5.4, which is used by the Arduino ESP8266 core version 2.3.0.


text:
Arduino shuts off and doesn't turn on after couple hours
I use a mega 2560, pir sensor and a SG90 9g Servo motor in my project. Basically while the pir outputs high, the Servo Motor rotates from 0 to 180 degrees.
Here is how everything is wired up:
PIR sensor:
Data: pin 24
Vcc: 5 volt
Gnd: Ground
Servo:
PWM pin: pin 11
Vcc: 5 volt
Ground: ground
The arduino mega has two 5 volt and ground pins, one next to the analog pins and other at tho bottom bar of pin, where pins 22 and up are. I connected the Servo to the first 5v and gnd and the pir to the second.
My power source is my nexus 5 charger(5v 1.8 or 2 A).
My code:
Servo myservo;

    void setup() {
      myservo.attach(11);
     pinMode(24, INPUT);
    }

    void loop() {
     if(digitalRead(24) == HIGH){
       myservo.write(0);
       delay(500);
       myservo.write(180);
       delay(500);
     }
    }

All of this works fine for the first ~10 hours. After that the arduino just shuts down. The power led of the arduino isn't lit up. Disconnecting the adapter and reconnecting it or pressing the reset button of the arduino doesn't work.  I Have to wait for a couple of minutes with the adapter disconnected and reconnect it. After that it works fine for the next ~10 hours.
Seems like a hardware issue, but I'm not sure what exactly fails and why.

You should not route power for the servo through the Arduino.  It needs its own connection to a supply capable of handling its stall current, which may well exceed an ampere.

I assume your charger is connecting to the USB port of the Mega2560.
That USB port has a polyfuse (actually a special type of positive-coefficient thermistor) which is normally rated at around 500mA (polyfuses are a bit woolly with their ratings since they are heat based).
If you are drawing near that limit of current the fuse will be gradually heating up. I would think that after 10 hours it may have reached its threshold temperature and thus switches the power off.
Disconnecting the power and allowing it to cool down would then make the board work again.
How can you test it?  Well, next time it switches itself off try bypassing the polyfuse (tweezers would be good to do that with) to see if the power LED turns on again.

Yes, it's connected to the usb port. The polyfuse indeed seems like a logical place to look for the issue. I will try your suggestion. Thanks.

The power led of the arduino isn't lit up.
The power LED is implemented in hardware, basically, if it's not lit, it won't work.
Find the problems' (power?)source
After the 10h operation, your Arduino isn't on anymore.
Does the power supply still have 5V available at that point? Or does your Arduino's chips get hot or short-circuit the supply?
Exclude as much variables as possible
You don't know what the problem is, it could be:

The supply
The Arduino
The Servo
The PIR

Try another supply (preferably through the barrel jack, since it's regulated) (The supply may have some "protection" to avoid it being on too long).
Try another Arduino (unlikely?).
Try no servo & pir connected. (They may draw too much current, so the Arduino shuts down or create electrical noise.)

Yes, I'm trying out a new supply now, the difficulty with finding the problem is that every time I change something, I have to wait for 10 hours to see if there is difference :(.  The arduino doesn't get hot, I tested that.

@MeesterPatat, atleast you can do something else in that 10 hours ;)
But yeah, welcome to the world of testing ;D It might be a good idea to make "test cases" or atleast think very well of what you're going to test, what the result should be and why ;)

I'm just going to hazard a guess: Your 5v line isn't staying at 5v because of the servo. They draw massive amounts of power quickly, and can wreck a lot of havoc. Many times electronics "kinda" work after voltage drops, but will lock up or glitch eventually.  (To get confirmation that this is the problem, monitor your 5v power with an oscilloscope. Set a trigger at 4.5v and try to capture the voltage drops.)
If that is the problem, you need better isolation on your digital power (running the arduino) and your analog power (running the servo.)  Two ideas to try (you may need both):
1)  Get a big cap (say 100 uF or more), then put it across your power to the arduino. If it's big enough, it will prevent your 5v from sagging. It may be expensive to get a big enough cap.
2) Instead of connecting your servo directly to 5v, put a small resistor (say 10 ohm) between them.  Now when he tries to suck all the power, it will get resistance, which will limit the current. The bigger the resistor the better the isolation, but too big will prevent your servo from working. (And may heat up your resistor).


text:
How to convert voltage to current from ACS712-20A?
I've been used the ACS712-20A to measure the current flow. Actually I used LIFA program (LabVIEW interface for Arduino).
I used this equation:
current = ((analog read)-2.5 )/ 0.1
But I am still not sure with the result.
Any suggestion?

According to the datasheet you have 100mV per ampere, and a zero offset voltage of Vcc × 0.5.
So assuming you are correctly converting the ADC reading into a floating point voltage the instantaneous current can be calculated with the formula
i = (Vadc - 2.5) × 10

Or for milliamps,
i = (Vadc - 2.5) × 10000

If you are measuring a DC current that is then all well and good.  However, if you are measuring an AC current things get considerably more complex.
To work out an AC current you need to have the peak-to-peak voltage, not the instantaneous voltage.  To get that you need to sample the ADC over a number of cycles and find both the maximum and minimum values.  You can then subtract the minimum from the maximum to give you the peak-to-peak voltage.  That can then give you the peak-to-peak current.
From that you can then calculate the RMS current.

Wouldnt the peak voltage alone suffice?

@TisteAndii If the voltage swings precisely around 0V then yes.