text:
Arduino Nano gives 7V on the 5V PIN!
I have an Arduino Nano which is Powered by an external Power supply. This is connected with VIN and GND. The voltmeter says, there are 12,12 V
I have some components connected on the 5V PIN, which altogether draw max. 100mA
Since some of the components are not working anymore, I started measuring...
I have disconnected everything, but the Arduino Nano Power supply. (12,12V)
When I now measure GND and the 5V PIN, the Voltmeter says 6,97V! I guess this is why my components are giving up.

But why are there 6,97 Volts all of the sudden?
Is my Arduino broken now?
Can I fix this?
How can this happen?

I think you should check your voltmeter as the 5v regulator of the nano will not be outputting ~7v

How did you connect it? Try a 5V source on the USB (just a phone charger or USB connection).

Just a stupid question: are you sure you are measuring from 5V to ground and not from 5V and 12V? Because 12V-5V=7V, and I think that's a strange coincidence..

Thanks for the comments. When Powering with USB from PC I have 4,2 V, but that is normal I think. I am 100% sure that I am measuring right and that the voltmeter is fine. :) Also one of the components that is connected with 5V burned through... so there is definately too much voltage on that pin! After the christmasholiday-break I will take a picture for proof ;) Also I tried another Arduino Nano, and there the Power is 5,02 V. So it seems the other one is definately broken.

The 4.2V is a bit too low too. I guess the regulator is broken.

Of course the 5V regulator on the nano can be faulty. Another possibility is the 5V decoupling capacitor. If it goes open circuit the regulator will oscillate and the mean output voltage will be near half the input voltage. Most regs have a minimum decoupling cap value specified.

Since I am using a cheap china-copy instead of an original Arduino, I guess this is exactly what happened.


text:
Using Sprintf() to left pad a string?
I've been at this all day, and I just can't seem to wrap my mind around how to use sprintf() to set a width for my string so that my characters are right justified.
What I'm trying to do is scooch my output over to the right on my touchscreen when the value is positive.
My output string is always a predictable length, so it seems like it should be easy.
I tried concatenating a string with just a space in it, and every other way I could think of to add a space to the beginning of my string. No luck.
char stringval[8] = 1.08;
char juststringval[8];
            if (hashpos > 0 && hashpos < 10) {

                sprintf(juststringval,  " %5s" , stringval);
                Serial.println(juststringval);
            }

output:
1.08 (no spaces in front)

In case you're curious why I need to use a string, my touchscreen will print floats, but my library won't rotate them properly.
Only strings can be rotated the way I need them.
Isn't there some simple way of doing this?
EDIT:
It seems I can use the width trick as long as I include some character besides an empty space.
For example:
void setup()
{
char stringval[33] = "1.08";
char juststringval[33];
char space[] = "rr";         ////THIS WORKS: OUTPUT IS  rr      1.08
float hashpos = 1.08;
if (hashpos > 0 && hashpos < 10) {

    sprintf(juststringval, "%s  %7s", space, stringval);
    Serial.println(juststringval);
}
}

void setup()
{
char stringval[33] = "1.08";
char juststringval[33];
char space[] = " ";     ////THIS DOESNT WORK. OUTPUT IS 1.08 LEFT JUSTIFIED
float hashpos = 1.08;
if (hashpos > 0 && hashpos < 10) {

    sprintf(juststringval, "%s  %7s", space, stringval);
    Serial.println(juststringval);
}
}

But I can't live with other characters in my string.
Isn't there something I can do?

Right justification is the default. Have you tried printing another string above or below it to compare?

Yes, and the default is left justification. When you print something on a new line, it starts on the left, just like words on a page.

Does it work if you supply a left-padded string?

No, it's always as far over to the left as possible. Both in my serial port and on my touchscreen.
Even if I artificially insert spaces into "stringval"

Printing in general starts at the left, but within the field described by the format spec - %5s in your case, the string will be right justified within that 5-char field (assuming the string is 5 characters or less). How wide is your screen? If you're trying to right-justify to the width of a 20-char screen, f/ex, you'll need a (20+1) char buffer, and execute:sprintf(buffer, "%20s", stringval); Serial.print(buffer); This will print a line of 20 characters, space padded on the left, ending in your "stringval".

My text begins at a certain pixel coordinate on the screen. Whenever my output lacks a minus sign, I need an extra space. But what I'm saying is that this method does not work. In both my serial port and on my touchscreen, the output is always as far left as possible.
And unfortunately I cant get away with changing the starting coordinate.

xxprintf() functions don't know about algebraic signs (or any other numeric feature) within strings. For that, you'll have to make a conversion to string from some numeric format that observes the (minus or space) convention for printing signs. As to right justification, I just ran your code, tweaking the field width, and printing to the Arduino IDE terminal window. The output did indeed move farther to the right with larger field widths...

... However, I first tested it in Eclipse, whose terminal uses a variable width font, and the spaces were tiny enough not to make much difference. With the Arduino IDE's terminal and a fixed-width font, it was much more obvious.

@JRobert- I'm currently using Visual Micro for Visual Studio. And my problem isn't with detecting the minus sign. That's unrelated. But I wonder if it's just a quirk of my serial monitor.

It WAS a quirk of my serial monitor.

I just tried and to my surprise a format string of "% 5s" actually prints leading spaces if the string is shorter than 5 characters.

The mistake in question and in comments (except of Bigoldsofty's comment), is missing character for justifying. This character should be in format string before the required width. "% 5s" not "%5s"

source: Stack Exchange

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

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

sort: votes


text:
How to build circuit to switch to other power source if primary source dies?
I would like to have a backup battery connected to a device that requires an uninterrupted power supply, like an Arduino or Raspberry Pi, so that if my primary power source (USB plug) gets pulled, the device will switch to being powered by the battery.
I need a solution that I can either build on a breadboard or buy for only a couple dollars. Does anyone know a solution? I'm assuming this is a common need and think I perhaps am not searching with the correct key words.
Edit:
I would like to add that I may also use 4AA batteries and a DC-DC step down module to produce 5V exactly to power a 5V device, so I'm looking for a solution that accepts 5V. Assume the device, let's say Raspberry Pi, takes 5V, the power supply is 5V, and the battery backup is 5V.

The edit says  “the power supply is 5V” ... does that refer to the 4 AA's with step-down to 5 V?  Or to a mains-connected power supply?

@jwpat7 5V is the rating of both the mains power (USB cable) as well as the DC-DC step down from the batteries

Your $2 budget rules out some of the more-effective possible solutions, such as using an actual UPS (uninterruptible power supply) system.
One affordable approach is to connect the plus side of a 3.7 V lithium-polymer battery through a Schottky diode [such as MBR0520, SS14, 1N5819] to the +5 V line of an Arduino board.  (I haven't looked at Raspberry Pi schematics and don't know if this will apply there.)  Hook the minus side of the battery to Arduino ground.
Ideally, the battery voltage less the voltage drop through the diode (say .4–.5 V) should be just less than the voltage that USB supplies.  Ie, just under 5 V if you have a 5 V board, or just under 3.3 V for a 3.3 V board.  Note, most 3.3 V Arduino systems are specified to run at 8 MHz rather than 16.  There's a good chance a 5 V Arduino running at 16 MHz would continue to run ok when powered by about 3.3 V, but it's out of spec.
If your battery voltage exceeds 5 V you won't be able to make the connection quite so directly.  Besides certain risks of damage (see eg Method #5 and Method #8 of 10 Ways to Destroy An Arduino) there will be the practical matter that the higher battery voltage will cause its power to be used preferentially to the USB power, thus discharging the battery so that it won't act as a backup.
Edit: The question-edit says the system uses 5 V, and seems to suggest the primary 5V power supply uses 4 AA batteries and a DCDC converter.
If the DCDC converter is a step-down buck converter it will go out of regulation when the input voltage from the four AA's goes below 5 V, which is 1.25 V per cell.
As you can see from the following graph, if the discharge rate of a typical alkaline cell is 100 mA, it still has about half its power left when its voltage goes below 1.25 V.  To fully use up the alkaline batteries, you could use a buck-boost converter or could test if your buck converter just passes the voltage on through, as opposed to shutting down when the input voltage is low.

(Note, the AA-battery discharge curves shown above and below are from the powerstream.com's “AA tests”  web page.)
For the backup battery, where you also want 5 V output, an economical possibility is use of four AA NiMH cells, with nominal voltage 1.2 V per cell. However, initial voltage officially can exceed 1.4 V per cell, giving 5.6 V total:

A Schottky diode in series will bring that down to say 5.2 V, an acceptable level for powering a 5 V system.  But if the primary supplies 5.0 V, the backup will end up discharging slightly until its output voltage goes below that of the primary.  If that's acceptable, fine.  Otherwise, you could use a diode like 1N4001, with 0.7 to 0.8 volts of drop at 0 to 150 mA output.  Instead of losing some backup power at first (due to higher backup than primary voltage) you will lose some at the end, due to backup voltage going too low slightly sooner. That won't be a problem, however, if you restore the primary supply and recharge the backups in time to prevent over-discharge damage to the backup batteries.

Thank you for the info. Please see my edit above. Does your suggestion still hold true?

@jake9115, see edit

Thanks for this thorough answer, it is truly helpful. May I ask a bit more of you, and request a circuit diagram or links for parts needed? Your solution sounds elegant and simple. However, other sources, such as here: http://raspberrypi.stackexchange.com/questions/1360/how-do-i-build-a-ups-like-battery-backup-system, suggest much more difficult and complex designs. Are there any obvious deficits with the simpler design you offer here?

Those designs are more complex because they include charging circuits for the backup batteries, and most of them use bigger-than-AA batteries, eg sealed AGM lead/acid batteries as are used in ordinary UPSs.  Because the R.Pi's typical current draw is on the order of 300 mA, vs say 30 mA for an Arduino, the circuit I suggested is only suitable for supporting an R.Pi through brief outages of its main supply (eg five to ten minutes).

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


text:
android app to control arduino using usb
I am trying to figure out how i could make an android app like this one, https://www.youtube.com/watch?v=cVj0jqOlGXo but instead of transmitting through bluetooth it would transmit it through a usb cable that plugs from my phone directly into my arduino.

There are no "good" answers for this, but two classes of possibilities - USB host mode, and "accessory" or "ADK" mode.  Both have a number of issues.  Both have received substantial coverage on the main stackoverflow site which you should read (do not simply post a new question there) and elsewhere online.

I think you may want to look USB Serial port communication in android. Some googling will help
 here's a nice example of such work, described in detail:
http://felhr85.net/2015/01/09/a-dirty-and-quick-example-of-serial-port-communication-in-android/
And in case the codes/that source gets lost, here is the
GitHub link of the developer: https://github.com/felHR85/SerialPortExample


text:
How would i capture and split serial data?
How would i capture the following serial data, and split it into parts?
<Alarm,MPos:0.000,0.000,0.000,WPos:0.000,0.000,0.000>
the parts i need from this is
Alarm - This is a state. i.e Alarm, Idle, Paused, Working
MPos: - This is a series of positions X,Y,Z
WPos: - This is a series of positions X,Y,Z
What i want to do is capture the string from serial (See above for formatting)
Then display the information on the LCD.
i.e.
X: 0.000  Y:0.000
Z: 0.000  Idle
I've managed to figure out how to do all the LCD display stuff, and send commands to the serial, but it appears there are so many variations on how to split the data up, that i't really confusing to me, as well, almost all of the examples i find use loop to do this, but i would like to have this done in a function, that way i can display this info only when needed, not constantly, as i'll be useing the LCD for a menu system.

An actual example of what the string looks like would help - your description is very very vague and of no use to us whatsoever.

Wierd.. i did include an example.. not sure where it went.
<Alarm,MPos:0.000,0.000,0.000,WPos:0.000,0.000,0.000>
That is the string i need to capture and split up

Ah, it probably thought it was HTML and pruned it out.

Are all the parts always there and always in the same order?

Yes, all parts are always there, and always in the same order, however, they are not always the same.
I.e.
<Alarm,MPos:0.000,0.000,0.000,WPos:0.000,0.000,0.000>
<[1],MPos:[2],[3],[4],WPos:[5],[6],[7]>

This could be any of the following: Idle, Run, Hold, Door, Home, Alarm, Check
This is Machine Position X
This is Machine Position Y
This is Machine Position Z
This is Work Position X
This is Work Position Y
This is Work Position Z

This string is actually fairly easy to split up, because everything is separated by commas nice and regularly.
Assuming you have the string in a char array (aka a C string) and not a String object (I and most other programmers abhor the String class) you can use the function strtok() to split the string up into parts.
So you have the string:
char string[] = "<Alarm,MPos:0.000,0.000,0.000,WPos:0.000,0.000,0.000>";

The function strtok() takes, on its first call, the string you want to split and the delimiter that you want to split on.  It returns a pointer to the chunk:
char *alarm = strtok(string, ",");

alarm now contains <Alarm and strtok() moves its internal pointer to point at the next character, so it sees the string as MPos:0.000,0.000,0.000,WPos:0.000,0.000,0.000>
With the next and subsequent calls to strtok() you don't give it the string, or it will reset its internal pointer.  You just pass it NULL and it gives you the next block:
char *mposX = strtok(NULL, ",");
char *mposY = strtok(NULL, ",");
char *mposZ = strtok(NULL, ",");
char *wposX = strtok(NULL, ",");
char *wposY = strtok(NULL, ",");
char *wposZ = strtok(NULL, ">");

Note that I changed the delimiter on the last one to > so it chops off that extra character that we don't want (and there is no , after the last part).
So now you have 7 variables that point to chunks of the string, which has internally been chopped up and modified into individual substrings:
*alarm = "<Alarm";
*mposX = "MPos:0.000";
*mposY = "0.000";
*mposZ = "0.000";
*wposX = "WPos:0.000";
*wposY = "0.000";
*wposZ = "0.000";

So now we can clean up the three entries that have extra stuff in them, and that is a simple as adding an offset value to the pointers we have:
alarm += 1;
mposX += 5;
wposX += 5;

Our list of pointers now looks like this:
*alarm = "Alarm";
*mposX = "0.000";
*mposY = "0.000";
*mposZ = "0.000";
*wposX = "0.000";
*wposY = "0.000";
*wposZ = "0.000";

The position variables can now be passed through strtod() to convert them to float values:
float mx = strtod(mposX, NULL);
float my = strtod(mposY, NULL);
float mz = strtod(mposZ, NULL);
float wx = strtod(wposX, NULL);
float wy = strtod(wposY, NULL);
float wz = strtod(wposZ, NULL);

You can do different things depending on the content of the *alarm string by using strcmp():
if (strcmp(alarm, "Busy") == 0) {
    // Something to do when Busy
}

etc.
Or you can just use it to print the content to the LCD.


text:
How can i read serial data into a string until a certain character is recieved?
This is not a duplicate of my other question. This question deals with reading specific data within a serial stream. The other question deals with reading and adding data into a manageable data string.
What I'm trying to do is send a command to serial, get the response, and put it into a string, and then break that string up into usable parts of data.
The problem I'm having, is there is a delay between the time the serial command is sent, and the response. meaning the serial data isn't being captured before the function moves onto the next line. Using delay() doesn't appear to work, as i believe it halts everything for that delay period.
What I'm hoping to do, is read the data from serial and if the character '<' is received, place it, and everything after it into the buffer until the character ">" is received.  After the last character is received, and placed into the buffer, continue on with the script.
Unless of coarse someone has a better idea on how to approach this.
i would also like to note that this is just a part of a larger project. If you need to see the entire project, please let me know and i will provide a link where you can download it.
The string i'm expecting as a response would be similar to this:
<Alarm,MPos:0.000,0.000,0.000,WPos:0.000,0.000,0.000>

Here is the code i have so far:
float mx;
float my;
float mz;
float wx;
float wy;
float wz;
String dAlarm;
char buffer;
void gPos() {
  Serial1.print("?\n");
  buffer = Serial1.read();
  char string[80];
  string[buffer];
  char *alarm = strtok(string, ",");
  char *mposX = strtok(NULL, ",");
  char *mposY = strtok(NULL, ",");
  char *mposZ = strtok(NULL, ",");
  char *wposX = strtok(NULL, ",");
  char *wposY = strtok(NULL, ",");
  char *wposZ = strtok(NULL, ">");
  alarm += 1;
  mposX += 5;
  wposX += 5;
  mx = strtod(mposX, NULL);
  my = strtod(mposY, NULL);
  mz = strtod(mposZ, NULL);
  wx = strtod(wposX, NULL);
  wy = strtod(wposY, NULL);
  wz = strtod(wposZ, NULL);

  if (strcmp(alarm, "Idle") == 0) {
    dAlarm = "Idle";
  } else if (strcmp(alarm, "Run") == 0) {
    // Something to do when Busy
    dAlarm = "Run";
  } else if (strcmp(alarm, "Hold") == 0) {
    // Something to do when Busy
    dAlarm = "Hold";
  } else if (strcmp(alarm, "Door") == 0) {
    // Something to do when Busy
    dAlarm = "Door";
  } else if (strcmp(alarm, "Home") == 0) {
    // Something to do when Busy
    dAlarm = "Home";
  } else if (strcmp(alarm, "Alarm") == 0) {
    // Something to do when Busy
    dAlarm = "ALARM!";
  } else if (strcmp(alarm, "Check") == 0) {
    // Something to do when Busy
    dAlarm = "Check";
  }
  dispPos();
}

void dispPos() {
  int state = 0;
  int x = analogRead (0);
  if (x < 800) {
    state = 1;
  }
  if (state == 1) {
    dPos = false;
  }

  if (dPos == true) {
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("X");
    lcd.print(mx);
    lcd.setCursor(8, 0);
    lcd.print("Y");
    lcd.print(my);
    lcd.setCursor(0, 1);
    lcd.print("Z");
    lcd.print(mz);
    lcd.setCursor(8, 1);
    //lcd.print(" ");
    lcd.print(dAlarm);
    delay(3000);
  } else {
    mainMenu();
  }
}

possible duplicate of How would i capture and split serial data?

Sorry nick gammon, not a duplicate of that question. That question dealt with capturing and splitting the data. This deals with doing it for specific data only. The difference between the two is one asks how to capture and split, this one delves deeper and captures based upon certain criteria.

You have lost me as to the difference between "capturing and splitting the data" and "for specific data". You are quoting the same data: <Alarm,MPos:0.000,0.000,0.000,WPos:0.000,0.000,0.000>. It's all very well do "delve deeper" but this is splitting the basic problem across two separate questions. One with, and one without, "certain criteria" I gather.

I guess i could go ahead and delete the question, but i have a feeling it would just be asked again, simply because it deals with a specific problem within a general subject. As far as i know, we aren't supposed to expand upon the initial question with another one. As i said, the first one deals promarily with general serial data collection, and processing. Where this question deals with a specific string within the serial stream. Just because i used the same example, doesn't mean the question is a duplicate, it offers other readers information not available in the first question's answer..

What you need to do here is implement a small finite state machine.
Basically you need to look at each character as it comes in and make a decision what to do with it depending on what state you're in at the moment.
Basically the operational decisions you need to make are:

Is the character a < and am I currently not reading a string?

Yes, start reading the string.

Is the character a > and am I currently reading a string?

Yes, finish reading the string and process it

Is it any other character and I am currently reading the string?

Yes, add it to the buffer.

So you can see there some common questions:

What is the character?
What am I doing at the moment?

So you need to have a simple state variable that remembers if you're reading the string or not, and something to say where in the buffer you are so you know where in the buffer to add any incoming characters.
boolean readingString = false;

A simple true/false will suffice to depict if we're reading the string or not.  Start off not reading the string.
char buffer[80] = "";

A buffer to store the text - maximum of 80 characters (including the NULL terminating character)
int charPointer = 0;

Something to know where in the buffer are currently.
Now to read the characters:
First get the next character from the serial port:
loop() {
    if (Serial.available()) {
        int incoming = Serial.read();

Now decide what to do with it.  We have a number of possible situations, some of which can be combined into single options.  For instance, if we get a "<" while reading a string it's an error condition - but do we really care?  It could be that we lost the end of the last string and have just started a fresh one - so we can just treat it as the start of a string regardless of what state we're in.  Let's use a switch for this since it's nice and tidy:
        switch (incoming) {
            case '<':
                readingString = true; // Start reading string
                charPointer = 0; // Set the buffer pointer to the start
                buffer[0] = 0; // Make the string empty
                break;

            case '>':
                if (readingString) {
                    processBufferData(); // Do something with the buffer
                }
                readingString = false; // Finish reading
                break;

            default: // Anything that's not > or <
                // If we are reading the string and the buffer isn't full
                if (readingString && charPointer < 78) {
                    // Add the character to the buffer and increment the pointer
                    buffer[charPointer++] = incoming;
                    buffer[charPointer] = 0; // Don't forget to terminate the string
                }
        }
    }
}

So the reception of a < starts the string reading, the reception of a > stops it and triggers the processing of the string, and anything else (while we are reading the string) gets added to the buffer.

for some reason i'm not getting the result i expect.
I think because elsewhere in the script i already have serial available, and perhaps it's interfering, or something else more drastic is happening.
If you're willing to take a look. Perhaps you can spot, and explain what i've done wrong and where so others can learn from my mistakes.
Also.. Please don't laugh too hard at me, it's only my second or third week using the arduino IDE
I've uploaded my project to Here

You must only consume the serial bytes in one place, otherwise who knows what'll happen.

hrm.. well.. that kind of shoots my entire project down then.
What i'm trying doing is sending data to an arduino Uno with GRBL, through an arduino mega with an LCDKeypad shield.
That way i can display the POS on the LCD, have a menu system for common GRBL stuff. As well as use the PC (and at a later date SD) to send g-code to the uno.
So the flow would be PC-> Mega+Keypad -> UNO | Uno -> Mega -> LCD+PC
So far everything is working OK, but i've had to avoid using if(serial.available) as it's always available so it can send data from PC to UNO, and from UNO to PC.

Just move the reading routine out of the timer and into the serialcomms routine, and print the characters in there instead.

I Thought about that, and was working on it as you responded.
I left the command in the timer that requests the status string from GRBL (the string we are processing)
That way it can continue to update without interference.
And i moved the reading of the string to the serial comms. Going to test it now :)

@ArcAiN6 You need to remove it from the timer.  The routine only consumes one character with each call, so it can run directly within loop() without any blocking.  If you have it in the timer it will only take one character every time the timer fires - it will take forever to read one string in.

I think you misunderstood what i left in the timer loop.
I moved everything out of the timer into serial coms, except for the command that tells grbl to display position..
This is the only thing left in the timer.
Serial1.print("?\n");
The reason i did that is because everytime GRBL replies with position, it causes the stepper motors to stop moving for a fraction of a second. This may not seem like a big deal, but if this happens every few miliseconds as the loop gets back to the serial function we've created, it would cripple the stepper motors, and possible cause grbl to poop the bed.

@ArcAiN6 Ok, that's cool.

With that problem solved thanks to your insights, I'm off to search out information on how to compare those floats we created, that way i can update the display in real time as the positions change :)

Floats can be tricky to compare since they are only approximations.  It could be better to do them as integers - multiply the value by (say) 1000 and store them as integers then divide them by 1000 to display them.

nod I was looking that over, and was contemplating on convert them to integer, then round them off, then compare the rounded integer of the stale data, against the rounded integer of the new data.


text:
Why do ESP boards break out the SPI flash pins?
I have an ESP32 development board and a NodeMCU board here. Both breaking out the pins for the SPI flash of the ESP. These pins are mentioned in standard pinout descriptions as must/should not connect. This pinout description states, that they

are not recommended for other uses. So, don’t use these pins in your projects

The answer to this question suggests, that you can somehow connect other SPI devices to the same bus as the SPI flash. The linked documentation from that answer states, that in that case you cannot control the chip select for the additional SPI device via a digital pin, but have to let the "hardware arbiter" (whatever that is) decide, when to connect to the additional SPI device.
That is the only use of these pins, that I could find, and even this seems pretty niche. It doesn't seem to be a standard way of usage for the pins and also rather difficult.
Considering the very limited and difficult use of the SPI Flash pins, why do ESP boards break these out to the user? Why aren't they just kept internal, making the board a little smaller?
Maybe there is another use of the pins or I just underestimate the importance of adding additional SPI devices to the bus.

Majenko's answer applies to esp8266 modules. But the question "why on the NodeMcu" remains? Can the NodeMcu Lua firmware use it?

Considering the very limited and difficult use of the SPI Flash pins, why do ESP boards break these out to the user? Why aren't they just kept internal, making the board a little smaller?

The ESP32 is not designed specifically for Arduino. There are other boot modes, such as SD card boot, whereby the internal flash is not directly used. In this situation you are free to use those pins as you wish (given that there is a flash chip attached to them).
The "ESP32 Development Board" was not primarily designed for Arduino. Instead it's a generic board designed by Espressif (and copied many times), and is usable with the Arduino core as one of many options.
In short: the pins aren't there for Arduino users, they're there for other users.

Addendum:
The SPI flash pins can also be used for (and are most commonly used for):

Adding more SPI flash chips which then get integrated into the normal memory space and with the internal caching system, and
Adding PSRAM to increase the RAM memory space.

A good example of the latter is the ESP32-CAM which has an SPI-connected PSRAM chip for framebuffering and image analysis connected to the SPI pins.
You can think of them not so much as SPI pins but as the EBI pins of the PIC32MZ or the EMB of the ATMega2560, etc. Used for expanding the memory rather than for adding random peripherals.

+1. That said, I do find it silly to breakout those pins on consumer-targeted devboards...

@dandavis What's a "consumer-targeted devboard"?  A devboard by definition is not consumer targeted. It's developer targeted. A consumer would never see one.

Fair point, I meant something like a Wemos D1, ESP-CAM, and other's you can buy on consumer sites like ebay/amazon/ali, compared to "pro" dev things from digikey, mouser, TI, and the like...

Most of those are cheap chinese copies of the original Espressif devboard. You may want them, so they give them. Why not? If you don't need them just ignore them. If you do need them then they're there for you. The more people that the board can appeal to the more people will buy it.

Wow, didn't know of the SD card boot. That sounds really interesting. I guess the lines between consumer and developer are a big fuzzy for the field of hobbyists. That explains it for me. @Majenko Thank you for your expertise

@chrisl, SDIO card/device, not SD card

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


text:
Using Piezzo Electric buzzer 10V with an Arduino Lilypad USB
I bought a 10 V Piezzo electric buzzer and I wonder how to connect it to an Arduino (in my case a Lilypad USB, but the question stands for any Arduino I guess...).
I hadn't realized this was a 10V buzzer, whereas the Arduino will support at most 5V.
I tried a simple layout such as below, with the sample code from a sparksfun tutoral, but that's not working!

So, how can I do it? ... or should I use another buzzer ?
Thanks

Your options:

Try it anyway with 5V: the buzzer might still produce loud enough sounds for your needs.
Use the line from the arduino to drive an "amplifying" stage (ex: 2N2222 in ON/OFF mode) - but this will also require a 10V source (like a step-up voltage converter)
Get a piezo that is designed to operate at 5V

I'll try next week-end and let you know, thanks.

I haven't managed to get any sound, but I'm probably doing it wrong.
I connected the buzzer to output pin 9 (and the other one to GND), and used the code here : no sound.
I also tried with another 5V buzzer : no sound.


text:
Why does my LCD display random characters?
I've been struggling with my LCD for hours, and after solving more different issues than I can remember, I'm out of ideas for this one.
My LCD is showing random characters, see the picture below (the last character blinks, some characters change and over time there are slowly more and more characters). I'm starting to wonder if the LCD I chose has a driver compatible with the LiquidCrystal library, what do you think? If so what can I do to avoid buying another one?

Here is the code:
// include the library code:
#include <LiquidCrystal.h>

// initialize the library with the numbers of the interface pins
//RS EN D4 D5 D6 D7
LiquidCrystal lcd(2, 3, 4, 5, A2, A3);
//RW to GND, VSS to GND, VCC to 5V, V0 to wiper of 5V-to-GND 10k potentiometer

void setup() {
  Serial.begin(9600);
  Serial.println("Starting");
  lcd.begin(16, 2);
}

void loop() {
  lcd.setCursor(0, 1);
  lcd.print(millis() / 1000);
  Serial.println("Printing");
  delay(1000);
}

I'm using this Arduino and this LCD. Note that I'm using pins 10,11,12,13 for a SD (which works) and 6 7 8 for a MAX232 (which is disabled).
Any ideas?

I'm not sure whether the LiquidCrystal library supports using the "analog pins" A2 A3 that way. Can you test your LCD using the standard pin configuration (obviously not using the SD or any other interfering devices). The LCD itself looks like a common HD44780 type, so pin configuration is more likely the cause than some exotic device driver.

The LiquidCrystal library includes known-good example code, that's part of what Arduino is for. Go ahead and use that as a diagnostic to check the LCD works, before attempting the non-standard connection.

Thanks. The above code is an example on the official website, I've just added the delay() so it should work... I've checked and A2 and A3 are sending digital signals just like the other pins so it looks fine. Passerby, isn't it sufficient to call the constructor with 6 arguments to select 4 pin mode?

A lot of people having this issue had EMC issues - The 5V is supplied by a boost converter from a battery but I've observed the supply rail and it's a solid 5V...

The pins not labelled on the picture are left unconnected - should I ground them? All examples I've seen left them unconnected

Stupid question but the picture looks like you just pushed the wires in the holes. You did solder them, didn't you?

Please don't migrate this post to Arduino SE for now - too late!

check 2 and 3 :) again your soldiering is bad, well from what I know if there is "?" this sign you must check your connections

The connections are through hole, it doesn't matter which layer I solder them on, and they are soldered on the bottom. I've checked and the top pads are connected.

It could be because "millis()/1000" generates a "number", and not the "string" (or "char"). Try to add ",DEC" in your lcd.print(), something like "millis()/1000,DEC" to convert it to "decimal". Generally, it depends on the library, how they implement this function.
Good luck,
Mike

You and Passerby were right about this, I ruled it out because it was an official example but it is obvious that their example was wrong. I changed that to "ABC...Z" and then "123...90" and both worked flawlessly. Thanks!


text:
MG2639 & Arduino Uno not GPS-ing?
is there any way I can run an MG2639 GPS Cellular Shield (the one SparkFun makes) on an Arduino Uno for GPS tracking purposes? It seems whether I use New or AltSoftSerial, the unit just can’t read what’s streaming in through from the GPS on the 115200 baud rate, which the shield is hard-wired to.

Have you tried sending the baud rate command yet?

Try sending a command that sets the GPS baud rate to something a little lower:
altss.write( F("$PMTK251,38400*27\r\n") );
altss.end();
altss.begin( 38400 ); // change to match above command

Are you sure you're having trouble reading, because there are many other things you may be doing in your sketch that cause input buffer overflow.  Please post your code and some sample output for us to examine.  It may be failing for a different reason.
For example, you may just be losing data because you're trying to do too many things in loop().  Please take a look here.
To solve this kind of problem, I have posted a modified version of AltSoftSerial on github, here, that let you process GPS data in the background (i.e., during interrupts).  When coupled with NeoGPS, it can save you quite a bit of program space, RAM and execution time.  There is an interrupt-driven example here.  Just change which include is uncommented on lines 30-31:
#else
  // Only one serial port is available, uncomment one of the following:
  #include <NeoICSerial.h>
  //#include <NeoSWSerial.h>
#endif
#include "GPSport.h"

...and the baud rate below, on line 140:
  // Start the UART for the GPS device
  gps_port.attachInterrupt( GPSisr );
  gps_port.begin( 115200 );
}


text:
Serial monitor disconnecting itself
Problem: can't print to the serial monitor, it appears that the serial monitor disconnects itself after uploading a program.
I'm brand new to arduino, and I'm trying to upload a basic program to print to the serial monitor.
I use an arduino uno and my OS is Ubuntu.
I am connecting the arduino to my PC via USB.
Using Arduino Studio Release 0.0.5 experimental build 0.0.5-16058
(I am able to communicate via the digital output pins, tested by making a simple circuit to make the led light blink)
Here is the program:
void setup()
{
    Serial.begin(9600);
}

void loop()
{
    Serial.print("test");
    delay(500);
}

Here is the result of the build, look at the last line and it says the serial monitor was disconnected? Why would this happen automatically?
[2/2/2016 8:51:26 PM] - Start Building
[2/2/2016 8:51:26 PM] - CPP File Created [/tmp/build1454471486915/test.cpp]
[2/2/2016 8:51:26 PM] - test.cpp compiled
[2/2/2016 8:51:26 PM] - CDC.cpp compiled
[2/2/2016 8:51:27 PM] - HID.cpp compiled
[2/2/2016 8:51:27 PM] - HardwareSerial.cpp compiled
[2/2/2016 8:51:27 PM] - HardwareSerial0.cpp compiled
[2/2/2016 8:51:27 PM] - HardwareSerial1.cpp compiled
[2/2/2016 8:51:27 PM] - HardwareSerial2.cpp compiled
[2/2/2016 8:51:27 PM] - HardwareSerial3.cpp compiled
[2/2/2016 8:51:27 PM] - IPAddress.cpp compiled
[2/2/2016 8:51:27 PM] - Print.cpp compiled
[2/2/2016 8:51:27 PM] - Stream.cpp compiled
[2/2/2016 8:51:27 PM] - Tone.cpp compiled
[2/2/2016 8:51:27 PM] - USBCore.cpp compiled
[2/2/2016 8:51:27 PM] - WInterrupts.c compiled
[2/2/2016 8:51:27 PM] - WMath.cpp compiled
[2/2/2016 8:51:27 PM] - WString.cpp compiled
[2/2/2016 8:51:27 PM] - abi.cpp compiled
[2/2/2016 8:51:27 PM] - hooks.c compiled
[2/2/2016 8:51:27 PM] - main.cpp compiled
[2/2/2016 8:51:27 PM] - new.cpp compiled
[2/2/2016 8:51:28 PM] - wiring.c compiled
[2/2/2016 8:51:28 PM] - wiring_analog.c compiled
[2/2/2016 8:51:28 PM] - wiring_digital.c compiled
[2/2/2016 8:51:28 PM] - wiring_pulse.c compiled
[2/2/2016 8:51:28 PM] - wiring_shift.c compiled
[2/2/2016 8:51:28 PM] - CDC.cpp.o linked to core.a
[2/2/2016 8:51:28 PM] - HID.cpp.o linked to core.a
[2/2/2016 8:51:28 PM] - HardwareSerial.cpp.o linked to core.a
[2/2/2016 8:51:28 PM] - HardwareSerial0.cpp.o linked to core.a
[2/2/2016 8:51:28 PM] - HardwareSerial1.cpp.o linked to core.a
[2/2/2016 8:51:28 PM] - HardwareSerial2.cpp.o linked to core.a
[2/2/2016 8:51:28 PM] - HardwareSerial3.cpp.o linked to core.a
[2/2/2016 8:51:28 PM] - IPAddress.cpp.o linked to core.a
[2/2/2016 8:51:28 PM] - Print.cpp.o linked to core.a
[2/2/2016 8:51:28 PM] - Stream.cpp.o linked to core.a
[2/2/2016 8:51:28 PM] - Tone.cpp.o linked to core.a
[2/2/2016 8:51:28 PM] - USBCore.cpp.o linked to core.a
[2/2/2016 8:51:28 PM] - WInterrupts.c.o linked to core.a
[2/2/2016 8:51:28 PM] - WMath.cpp.o linked to core.a
[2/2/2016 8:51:28 PM] - WString.cpp.o linked to core.a
[2/2/2016 8:51:28 PM] - abi.cpp.o linked to core.a
[2/2/2016 8:51:28 PM] - hooks.c.o linked to core.a
[2/2/2016 8:51:28 PM] - main.cpp.o linked to core.a
[2/2/2016 8:51:28 PM] - new.cpp.o linked to core.a
[2/2/2016 8:51:28 PM] - test.cpp.o linked to core.a
[2/2/2016 8:51:28 PM] - test.ino linked to core.a
[2/2/2016 8:51:28 PM] - wiring.c.o linked to core.a
[2/2/2016 8:51:28 PM] - wiring_analog.c.o linked to core.a
[2/2/2016 8:51:28 PM] - wiring_digital.c.o linked to core.a
[2/2/2016 8:51:28 PM] - wiring_pulse.c.o linked to core.a
[2/2/2016 8:51:28 PM] - wiring_shift.c.o linked to core.a
[2/2/2016 8:51:28 PM] - test.cpp.elf linked to core.a
[2/2/2016 8:51:28 PM] - test EEPROM
[2/2/2016 8:51:28 PM] - test.hex builded
[2/2/2016 8:51:28 PM] - Uploading...
[2/2/2016 8:51:30 PM] - Uploaded
[2/2/2016 8:51:30 PM] - [arduino ide - serial monitor] Serial monitor connected to /dev/ttyACM0
[2/2/2016 8:51:36 PM] - [arduino ide - serial monitor] Serial monitor disconnected from /dev/ttyACM0

Are you using the Arduino IDE? If so, what version? If not, what are you using?

Yes, ArduinoStudio Release 0.0.5 experimental build 0.0.5-16058

Does the serial monitor disconnect when you hold open the monitor and after that hold the reset button?

I'm not sure why your IDE is doing that, but the official Arduino IDE from Arduino.cc works on Ubuntu and does not have that issue. Download from Arduino Software download page.

I thought arduino studio was the official IDE, I'll download it and try it when I get home. Thank you for the suggestion

@JamesWierzba "Arduino Studio" is from Arduino.org, whereas this answer links to the standard IDE produced by Arduino.cc. Neither is more official than the other; the original Arduino company split into two factions and are now offering competing products and software.

I edited my answer to clarify that I was referring to the version from Arduino.cc. Arduino.cc has a forum where you can ask questions like that. Arduino.org does not appear to have a forum (as far as I can see).

I downloaded the Arduino IDE you suggested and printing to the serial monitor now works. Thanks


text:
Why connect arduino with Rasberry pi?
I have a question about connecting a Arduino with Raspberry Pi.
What is the benefit of connecting the two?

Thanks a lot. Thats some great answers :-) Do any of you know any good resources where I can learn about connecting the two?

Interfacing hardware is easier with the Arduino: more available I/O pins
capable of sourcing and sinking more current, 5 V I/O, analog
inputs, very predictable timings, etc. The Raspberry, on the other hand,
is a real computer with a real OS, has a lot more computing power
and memory, has Internet connectivity, can easily run “standard” web
servers like Apache or nginx... or mostly any Linux software for that
matter.
Some projects can benefit from using both. E.g. if you want to make a
web interface for some low-level hardware sensors.

Why add an Raspberry Pi to an Arduino?
There are some things that simply are beyond the possibilities of Arduino. The first thing that would cross my mind is video processing, HDMI output, decent sound etc.
A Raspberry Pi can be used to add some features to your project aswell. If you make an Arduino controlled robotic arm, you could add an "user interface" to it, using a Raspberry Pi.
Why add an Arduino to an Raspberry Pi?
Some may argue that the Raspberry Pi is much more capable as an Arduino, in every form.
Though, the strengths of Arduino are:

Ease of use. (For GPIO on Raspberry Pi you'll likely need to install something, to make it work with your favorite programming language.)
Real time / deterministic timing, this is one of the best things of Arduino. Given that an Arduino has no "operating system" that can induce random (tiny) delays in your program (other than the millis()/micros() interrupts).

Why do any of this? You could choose an Arduino OR Raspberry Pi
One thing you might not think about is, that by joining an Arduino and a Raspberry Pi, you're joining two important parts of Embedded Systems. Which you can learn a lot from.
Microcontrollers and Single-board computers. This really has a good educational effect. Since you'll not limit yourself to one device or "way of thinking".
Moreover, the interfacing between two devices is often important and will bring some extra problems. (And solving them gives extra knowledge/experience)

I prefer to use arduino type boards as data acquisition units then transfer the data to an actual computer (or raspberry pi) in most of my projects. Arduinos are, in my experience, much more tolerant of fault and accidental crossed circuits than the R pi.  Thus is especially true of the ruggedized or industrial arduino versions.

Good point! One could say that accidently blowing up your Arduino is much cheaper than blowing up a raspberry pi

And it is much easier to destroy a Pi than it is an arduino... Although I love the fact that I often have to add a 0.2V schottky diode in fw bias to control a little MOSFET... just to prevent the cr?p from dying because of a little spike.

authors: وليد مبارك عيد


text:
Do I need to solder wires to my tilt sensor?
I am using the Arduino Starter Kit and I am on project 8. The picture of the sketch in the book is not clear because it shows the tilt sensor seemingly resting sideways, which is not the way that it connects. If you insert the pins into the board the sensor will always be standing and there will be no way to turn it. I was thinking you might have to solder wires to the pins. Does anyone know?
-Thanks
Edit: Perhaps this picture will help:

Pretend for a moment that we don't have a clue what it is your describing.  Show us some pretty pictures and point out what you mean.

My question is: How do you use a tilt sensor, because I can't seem to figure it out, and my book does not explain it.

Well I for one can't see your book or your tilt sensor. PICTURES!

The picture of the sketch in the book is not clear - the picture in your question is even less clear. Non-existent would be my way of describing it. which is not the way that it connects - you've lost me there. I usually tilt things in all sorts of directions when I connect them.

Perhaps this picture will help - see amended answer.

Generally, yes, you will need to solder to that.  In a way a wire wrap tool may be preferable (you can start with it just wrapped, and later solder the wrap if you wish) however that wire has a limited flex life, and you would have to wrap the other end to header pins before inserting them in a breadboard.  Individual female crimp connectors may also be an option, but the pins of that sensor look short and may not work well in housings, though you can individually heat shrink them.   Socket contacts from 2mm connector families sometimes grip .100" pins better at short engagement, too.

I don't have the starter kit but I have a tilt ball sensor:

My guess is that there is a ball inside it, and it connects the wires, like this:

This is confirmed by measurement.

I suggest you either solder wires to it, or push the wires into your breadboard. As you can imagine from the diagram, the contacts will be closed if the ball (or mercury or whatever it is) is downwards. In other words, if the leads are facing down. As you tilt it, the ball will move away from the two wires, breaking the connection. You may have to tilt it quite a lot for this to happen.

(Edited to add)
I see from the Arduino Starter Kit page that the tilt sensor works like this:

This shows that my guess was pretty accurate. :)
There are four pins, so I imagine that the ball would connect four of them if held upright, and various combinations if tilted forwards or sideways.

If you insert the pins into the board the sensor will always be standing and there will be no way to turn it.

Well, you could tilt the breadboard, yes?
However I agree that if you want to tilt just the sensor, then soldering wires to it would seem quite sensible.
I think the starter kit is there to show you the concepts. There is nothing stopping you tilting the entire breadboard to see how it works. In practice you would mount the sensor in such a way that it activated when moved from position A to position B, whatever that is.

I remember when the glass beads with mercury in them were still legal :)  At least with those you could see exactly how they worked.

Yes I think that tilting the sensor when it is on the breadboard might work. It would make sense to tilt the breadboard, but the pins do not fit smugly into the board so it would just fall out; but I think that is why the pins don't fit: so you can turn it.

A breadboard (even a smaller daughter one) will not permit independent connection to all four pins; also the pins are likely too short for reliable connection.

I would say @ChrisStratton is right. Those pins look close together, and it would be hard, or impossible, to get them into a breadboard with independent connections (because of the way breadboards work).

I have the starter kit with the exact same tilt sensor. In my experience it does sorta work. In that you can plug it in the breadboard and it will sit snugly and have a stable connection, but two and two of the connectors will be shorted so you can't use all four independently. And it will respond to tilting the board, at least in one specific direction. So it does work without soldering, at least for learning/demonstration purposes.


text:
Why is my TMP35 giving me weird values?
A TMP35/36/37 is giving very high voltage readings, which results in high temperature readings. The serial monitor looks like this:
As you can see, the sensor value is in the 900s, voltage is almost 5, and temp is in the 400s. The circuit is very simple, just a TMP connected to 5V and ground and pin A0. Here is my code:
const int sensorPin = A0;
const float baselineTemp = 20.0;

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

}

void loop() {
  int sensorVal = analogRead(sensorPin);
  Serial.print("Sensor value: ");
  Serial.print(sensorVal);

  float voltage = (sensorVal / 1024.0) * 5.0;
  Serial.print(", volts: ");
  Serial.print(voltage);

  Serial.print(", degrees C: ");
  float temperature = (voltage - .5) * 100;
  Serial.println(temperature);
  delay(1000);
}

This is a very simple program and a very simple circuit, so I'm not sure what is going on. Maybe the problem is the sensor itself. I have also tried this sensor with multiple other circuits and programs and the same thing happens.
If anyone knows anything about this, help would be great.

Can you hook up a voltmeter to the Vout of the TMP? If the voltage is actually that high, then yes, you've got a broken part. Try another TMP sensor. This is to just rule out the arduino.

When I connect a voltmeter to the TMP it says 5V. So it must be the part.

Yeah, must've gotten damaged somehow. Just for the sake of being thorough you could: 1. double check your circuit, 2. double check the the TMP orientation (I've hooked them up backwards before), 3. double check the supply voltage and make sure it's between 2.7v and 5.5v (per the data sheet). But, you probably already did these things. I just thought I should mention them just in case.

Thanks for the comment but yes, I checked all these multiple times. Too bad they only give you one TMP in the starter kit.

Just curious: where does the - .5 come from, in float temperature = (voltage - .5) * 100;? TMP35 outputs 10mv/degC, with 0v at 0degC. (Not that it would help if this is a coding error; it would make your results look 50degC higher.)

Part seems to be broken; voltage is unusually high.

Before you toss it, it's worth trying another ADC pin.  Also make a divider with some resistors and verify you can get a range of values from the ADC.  And be sure you have the sensor, not some random transistor, and that you have the wiring correct, including its ground connected.

Thanks, tried different ADC pins, all same results. It is definitely a temperature sensor and the wires are correct. I will try to make a divider to test the ADC, but the other pins were giving me the same results.

I use voltage dividers a lot and have seen this before.
In each and every case where ALL my readings are high, yet they vary predictably (like on my solar panels - they go up during day and down at night), there has always been proven to be a very simple, single cause.
Resistance in the ground lead.
Such as if it is plugged into a breadboard hole that is not holding it well, or if I have extended it and have connections along the way.
So that would be the first thing I would look for.

Having said that, if the readings are very high and do NOT vary predictably, then I would look for a disconnected ground lead.

If all the connections are good but it still misbehaves then I would swap it out with another one to make sure the part itself isn't the problem.


text:
Adafruit 128x64 OLED not turning on
I ordered a 128x64 pixel OLED display from Adafruit and wired it according to their guide. (To an Arduino Uno) I'm using SPI right now and the display will not turn on or do anything. I haven't tried i2C, but I don't think that should make a difference. Maybe I will if nothing else works. I've installed the two libraries from the guide and am running the SPI 128x64 example. I've tried to find people with this same issue but I haven't found that much about it. Any help would be greatly appreciated!
Edit: Added pictures. I've used header pins in the past in case anyone is wondering if the connection using these wires isn't good, but the pins did not work either, so it's not a bad connection.

There isn't exactly a question here that has a definite answer. A clear photograph of your setup would help. Please state the exact part number you are using, also the exact sketch that you are testing it with.

The sketch is an example from the SSD1306 library called "ssd1306_128x64_spi". I will add a picture soon.

I don't see any soldering in those pictures. You can't just poke wires into holes and hope they'll work. That will be your problem.

and wired it according to their guide - No you didn't. See the this - you didn't solder the pins to the board.

I understand that, but I've done this with a few different sensors in the past and as long as the wires are touching the metal holes there is a connection. I also have set it up exactly how they showed it in the guide just without soldering it.

When I move the OLED around a little bit the "L" light on the Arduino flashes and I get a notice on my computer saying that a USB device is using too much power. That usually happens when something gets shorted, and I'm not sure why that would be happening here.

The green and yellow wires on the right look very close. I suggest you install it properly, soldering the wires in and not having large amounts of bare wire which are almost touching. Or at least solder on a header strip as shown in the article. The whole point of using a breadboard is that those pins stick into it.

These devices are selectable to use SPI or I2C by means of a soldered-in jumper on the back. You can use either but your jumper selection must match. Does yours?

Wiring is your problem. Use soldering iron/solder and flux. Solder your wires. Intermittent connections and accidental shortages with current setup may damage your Arduino and display (and possible your PC/laptop).

I know this issue and understand it well.
If the module is genuine from Adafruit then it should definitely work, if not then once try this library https://github.com/olikraus/U8glib_Arduino
This library has very good documentation. Further if it does not work, attach the picture of wiring.

Its not every time fault of hardware, check the program as well. Load example test program and try again.
https://iotforgeeks.com/i2c-oled-display-not-working/
helped me to resolve the same issue.


text:
Why is my DHT22 sensor reading 1.00% humidity?
I have a seemingly simple problem but I haven't found a solution yet. I recently got a DHT22 temp/humidity sensor and I wired it according to the guide from Adafruit.
I downloaded and installed the library. I loaded the "DHTtester" example sketch. I also included the Adafruit Unified Sensor library to be safe, because the guide said I might need to. But when I upload the sketch and check the serial monitor the humidity value is always "1.00%". The temperature also seems to be off by about 4 degrees F.
I don't know what is going wrong here. I've removed the 10K resistor but nothing changed. Does anyone know why this might be happening? Any help would be appreciated. Thanks!

Without a diagram of your setup, and the code you're using, this is akin to reading tarot cards...

My setup is exactly the same as the one in the guide that I linked to. I'm using an Arduino Uno. First pin on the DHT22 is connected to 5V, second to 5V with a 10K resistor to digital pin 2, and fourth to GND.

Then barring a mistake in the code or setup, it might probably a hardware issue -- have you tried your DHT on another board?

When I have rigged up these sensors to test, I breathe on them. Both the temperature and humidity should rise as breath is warm and humid.
From memory, I have seen the humidity rise from ~40% to ~70%, and temperature by at least 5 degrees.
If you see temperature rise but not humidity, then the humidity part may not be working (perhaps as smajli suggests).
There is also a checksum in the data, so I imagine that if there was a problem with communications, the result would be -1 or nothing at at all.

I have 2 suggestions for you.

If you compare these 2 data sheets:
This one says "adafruit learning systems" on it
and this one is from the Adafruit website
, you'll see there is a discrepancy regarding the pull-up resistor value to use. One document says 10k ohm, the other says 1k ohm. It's a bit of a long shot, but you could try adding another 10k ohm resistor in parallel with the one you already have on the data line. This gives you an equivalent resistance of 5k ohm which works when used on a DHT11 sensor (cheaper, less accurate version of the DHT22).
There are several versions of the DHTxx library out there, so my next suggestion is to try a different one. You may have to remove the library you currently have installed before trying a new one.

I tried different resistors but humidity is still at 1.00%.The weird thing is that temperature is accurate, which makes me think that the humidity sensor is defective or broken.

After a year hanging outside my door in sunny/rainy/windy conditions my DHT22 gave up and shows 1%RH all the time. I don't recommend using it just like that. I have opened it and did some IPA cleaning. It sorted the problem for about a month. If your sensor wasn't stored in good conditions, it may be corroded/contaminated.

This problem mainly happens when DHT11 sensor is mistaken with DHT22 or vice versa. Try testing it for DHT11, can you send the picture of sensor and circuit connection if possible.

Definitely the DHT22, but I tried uncommenting different sensors anyway, and the readings were wrong.


text:
Interfacing Gammon's RS485 with computer
I'm using the non-blocking RS485 Gammon's library for Arduino (as shown at http://www.gammon.com.au/forum/?id=11428) to handle the communication between some arduinos.
Now I'm having trouble to add a Raspberry Pi (or otherwise a non-arduino platform) to the network.
How can I integrate the Gammon's protocol in a python or processing software?

Surely the Pi supports the C++ language?

Open-source and Web-search is just great. This might be what you are looking for.
Cheers!


text:
W5100 Ethernet shield DHCP fails with a Switch
we are using Arduino W5100 Ethernet shield. The code is to try DHCP first and if that fails, then try the static IP. we do the Ethernet Initialization and stop every time.  The library is Arduino Ethernet library.

when we try with a wireless router, everything works and we are able to contact our web server.
Now the wireless router is connected to a switch.
switch <======> router <=====> W5100

if we try to send data using the switch directly, DHCP fails, whereas a laptop using the same cable works.
Question is, even Arduino Library has DHCP functionality, why should a laptop work where the shield is failing? The network and topology and rules should be same for both the laptop and W5100 shield. Anything we can do to debug this issue more?
Edit1 : -  Switch which we are using is L3 in nature.
Below is the code which we are using at present.
    while(1) {

        KDEBUG("wait 10 seconds...\r\n");
        // wait 10 seconds
        for(loop = 10; loop > 0 ; loop--) {
            wait_millis(1000);
        }

        KDEBUG("Try transmitting data on ethernet...\r\n");
        transmit_data();

    }

    return 0 ;

}

void wait_millis(uint16_t num) {

    for(; num > 0 ; num-- ) {
        _delay_ms(1) ;
    }

}

// transmit data using Ethernet
static uint8_t transmit_data() {

    char request[256];
    uint8_t status = 0  ;

    // reset counter
    counter = (counter > 254) ? 0 : counter ;

    memset(&request[0], 0 , sizeof(request));
    memset(&bencode[0], 0 , sizeof(bencode));

    wait_millis(5000);
    // try DHCP
    if (Ethernet.begin(mac_address) == 0) {
        KDEBUG("Failed to configure Ethernet using DHCP \r\n");
        // use static IP. no return code.
        Ethernet.begin(mac_address, ip_address);

    } else {
        KDEBUG(" Got lease from DHCP \r\n");
    }

    // wait for ethernet to initialize:
    wait_millis(5000);

    // we got a connection?
    status = client.connect(server, port) ;
    KDEBUGF("ethernet client  status= %d \r\n", status);
    if(!status) {
        goto quit ;
    }

        KDEBUG("connected \n");
    // create an HTTP request
    strcat(request, "GET /api/gl868.php?data=");
    strcat(request,bencode);
    // 12 chars
    strcat(request," HTTP/1.1 \r\n");
    // 25 chars
    strcat(request,"Host: ");
    strcat(request,server);
    strcat(request," \r\n");

    // send GET request
    client.println(request);
    _delay_ms(1);
    client.println() ;

    wait_millis(1000);
    client.stop();
    wait_millis(1000);

    if(client.connected()) {
        client.stop();
    }

    return 1 ;

quit:

    wait_millis(100);
    if(client.connected()) {
        client.stop();
    }

    return 0 ;

}

What Arduino board?

@MikaelPatel - We are using Arduino Mega.

I have exactly the same problem with an arduino uno - it works fine plugged in to the router but not when plugged in via a switch (in fairness, a chain of switches) Fixed IP is fine and laptop DHCP is fine, it's just DHCP on the ethercard that is an issue.  I suspect that the ethercard.h library has a bug but I'm not good enough to find it. srj0408 did you ever find a solution?

If I understand your connection...

Device over wifi to router works.
Wired, via a switch to router does not?

DHCP is clearly switched on for WLAN, is it switched on for LAN?
Personally I always use fixed IP for such projects, with a default value that can be reset so that I can always find my device. I change the IP (and/or MAC) via a serial monitor.

The poster specifically says that a laptop connected via the same cable  works (which I assume means "gets a configuration via DHCP").

Even though i am using a static or fix IP for my ethernet shield, it is unable to send data to server. Of that, our switch is L3 in nature.

A certain way to debug this is to use tcpdump to capture network packets from both Arduino and your laptop and check the differences. I would start by looking for DHCPDISCOVER packet that Arduino should be sending.
A simpler way would be to check DHCP server logs to see how the communication looks like from server's perspective. Here, you should be looking for lines which have the MAC address of your Arduino shield. The success of this approach will depend of the verbosity of the DHCP server you're using.


text:
How to protect link/url form ESP-12E for controlling LED
I am using ESP8266 ESP-12E NodeMCU for controlling LEDs and Relay.
When ESP-12e power on it connect into my home wifi network and it gives IP address such as 192.168.0.104, and by that I can control my devices through Localhost.
I am using link or url to control my application such as
192.168.0.104/status1=1 (for starting LED 1 start)
192.168.0.104/status1=0 (for turn off LED)
but my point is how to secure 192.168.0.104/status1=1 or 192.168.0.104/status1=0.
Because it is open for all and however if some one do just for fun and turn off my Relays and LEDs it will be very risky for home application.
Here is my code, this code works very well:
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>

const char* ssid = "Asif Wifi";
const char* password = "asif0172";

ESP8266WebServer server(80);

const int output1 = D1;
const int output2 = D2;
const int output3 = D3;
const int output4 = D4;

boolean device1 = false;
boolean device2 = false;
boolean device3 = false;
boolean device4 = false;

void handleRoot() {
  //digitalWrite(led, 1);
  //server.send(200, "text/plain", "hello from esp8266!");
  //digitalWrite(led, 0);

  String cmd;
      cmd += "<!DOCTYPE HTML>\r\n";
      cmd += "\r\n";
      //cmd += "<title>ESP8266 Webserver</title>
\"ESP8266 Web Server Control\"
";
      cmd += "";
      cmd += "<meta http-equiv='refresh' content='3'/>";
      cmd += "";

      if(device1){
        cmd +=("
Device1  : ON");
      }
      else{
        cmd +=("
Device1  : OFF");
      }

      if(device2){
        cmd +=("
Device2  : ON");
      }
      else{
        cmd +=("
Device2  : OFF");
      }

       if(device3){
        cmd +=("
Device3  : ON");
      }
      else{
        cmd +=("
Device3  : OFF");
      }

      if(device4){
        cmd +=("
Device4  : ON");
      }
      else{
        cmd +=("
Device4  : OFF");
      }

      cmd += "\r\n";
      server.send(200, "text/html", cmd);
}

void handleNotFound(){
  //digitalWrite(led, 1);
  String message = "File Not Found\n\n";
  message += "URI: ";
  message += server.uri();
  message += "\nMethod: ";
  message += (server.method() == HTTP_GET)?"GET":"POST";
  message += "\nArguments: ";
  message += server.args();
  message += "\n";
  for (uint8_t i=0; i<server.args(); i++){
    message += " " + server.argName(i) + ": " + server.arg(i) + "\n";
  }
  server.send(404, "text/plain", message);
  //digitalWrite(led, 0);
}

void setup(void){
  pinMode(output1, OUTPUT);
  pinMode(output2, OUTPUT);
  pinMode(output3, OUTPUT);
  pinMode(output4, OUTPUT);

  digitalWrite(output1, LOW);
  digitalWrite(output2, LOW);
  digitalWrite(output3, LOW);
  digitalWrite(output4, LOW);

  Serial.begin(115200);
  WiFi.begin(ssid, password);
  Serial.println("");

  // Wait for connection
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");

  }
  Serial.println("");
  Serial.print("Connected to ");
  Serial.println(ssid);
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());

  if (MDNS.begin("esp8266")) {
    Serial.println("MDNS responder started");
  }

  server.on("/", handleRoot);

  server.on("/status1=1", [](){
    server.send(200, "text/plain", "device1 = ON");
    digitalWrite(output1, HIGH);
    device1 = true;
  });

  server.on("/status1=0", [](){
    server.send(200, "text/plain", "device1 = OFF");
    digitalWrite(output1, LOW);
    device1 = false;
  });

  server.on("/status2=1", [](){
    server.send(200, "text/plain", "device2 = ON");
    digitalWrite(output2, HIGH);
    device2 = true;
  });

  server.on("/status2=0", [](){
    server.send(200, "text/plain", "device2 = OFF");
    digitalWrite(output2, LOW);
    device2 = false;
  });

  server.on("/status3=1", [](){
    server.send(200, "text/plain", "device3 = ON");
    digitalWrite(output3, HIGH);
    device3 = true;
  });

  server.on("/status3=0", [](){
    server.send(200, "text/plain", "device3 = OFF");
    digitalWrite(output3, LOW);
    device3 = false;
  });

  server.on("/status4=1", [](){
    server.send(200, "text/plain", "device4 = ON");
    digitalWrite(output4, HIGH);
    device4 = true;
  });

  server.on("/status4=0", [](){
    server.send(200, "text/plain", "device4 = OFF");
    digitalWrite(output4, LOW);
    device4 = false;
  });

  server.onNotFound(handleNotFound);
  server.begin();
  Serial.println("HTTP server started");
}

void loop(void){
  server.handleClient();
}

Only need to know how to secure this system, that's it.
Thank you.
Dear Garben,
well I am trying in your way but I can not add variable and can not operate by operator..... Here is my code:
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>

const char* ssid = "Asif Wifi";
const char* password = "asif0172";

const char* pwd = "dada123456";

ESP8266WebServer server(80);

const int output4 = D4;

boolean device4 = false;

void handleRoot() {
  //digitalWrite(led, 1);
  //server.send(200, "text/plain", "hello from esp8266!");
  //digitalWrite(led, 0);

  String cmd;
      cmd += "<!DOCTYPE HTML>\r\n";
      cmd += "\r\n";
      //cmd += "<title>ESP8266 Webserver</title>
\"ESP8266 Web Server Control\"
";
      cmd += "";
      cmd += "<meta http-equiv='refresh' content='3'/>";
      cmd += "";

      if(device4){
        cmd +=("
Device4  : ON");
      }
      else{
        cmd +=("
Device4  : OFF");
      }

      cmd += "\r\n";
      server.send(200, "text/html", cmd);
}

void handleNotFound(){
  //digitalWrite(led, 1);
  String message = "File Not Found\n\n";
  message += "URI: ";
  message += server.uri();
  message += "\nMethod: ";
  message += (server.method() == HTTP_GET)?"GET":"POST";
  message += "\nArguments: ";
  message += server.args();
  message += "\n";
  for (uint8_t i=0; i<server.args(); i++){
    message += " " + server.argName(i) + ": " + server.arg(i) + "\n";
  }
  server.send(404, "text/plain", message);
  //digitalWrite(led, 0);
}

void setup(void){

  pinMode(output4, OUTPUT);

  digitalWrite(output4, LOW);

  Serial.begin(115200);
  WiFi.begin(ssid, password);
  Serial.println("");

  // Wait for connection
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");

  }
  Serial.println("");
  Serial.print("Connected to ");
  Serial.println(ssid);
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());

  if (MDNS.begin("esp8266")) {
    Serial.println("MDNS responder started");
  }

  server.on("/", handleRoot);

  server.on("/status4=1&password=" + pwd, [](){
    server.send(200, "text/plain", "device4 = ON");
    digitalWrite(output4, HIGH);
    device4 = true;
  });

  server.on("/status4=0&password=" + pwd, [](){
    server.send(200, "text/plain", "device4 = OFF");
    digitalWrite(output4, LOW);
    device4 = false;
  });

  server.onNotFound(handleNotFound);
  server.begin();
  Serial.println("HTTP server started");
}

void loop(void){
  server.handleClient();
}

Use something like 192.168.0.104/status1=1&password=12345 for at least some very basic security.

Gerben: Ok sir I going to test it.

Dear Gerben please check question again I just update next problem.

You need to take a look at the HttpBasicAuth example that comes with the ESP8266's ESP8266WebServer library that you are using. It is simple enough.
Here it is pasted in for reference:
#include <ESP8266WiFi.h>
#include <ESP8266mDNS.h>
#include <ArduinoOTA.h>
#include <ESP8266WebServer.h>

const char* ssid = "........";
const char* password = "........";

ESP8266WebServer server(80);

const char* www_username = "admin";
const char* www_password = "esp8266";

void setup() {
  Serial.begin(115200);
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);
  if(WiFi.waitForConnectResult() != WL_CONNECTED) {
    Serial.println("WiFi Connect Failed! Rebooting...");
    delay(1000);
    ESP.restart();
  }
  ArduinoOTA.begin();

  server.on("/", [](){
    if(!server.authenticate(www_username, www_password))
      return server.requestAuthentication();
    server.send(200, "text/plain", "Login OK");
  });
  server.begin();

  Serial.print("Open http://");
  Serial.print(WiFi.localIP());
  Serial.println("/ in your browser to see it working");
}

void loop() {
  ArduinoOTA.handle();
  server.handleClient();
}

The key part is this bit:
    if(!server.authenticate(www_username, www_password))
      return server.requestAuthentication();

Add that into your handler for your URL and it will ask for a username and password which you provide as www_username and www_password.
There's a more advanced example too if you want to delve deeper.

Ok..sir, Thank you. I will try it right now but I will tell you tomorrow.


text:
How to optimise TX power for ESP8266?
I have multiple ESP8266 units programmed using Arduino SDK and I would like each one of them to adjust the transmission power to lower the power requirements.
Arduino allows setting the TX power of the ESP8266 using the function WiFi.setOutputPower(), however it is not clear to me how to choose that value.
I know that RFM69 using the LowPower library has automatic gain control using the ACK packet sent by another RFM69 module. However, with ESP8266 there is a standard AP and a similar approach would not be obvious.
How can I perform optimal gain control?
This question is independent from the choice of the WiFi mode b/g/n using WiFi.setPhyMode().
Edit
An idea could be to detect AP station signal strength and transmit at a power level offset by a fixed amount, decreasing that delta by one tick at every wake up, until no connection is achievable. At that point the delta should be increased by an amount corresponding to a sort of hysteresis, to jump above the no-connection threshold, and kept.
After a predefined amount of successful wake ups, for example 100, the process of decreasing the calculated delta would be tried again.
For example: AP strength -60 dB, transmission +12 dB: success -> delta 48 dB is good.
Next wake up, delta 48.25 dB: is AP is at -55 dB, transmission would be 55-48.25 dB = 6.75 dB. If success, delta increased to 48.50 dB.

one issue with that algo as described is that it seems to ignore time. the relatively high-level of the wifi lib masks repeated connection attempts. Think of a ping with a 25% return rate, it's going to take at least 4X as much power to transmit the data 4 times. If you can get the quality to 50%, you'll use half as much wifi, and wifi is 80%+ of the ESP's current draw. in short, i would drop power until half my attempts took twice as long as other attempts, then tick it back a notch or two for one bounce connections.

Well the connection time is the first thing that can be monitored easily and if significantly higher than the one at maximum power, failure can be recorded.

Is the reason your WiFi.setOutputPower() link points to that "links2004" fork of the ESP8266 core for Arduino simply that the fork has better documentation of the function than the parent repo (esp8266/Arduino)?

@per1234 I found that one first

I would like ... to adjust the transmission power to lower the power requirements.

Is your goal to reduce overall/average power consumption, or peak current draw? If the former, then because of the high-level nature of the wifi API exposed by the ESP system, you may get a greater level of success by optimizing the time you are connected, rather than the power consumption.
That is, make sure WiFi radio is disabled while you are preparing whatever data you may wish to send over WiFi, then turn the radio on, connect+send, go back to sleep.
This blog post gives experimental details, but the gist is
In Setup():
WiFi.mode( WIFI_OFF );
WiFi.forceSleepBegin();
delay( 1 );

Just before you choose to connect:
WiFi.forceSleepWake();
delay( 1 );

// Bring up the WiFi connection
WiFi.mode( WIFI_STA );
WiFi.begin( WLAN_SSID, WLAN_PASSWD );

And, when you go to sleep, tell the system to keep the radio off by default:
WiFi.disconnect( true );
delay( 1 );

// WAKE_RF_DISABLED to keep the WiFi radio disabled when we wake up
ESP.deepSleep( SLEEPTIME, WAKE_RF_DISABLED );

Part 3 of this blog also notes that if you will continually be connecting to the same WiFi network, you can tell the ESP8266 to not spend the time loading the previous connection's details from flash memory, but requiring you to provide them in the connection call:
WiFi.forceSleepWake();
delay( 1 );

// Disable the WiFi persistence.  The ESP8266 will not load and save WiFi settings in the flash memory.
WiFi.persistent( false );

WiFi.mode( WIFI_STA );
WiFi.begin( WLAN_SSID, WLAN_PASSWD );

My idea was to add TX power control in addition to those steps, to get an even lower consumption: optimisation of connection time is something known.


text:
How to keep accurate millis() while using ADC_sleep mode?
millis() uses timer0 (linked to CPU clock) to count time, but ADC_sleep mode stops the CPU clock, therefore millis() will drift (lag behind) after each ADC conversion performed in ADC_sleep mode.
With the standard number of CPU cycles needed for the ADC conversion (ADC prescaler=128 multiplied by ADC clock cycles=13), and with the standard prescaler for timer0 (64), it would look like millis() loses 13.5 tics (about 0.1 ms) for every ADC conversion performed in ADC_sleep mode.
I could update the timer0 register (TCNT0) by increasing it manually by 14 but first of all I would still have a 0.5 ticks drift (or a bit less, since the update operation would take some cycles), second I would miss the overflow event (the one Arduino uses internally for time tracking) every time the ADC conversion is started with TCNT0 > 230.
How should I proceed to use ADC_sleep mode during ADC conversions but still keep millis() accurate?

Is this about SLEEP_MODE_ADC? And on what AVR/Arduino? A possible solution is to use Timer2 for the Arduino millis-ISR. See Cosa RTT for an example; https://github.com/mikaelpatel/Cosa/blob/master/cores/cosa/Cosa/RTT.hh (and files RTT.cpp, RTT_Config.hh)

Rather than trying to update TCNT0, it might be better to track the number of cycles lost to ADC conversions, and in an intermediate routine – eg, omillis() – compensate for those cycles. [Edit:  See better alternative, below]
In more detail:
• At each conversion, add about 128·13 cycles (or perhaps 128·13.5, to account for average prescaler delay) to a cycle counter:
long lostcycles; ...; lostcycles += ADCcycles;
• Within each omillis() call, say return millis()+lostcycles/16000
• Or perhaps say return millis()+lostcycles>>14 to avoid wasting time on a division.  This would be off by 2% on the correction, but I presume the correction is small, say 5% of total time, leading to about 0.1% error because of using a shift instead of a divide.

Re: “I would miss the overflow event (the one Arduino uses internally for time tracking) every time the ADC conversion is started with TCNT0 > 230”

That's incorrect [if using suggested approach].  Even if the timer 0 overflow is handled a hundred microseconds late, it will be handled ok. [As noted in Edgar Bonet's comment, a method that just adds to TCNT0 without checking arithmetic overflow, as in original approach, could miss a timer tick.]
Note, the example code using SLEEP_MODE_ADC in the “Sleep during reading” section of ADC conversion on the Arduino on Gammon Forum suggests that one should check for the case where a timer or other interrupt occurs during an ADC conversion.  While SLEEP_MODE_ADC stops clkI/O, clkCPU, and clkFLASH, it leaves Timer 2, WDT, and some other potential interrupt sources active.
A better alternative:
As Gerben points out, it's slightly cleaner to update the count variable maintained by millis(), rather than using an intermediate routine.  For background, refer to his answer to an earlier question.  Here is an adaptation [untested] of the idea to the current case:
unsigned int lostcycles=0;
...;
void accountForADC() {
  enum { ADCcycles = 13*128 + 64;  ms_cycles=16000 }; // adjust appropriately
  extern volatile unsigned long timer0_millis;
  lostcycles += ADCcycles;
  while (lostcycles >= ms_cycles) { // This loop usually runs one pass only
    byte statusReg = SREG; // Save interrupt status
    cli();                 // Turn off interrupts
    ++timer0_millis;       // Need interrupts off for atomicity
    SREG = statusReg;      // Restore old status
    lostcycles -= ms_cycles;
  }
}

After startup, on the tenth call to accountForADC() this code would add 1 to timer0_millis to account for a millisecond lost to ADC conversions. lostcycles -= ms_cycles would set lostcycles to 1280.  After another 9 calls we again add 1 to timer0_millis and reduce lostcycles; and so forth.

At the end keeping track of the number of conversions was my idea as well, thanks for confirmation (yours is cleaner than my idea)

@OlafM, thanks!  Note, I miscalculated the cycles to add -- 108 us is wrong units; I presume 13*128 = 1664 cycles is the number to use

You definitely can miss the overflow event if, along the lines of the OP's original idea, you do TCNT0 += 26; and that operation overflows.

@EdgarBonet, true!  Something the data sheet warns about.

My idea I was referring to one I had after writing, that is to subtract 0.1 ms times the number of conversions. This one keeping track of conversions*1664/16000 is more accurate.

@OlafM: Unless you reset the prescaler, the ADC conversion will take (1664 + some unknown number between 0 and 127) CPU cycles from ADSC to ADIF. C.f. the timing diagrams on section 24.4 of the datasheet.

If you don't want to have to change all millis call, you could actually increment the variable that is used by millis. Look at the bottom of my answer here.

@Gerben, thanks; I've edited that approach in at end of answer

@jwpat7 since timer0_millis is a 4-byte long, that is updated in an ISR, you need to update it atomically, or weird things may happen if the timer0 interrupt happens in the middle of your code changing the 4 bytes. In my code I temporarily disabled interrupts for this.

@Gerben, thanks for pointing that out... have edited answer accordingly

The time to start a conversion is not fixed. From my page about timers we can see this:

Tip:
There is an extra time before a conversion starts. The conversion starts on the leading edge of the ADC clock, not the moment the code asks for it. In the case of a scaler of 128, there could be 127 extra (processor) clock cycles added, because the hardware has to wait for the next ADC clock cycle. This could add 7.938 µs to the conversion time.

It looks like the prescaler can be reset by writing 0 to ADEN. According to the datasheet:

The prescaler starts counting from the moment the ADC is switched on by setting the ADEN bit in ADCSRA. The prescaler keeps running for as long as the ADEN bit is set, and is continuously reset when ADEN is low.

If you do that however then you add to the conversion time, as it will now take 25 ADC clock cycles rather than 13.

As others have suggested, if accurate time is what you want, then an external clock chip could well be the answer. The chip and parts are likely to come to a dollar or so.
An alternative would be to get an external ADC chip, thus moving the problem of noise-reduction to a chip which is (hopefully) designed to cope with it.
Another possibility would be to put an external clock input to Timer 1 and run that asynchronously. As I read the data sheet, that timer will keep running in ADC sleep mode, and thus you could use that for timing. (That wouldn't help with millis() and micros() but you could write something similar that used Timer 1).
Edit - as Edgar Bonet pointed out, I misread the datasheet. It is Timer 2 that can do this, not Timer 1. And the pins to run the timer asynchronously are not on the PDIP chip on the Uno, and are not brought out to board pins on the Mega.

Only Timer 2 can run asynchronously, at lest on the Uno and the Mega. And you cannot use the asynchronous mode on those boards because the required pins (TOSC1/TOSC2) are not available.

Whoops! Misread the datasheet. Corrected my answer, thanks.

I think you read the datasheet wrong. The conversion takes 13 ADC cycles (except for the first one), not 13.5.
Secondly; the conversion start at the next rising edge of the ADC clock, not directly. So because the prescaler is 128, it can take an additional 127 main clock cycles before the next ADC clock's rising edge. So that means and ADC conversion takes between 13 and 13.9921875 ADC clock cycles.
I'm also not sure how long it takes the uC to restart the CPU clock. So there might me more time "missed" here.
Though you must be aware that the crystal oscillator isn't that accurate to begin with.

In my mind I thought that the CPU clock would stop when the ADC actually starts, therefore the "from 0 to 127" cycles of delay was not considered. I see it's more complex than that.

I won't tell you how to do what you ask as I don't really know how to do
it. But I have the gut feeling that it can be done. Only it would be
really, really hard, so this brings the question: is it worth it?
To avoid posting a pure opinion-based answer, I'll try to give you some
leads:

You can set the timer 0 with single-CPU-cycle resolution simply by
resetting its prescaler whenever you set a new value.
You can make very precise delays with the _delay_us() function. The
argument should be a compile-time constant. _delay_us(0.125) does
exactly what it says it does.
Beware of the prescaler of the ADC clock: it will induce some jitter
on the ADC timings unless you reset it as well. AFAIK, the only way to
reset that prescaler is to start the ADC conversion using some trigger
source in auto-trigger mode. This may cost you a timer.
If you miss the overflow event, you can just manually call the
relevant ISR (TIMER0_OVF_vect(), which you declare with
ISR(TIMER0_OVF_vect);). Sounds silly, but it works, with the only
caveat that it forcibly enables interrupts upon return.

To know how many tics exactly you are loosing, you could spend a few
evenings carefully studying the timings in the datasheet, or you could
try to calibrate against a stable frequency source. I would recommend
the latter.


text:
How do we connect 2 FSR sensors to an Arduino Mega?
One can connect an FSR sensor (a force-sensitive resistor) to an Arduino via 5V, Gnd,  and A0 port (as below, according to an adafruit.com page), but how will it work for two of them instead of one?

Attach the second FSR mostly the same as the first, but connect the second analog voltage to A1 instead of to A0.
You can use several copies of  the circuit (below left) with each circuit's analog voltage going to a different analog-converter input (A0, A1, A2, ...).

To connect up multiple 5V and ground connections, you can:
•  use almost any popular shield
•  use breadboards like those illustrated above
•  cut and solder Dupont cables to add extra pins or sockets in or out (for example, cut two M-F Duponts in half, and connect both F halves to one M half)
•  connect to the extra 5V and Gnd pins on Uno or Mega boards.  (On a Mega, besides 5V and Gnd pins on programming headers, there are two 5V sockets next to 22 and 23, and two Gnds next to 52 and 53.)
The diagrams above right show the location of the 5V pins on the programming headers found on the Uno.  Most Arduino boards have at least one AVRISP header like that.

What about the Ground pin and the 5V? there only 1 5V

@user19846 see edit


text:
How can I reduce the redundancy of this code, so one function can perform the task of printing on Serial and Softserial?
void Multi_print (String str)
{
  Serial.print(str);
  mySerial.print(str);
 }

void Multi_println (String str)
{
 Serial.println(str);
 mySerial.println(str);
}

void Multi_parse_int (int value)
 {
    Serial.print(value);
    mySerial.print(value);
 }

I can't tell what your goal is: One function to replace all three? The same three functions but printing on any one Serial instead of on both ones? Or something else?

Just send your data to a tee: this is a type of pipe fitting where you
push the data through one end and it goes out through the other two
ends. As it happens, both Serial and Softserial (and almost anything
that can print()) inherit from the virtual Print class. You can
implement a tee as a Print that outputs to two Prints:
class Tee : public Print
{
public:
    Tee(Print &_p1, Print &_p2)
    : p1(_p1), p2(_p2)
    {}

    size_t write(uint8_t c)
    {
        size_t count1 = p1.write(c);
        size_t count2 = p2.write(c);
        return min(count1, count2);
    }
private:
    Print &p1, &p2;
};

The write(uint8_t) is the only method you really need to implement to
have a working Print. Then, all the print() and println() methods
will work.
Example usage:
Tee dualSerial(Serial, mySerial);
dualSerial.print("The answer is ");
dualSerial.println(42);

Note that parseInt() will not work, as it is not a method from
Print. But if you think twice, you will realize that parseInt() on a
pair of channels just does not make sense.

Very nice solution to the question as asked. :)

LOL, while Edgar was busy answering your question, I posted a github implementation called NeoTee which will tee any number of streams.  I have occasionally wanted such a class (attached at the end).  He has explained the approach nicely.
One quirk of the Arduino Print and Stream classes is that the flush method is in Stream, not Print.  So to provide that method in the NeoTee class requires deriving from Stream.  But Stream requires that you implement read, available and peek.  Although available can return the sum of the characters available on all Streams, the usefulness of read and peek is functional, but dubious.  ;-)
One example sketch is available in the library.  For your sketch, you would declare something like this:
Stream *streams[2] = { &Serial, &mySerial };
NeoTee tee( streams, sizeof(streams)/sizeof(streams[0]) );

And used thusly:
tee.print( '!' ); // prints one character to both
tee.print( 123.45 ); // prints a floating-point number on both

NeoTee implementation:
#ifndef _NEOTEE_H_
#define _NEOTEE_H_

//------------------------------------------------------
// NeoTee
// Copyright (C) 2016, SlashDevin
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//

#include <Stream.h>

// This library is like the UNIX "tee" command, which splits an output stream
// into two streams, but with N branches.  On the Arduino, an output stream is
// instance of the Arduino Print class, and the flush method is in Stream.
//
// Simply declare your own array of streams:
//
//     Stream *streams[2];
//
// Pass the array and its size in to the NeoTee constructor:
//
//     NeoTee tee( streams, sizeof(streams)/sizeof(streams[0]) );
//
// Any Stream operation on "tee" will be duplicated on all Streams in the array.
//
//     tee.println( F("This is sent to all Stream instances in the array.") );
//
// Because there is no base class with "begin" and "end" methods, you
//   must call those explicitly on the individual Streams (e.g., Serial.begin)

class NeoTee : public Stream
{
  Stream **Streams;
  uint8_t  NumStreams;

public:

  NeoTee( Stream **streams, uint8_t numStreams )
    {
      Streams    = streams;
      NumStreams = numStreams;
    }

  virtual void flush()
    {
      for (uint8_t i=0; i<NumStreams; i++)
        Streams[i]->flush();
    }

  virtual size_t write(uint8_t c)
    {
      size_t minWritten = 0;
      for (uint8_t i=0; i<NumStreams; i++) {
        size_t written = Streams[i]->write( c );
        if ((i == 0) || (minWritten > written))
          minWritten = written;
      }
      return minWritten;
    }

  using Stream::write; // make the other overloads visible

  virtual int available()
    {
      int total = 0;
      for (uint8_t i=0; i<NumStreams; i++)
        total += Streams[i]->available();
      return total;
    }

  virtual int read()
    {
      for (uint8_t i=0; i<NumStreams; i++)
        if (Streams[i]->available())
          return Streams[i]->read();
      return -1;
    }

  virtual int peek()
    {
      for (uint8_t i=0; i<NumStreams; i++)
        if (Streams[i]->available())
          return Streams[i]->peek();
      return -1;
    }

};

#endif

Very nice solution to the more general problem. :)


text:
LED Pin 13 Input or Output?
It is not clear to me whether Pin 13, corresponding to the LED, should be driven by an external voltage or not.
From the documentation,

LED: 13. There is a built-in LED driven by digital pin 13. When the
  pin is HIGH value, the LED is on, when the pin is LOW, it's off.

However, in the "Blink" example code I am running, the Pin 13 appears to be driven by the ATmega328:
void setup() {
  // initialize digital pin 13 as an output.
  pinMode(13, OUTPUT);
}

// the loop function runs over and over again forever
void loop() {
  digitalWrite(13, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(100);              // wait for a second
  digitalWrite(13, LOW);    // turn the LED off by making the voltage LOW
  delay(2000);              // wait for a second
}

If I now attach a voltage source to Pin 13, will there be contention issues?

Like any other I/O pin, there should be no problem driving this pin (and
thus the builtin LED) from an external source, as long as you make sure
it is in INPUT mode. If the pin is set to OUTPUT you will likely
damage the Arduino.
Warning: If you have the Blink example already loaded in the
Arduino, the pin is in output mode. Be sure to upload another program,
that does not set pin 13 to output, before connecting anything that
could drive pin 13.

It would be good defensive - and documentary - practice to explicitly set it to INPUT during setup() rather than depending on the default.


text:
strtok problem while parsing String
Here is my code. The incoming string is "*CRB12344,Temp25,Humidity55,CC5#"
I am unable to get value of Temp which is 25 and Humidity which is 55 and CC which 5. It only display the value of CR i.e B12344 (in this case). May be issue with strtok function?
String inputString = "";
boolean stringComplete = false, StartCapturing = false;

char inData[50];
char inChar, IncomingWeight;
char IncomingString[50];
const int httpPort = 80;

char *i, *k,*p;
String CardID;
int Temprature, Humidity, TC, CC;
byte SendData = 0;

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

void loop()
{
  serialEvent();

  if (stringComplete)
  {
    inputString.toCharArray(IncomingString, 50);
    Serial.println();
    Serial.println(IncomingString);

    i = strstr(IncomingString, "CR");
    {
      if (i)
      {
        p = i+2;
        CardID = strtok(p, ",");

        Serial.print("Card Number :");
        Serial.print(CardID);
        Serial.println();
      }
    }

    i = strstr(IncomingString, "Temp");
    {
      if (i)
      {
        Temprature = strtoul(i + 4 , NULL, 10);
        Serial.print("Temprature :");
        Serial.print(Temprature);
        Serial.println();
      }
    }

    i = strstr(IncomingString, "Humidity");
    {
      if (i)
      {
        Humidity = strtoul(i + 8 , NULL, 10);
        Serial.print("Humidity :");
        Serial.print(Humidity);
        Serial.println();
      }
    }

    i = strstr(IncomingString, "TC");
    {
      if (i)
      {
        TC = strtoul(i + 2 , NULL, 10);
        Serial.print("Total Count :");
        Serial.print(TC);
        Serial.println();
      }
    }

    i = strstr(IncomingString, "CC");
    {
      if (i)
      {
        CC = strtoul(i + 2 , NULL, 10);
        Serial.print("Current Count :");
        Serial.print(CC);
        Serial.println();

      }
    }

    stringComplete = false;
    inputString = "";
    delay(10);
  }

strtok() is a destructive function. It replaces the token with an end-of-string marker (\0). Thus once used the original string is irevocably lost.
Your first use of strtok() changes the string from:
*CRB12344,Temp25,Humidity55,CC5#\0

to:
*CRB12344\0Temp25,Humidity55,CC5#\0

Thus any future references to InputString only see up to the end-of-string marker:
*CRB12344\0

Instead you should use strtok() in a while loop to slice the string into tokens and examine what the token is:
char *tok = strtok(IncomingString, ",");
while (tok) {
    if (strncmp(tok, "*CR", 3) == 0) { // tok is *CRB1234
        // ... whatever ...
    } else if (strncmp(tok, "Temp", 4) == 0) { // tok is Temp25
        // ... whatever ...
    } else if (strncmp(tok, "Humidity", 8) == 0) { // tok is Humidity55
        // ... whatever ...
    } else if (strncmp(tok, "CC", 2) == 0) { // tok is CC5#
        // ... whatever ...
    }
    tok = strtok(NULL, ","); // Note: NULL, not IncomingString
}

Didn't know this. I understand the mistake now.


text:
Processing printing sensor readings and raising NaN exception at the same time
I am using pressure sensor with Arduino Uno within Processing.
Given these variables:
Serial myPort;              //the serial port
float sensorValue = 0;      //the value form the sensor

Arduino is printing float numbers on Processing console, according to the snippet below.
(...)

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

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

However, I am getting a NaN exception:
sensorValue = map(NaN, 0, 1023, 0, height);
how is this possible? printing numbers that aren't numbers?

//convert to an int and map to the screen height
sensorValue = float(inString);
You can't convert a String to a Float just like that by casting.  You have to interpret the characters within the String.  Oh, and a float isn't an integer.
All you're doing there is trying to cast the address of the String object to a float, which it really doesn't like, hence you get NaN.
Try:
int sensorValue;
sensorValue = inString.toInt();