text:
How to power Arduino Uno from L298N motor driver's 5v terminal?
I am trying to setup L298N motor driver controller with my Arduino. Different online schematics about how to connect them are mostly similar - but they differ in powering the Arduino from the drive controller's 5v pin.
I am connecting 7.5v to the Vin and Gnd to the motor driver controller screw terminal , and I wish the power the Arduino from the 5v screw terminal. Since I am planning to use the 5v screw terminal as output I am choosing to leave the 5v jumper on.
Here are 3 of the schematics I've found online,

Source Homemade-circuits:

This is what I was expecting to see. But from Arduino Uno Rev3 Faq,
Vin -- The input voltage to the Arduino board when it's using an external power source (as opposed to 5
volts from the USB connection or other regulated power source). You can supply voltage through this pin,
or, if supplying voltage via the power jack, access it through this pin.

5V -- This pin outputs a regulated 5V from the regulator on the board. The board can be supplied with power
either from the DC power jack (7 - 12V), the USB connector (5V), or the VIN pin of the board (7-12V).
Supplying voltage via the 5V or 3.3V pins bypasses the regulator, and can damage your board. We don't advise it.

This one looks wrong to me. I am under the assumption that Vin pin is expecting 7-12V because it's connected to voltage regulator which will cause a 2v drop. Which mean I should not connect 5v from the motor controller to Vin - making this schematic incorrect. Is my analysis correct? Here is an answer that says I can not use the 5v pin to power an Arduino since it an input pin and not an output pin.

Source teachmemicro:

This one looks ok to me since the 5v source at motor controller is a regulated source and that's what exactly Arduino is expecting on 5v pin based on aforementioned FAQ. Can I implement is safely?

Source Instructables:

I do not know if it's correct or not. Notice that the 5v screw terminal is not connected to Arduino in any way. Is it setup going to work? I am wondering where the Arduino is getting its power from?
I am wondering which schematic should I follow. I am hesitant to hook up my L298N motor driver and Arduino without without understanding why each schematic is choosing to power the Arduino differently.

Clearly, your design (last image) won't work, because as you expected, the Arduino won't have power. It is a feasible design however, if you use it while still developing and you have the USB cable connected. Because then the Arduino will draw the power for itself from there.
Vin expects 7-12V, but allows an unregulated input (which is fine for connecting a battery). You can use the 5V pin to supply power from a regulated output as well. Since (pressumably) the output of the motor driver is regulated, that could work, however I would not advise it and directly connect the battery to the VIn pin.
Connecting the 5V output of the motor driver to the VIn pin might work. While this will likely not destroy anything, it may be to low to drive the internal regulator, which might cause the Arduino to run on undervoltage levels. You might see weird behavior in that case (pins not correctly recognizing high from low, incorrect measurements on analog inputs or even software crashes).

If I understood it correctly, you are suggesting a 4th options which is connecting the motor drive controller and Arduino(using Vin and Gnd) in parallel to the 7.5v battery?

Yes, I would directly connect the Arduino to the battery.

Thanks! Also why you advise against connecting 5v regulated motor controller pin to Arduino 5v pin?

I should have said that it would be my second choice. The quality of the power output of the motor controler may vary, while the one on the Arduino is known to be built for it. Also, a motor controller is subject (from the motors) to severe interferences, which I would try to avoid by reducing the connections to it to the required minimum.

What are the things I should watch out for when connecting Arduino and other loads in parallel with the power source? Do I need to make sure that the resistance of the load is strictly greater than Arduino to ensure most current do not go through the load?

You do not normally have to worry about that, since the loads that require external power (such as a motor driver) are designed already to have a very high resistance input and drive the output trough a series of transistors. If you were to build your own motor driver, you would need to ensure this yourself, though.

If you connect 5V from the motor board to the 5V pin on the Arduino, the varying loads on the motor controller's 5V line could cause the 5V input to the Arudino to bobble around (Even a regulated output fluctuates some under varying loads). That is an argument against that approach. You might want to add a filter capacitor between 5V and ground and close to the Arduino if you use that approach. It will even out the noise on the 5V line caused by changing loads.

I was facing same problem but I solved it by attaching L298 power pins to icsp power pins

Remember the voltage should be constant and there should not be any fluctuation other wise atmega will go in programming mode

I happened to just set up a similar circuit yesterday on a RC car. L298 is powered through a 3S lipo batterie, Uno is powered through the 5v output which also powers a servo. Uno powers a rc receiver. I burnt an Uno trying to power both servo and receiver.

Please note the picture is the very first version when servo was powered from receiver and receiver from uno. Not a good option, sketchy servo behavior


text:
How can I set a calculated value when my sketch is uploaded?
I have an Arduino based countdown timer that counts down the number of minutes remaining to an event and displays them on an LCD. Since the event's start time is fixed, I have to re-calculate my countdown duration and update a constant in the sketch every time I upload it.
Is it possible to calculate the duration on the PC and set the starting value for the timer automatically? Perhaps using some kind of pre-compile script? Or perhaps through some kind of debugging features?
I'm not interested in adding RTC or other hardware to this project b/c (1) I don't have it handy and (2) there's very limited physical space in the already assembled project.
I'm currently using the Arduino IDE but I would be open to solutions that use other IDEs, or external components.

Send it through serial?

Using a RTC would be better in this case, as it always keeps time, even when the Arduino isn't powered.

i would just use an ESP8266 to fetch the actual time from the web onboot. if you use epocs, you can just subtract the fetched value from the stored value to get "how much longer". this works across reboots and is immune to internal counter rollover.

I am avoiding changing the hardware at this point b/c (1) I don't have it handy and (2) there's very limited physical space in the already assembled project. However the ideas are valid; for another planned project I will be adding both Wi-Fi and an RTC for exactly this purpose.

@JensEhrich: if you have wifi+web, you don't need an RTC, just load time on each boot, takes 2 seconds...

@dandavis I won't have guaranteed access to wifi, so setting with NTP and keeping time with battery backed RTC would probably be the most robust for me. If I can find a way to set via standard radio signals (similar to some watches/clocks) I would try that too

@JensEhrich: speaking of that, GPS modules can provide time... ;)

Why not add the DS3231 RTC?  It makes it simplicity itself, and they are easy to wire and are cheap.

@SDsolar Thanks, but I'm not willing to modify the hardware at this point. I have updated my question to emphasize that.

The C compilers provide two macros that resolve to string literals:  __DATE__ gives the time the file was compiled, and __TIME__ gives the current time of day. They output e.g. "May 31 2017" and "21:19:49"
You'd have to parse these string to get the time and do the calculations to get the remaining time.

PC's date is not likely to be set for the future, can you elaborate on how this plan operates?

You know the date and time of the event. You know the current time, through the __DATE__ and __TIME__ constants. Subtract the latter from the former, and you get the number of minutes remaining. (provided the device doesn't lose power, and uses the now wrong value of __DATE__ and __TIME__

This is pretty much exactly what I was after. It will certainly solve the problem for this scenario; I'm aware of the clock reset issue, and have a battery backup on the timer already.

I'd suggest using a time library to parse the string and to do the date difference math.

IIRC TimeLib.h can work directly with these macros.

Store your time acquired the way Gerben is describing.
If you have a fixed future date, add that date with the compilation date (and calculate the number of seconds/hours).
Note however, this only works when you don't reset your Arduino, or might expect a power loss in the future. If this can happens, store the current time + event time in EEPROM.
Also, add some seconds in case accuracy is important between the compilation time and time for uploading/resetting the Arduino.
Also take into account that the normal way to get time is millis(), and this might cause overflows when used in calculations. So use a second counter to convert/check for overflows and convert to minutes/hours for example.e

Also, millis will start back from 0 after around 50 days. So you have to work around that if you want your countdown to be more that 50 days into the future.

The tip for adjusting the seconds between compile and run is a good one, but I don't need that kind of accuracy here. The target duration is within the limits of millis() but I'm still tracking full hours with a separate counter anyway. Thanks Michel.

source: Stack Exchange

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

sort: votes


text:
square root of large number
I've got 2 int16_t numbers, say 388 and 10288, which are sensor readings from an accelerometer. I want to estimate the angle of the device on that, but seemingly there are some type overflow issues:
My final goal is this:
theta =  atan(-ax/sqrt((float)ay*ay+az*az));

The problem occurs in the bracket: ay^2 and az^2 are the 2 power of the given numbers. I recalculated with matlab and for the above example I get a^2+b^2 = 388^2+10288^2 = 105993488 what I get from the arduino however is 152848.
To be short: I don't know much about fixed point math or thelike and I couldn't find a sufficient answer to this: How do I calculate the square root term?

You need 2 typecasts. So
atan(-ax/sqrt((float)ay*ay+(float)az*az));

Otherwise it will use int16_t for the right side of the addition and overflow.
Though for speed you might want to typecast them as long (int32_t), as floats calculations on the arduino are really slow. The sqrt function will covert this double into a float for you.

Ah, so dumb, thanks!     'theta =  atan(-ax /sqrt((uint32_t)ayay +(uint32_t)azaz)) *RAD_TO_DEG;'
works! uint, because its squares, which are allways positive^^. Could you however explain to me how sqrt and atan work, when getting an int as input as here? Do they cast automatically? If so, which casts do they do (can I make that obvious by casting myself?)?

sqrt is part of math.h, and it accept a double. A float, in arduino and most cases, is a double. Why it automatically typecasts, I don't know. I would rather expect a compile error, but I don't know C. PS in my question I said double, but meant to say long (fixed in edit).

Because sqrt() and atan() are declared (in math.h) to be functions of double returning double (e.g. double sqrt(double x);), the compiler knows to cast a non-double argument to double before calling the function. Yes, you not only can write the cast explicitly; it is good practice to do so, making clear to the reader that you intended / were aware of the cast.

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


text:
Baud rate Arduino/Linux
I'm trying to communicate some numbers between a Linux program and my Ardunino Uno. To this end I wrote a C++ program which somehow contains:
#include <stdio.h>

int a,b;
a = 1;
b = 2000;

File* serial = fopen("/dev/ttyACM0","w");
fprintf(serial,"%d,%d\n",a,b);
fclose(serial);

Now out of standards I guess, the baud rate is 9600 bit/s. If I use stty -F /dev/ttyACM0 115200 I can change the baude rate of that port to 115200 bit/s. However the communication does not work anymore. My arduino program waiting for number,number does not show any action to the same code as before. Oh, and in the Arduino program of course I changed the code to serial.begin(115200);.
How can I change the baude rate in such a setup? If it is a concern, I'm using Ubuntu and an Arduino Uno.

Also take into account that default settings may mean that opening the port resets the Arduino.  There will then typically be a brief delay before the bootloader hands over control to your sketch, so anything your program writes immediately after a port-open-reset will be lost and never seen by your sketch.  You can add a delay before writing your data or change the modem control signal settings to not trigger a reset (or at least not trigger one on subsequent port openings).  Even more reliable might be to open the port bidirectional and wait to receive a ready prompt from the sketch.

Thanks for the highly relevant hint! Could you maybe elaborate more on how the reset trigger is called? Or where I can disable it?
At the time beeing a bidirectional opening is more hasstle, than service, but I'll have it in mind for the future.

Actually, I tried it again with exactly the same settings and it worked. It seems, as if Linux uses the settings of ssty, when referring to the "file" of a serial connection.
Thanks anyway!

Settings do tend to persist.  You may want to reboot your system and see that it still works, and isn't only working because of settings set up by some program you ran during your experiments.  Programs that use the serial port are split in behavior - some leave their settings behind, others (at least on a normal exit) will set things back however they found them.  Also be aware that the necessary difference from bootup defaults may be more than baud rate - there is a lot about word format and character mapping and special casing to contemplate, too.

Thanks, using stty -F /dev/.. I tried to verify the baud rate after a reboot, but it is reset to 9600 baud. I didn't use any other related programs to change settings. So I guess I have to write a script to change the rate at bootup.

Setting baud rates in a C program isn't a trivial task. You need to use the low-level open() instead of fopen() and act on the returned file descriptor with ioctl() or tcsetattr() / tcgetattr().  The former method allows the setting of non-standard baud rates while the latter only allows specific baud rates to be used.
I wrote a C++ class to deal with it all for me a while back. You are welcome to examine the methodology and/or steal whatever bits of it you like to use in your own program.

https://github.com/majenkotech/SerialPort


text:
Help needed to add and extra sensor
I am new to Arduino, and already tried to edit this many time. But I cant figure out whats wrong.
The following code has a PIR sensor, 1 LED and 1 buzzer.
I want to add one more PIR sensor, but it should trigger a separate LED , and the same buzzer. In serial monitor.
I have searched many sketches, but all of them seems to have a different method , cant figure out the basics!
int ledPin = 13;                // choose the pin for the LED
int inputPin = 2;               // choose the input pin (for PIR sensor)
int pirState = LOW;             // we start, assuming no motion detected
int val = 0;                    // variable for reading the pin status
int pinSpeaker = 10;           //Set up a speaker on a PWM pin (digital 9, 10, or 11)

void setup() {
  pinMode(ledPin, OUTPUT);      // declare LED as output
  pinMode(inputPin, INPUT);     // declare sensor as input
  pinMode(pinSpeaker, OUTPUT);
  Serial.begin(9600);
}

void loop(){
  val = digitalRead(inputPin);  // read input value
  if (val == HIGH) {            // check if the input is HIGH
    digitalWrite(ledPin, HIGH);  // turn LED ON
    playTone(300, 160);
    delay(150);

    if (pirState == LOW) {
      // we have just turned on
      Serial.println("Motion detected!");
      // We only want to print on the output change, not state
      pirState = HIGH;
    }
  } else {
      digitalWrite(ledPin, LOW); // turn LED OFF
      playTone(0, 0);
      delay(300);
      if (pirState == HIGH){
      // we have just turned off
      Serial.println("Motion ended!");
      // We only want to print on the output change, not state
      pirState = LOW;
    }
  }
}
// duration in mSecs, frequency in hertz
void playTone(long duration, int freq) {
    duration *= 1000;
    int period = (1.0 / freq) * 1000000;
    long elapsed_time = 0;
    while (elapsed_time < duration) {
        digitalWrite(pinSpeaker,HIGH);
        delayMicroseconds(period / 2);
        digitalWrite(pinSpeaker, LOW);
        delayMicroseconds(period / 2);
        elapsed_time += (period);
    }
}

What have you tried?  You basically just need to copy and paste the parts of the code that deal with the pir sensor and change the variable names in the copy to something else.  How much of the code that you have now do you actually understand?  If you understand what that code is doing, then repeating it for a second sensor should be trivial.

@Delta_G, I tried to add duplicate code inside 'loop' for different pins, but it didn't work. I was doing it virtually in https://circuits.io/

Please post your update (solution) as an answer, then accept it after a while, so we keep the usual question/answer(s) split of the site.

@jfpoilpret, OK

Well, after playing with the code for some time, I just did it!!
pasting the updated code here, may be useful for someone else like me..
int ledPin = 13;                // choose the pin for the LED
int ledPinB = 12;               // choose the pin for the LED 2
int inputPin = 2;               // choose the input pin (for PIR sensor)
int inputPinB = 4;              // choose the input pin (for PIR sensor 2)
int pirState = LOW;             // we start, assuming no motion detected
int val1 = 0;                  // variable for reading the pin status
int val2 = 0;                  // variable for reading the pin status
int pinSpeaker = 10;           //Set up a speaker on a PWM pin (digital 9, 10, or 11)

void setup() {
  pinMode(ledPin, OUTPUT);      // declare LED as output
  pinMode(ledPinB, OUTPUT);      // declare LED as output
  pinMode(inputPin, INPUT);     // declare sensor as input
  pinMode(inputPinB, INPUT);     // declare sensor as input
  pinMode(pinSpeaker, OUTPUT);
  Serial.begin(9600);
}

void loop(){
  val1 = digitalRead(inputPin);  // read input value
  val2 = digitalRead(inputPinB);  // read input value
  if (val1 == HIGH) {            // check if the input is HIGH
    digitalWrite(ledPin, HIGH);  // turn LED ON
    playTone(300, 160);
    delay(150);

    if (pirState == LOW) {
      // we have just turned on
      Serial.println("Motion detected!");
      // We only want to print on the output change, not state
      pirState = HIGH;
    }
  }
  else if (val2 == HIGH) {            // check if the input is HIGH
    digitalWrite(ledPinB, HIGH);  // turn LED ON
    playTone(300, 160);
    delay(150);

    if (pirState == LOW) {
      // we have just turned on
      Serial.println("Motion detected!");
      // We only want to print on the output change, not state
      pirState = HIGH;
    }
  }

  else {
      digitalWrite(ledPin, LOW); // turn LED OFF
      digitalWrite(ledPinB, LOW); // turn LED OFF
      playTone(0, 0);
      delay(300);
      if (pirState == HIGH){
      // we have just turned off
      Serial.println("Motion ended!");
      // We only want to print on the output change, not state
      pirState = LOW;
    }
  }
}
// duration in mSecs, frequency in hertz
void playTone(long duration, int freq) {
    duration *= 1000;
    int period = (1.0 / freq) * 1000000;
    long elapsed_time = 0;
    while (elapsed_time < duration) {
        digitalWrite(pinSpeaker,HIGH);
        delayMicroseconds(period / 2);
        digitalWrite(pinSpeaker, LOW);
        delayMicroseconds(period / 2);
        elapsed_time += (period);
    }
}

Link to circuit and virtual demo

Good job.  Thank you for sharing so we have this in the database.


text:
Utilizing two different serial ports simultaneously on a due
I am trying to understand how the serial ports are configured on the due board. Please correct me if i'm wrong, but to my understanding, the due has:

Four separate serial ports ("serial", and "serial 1-3"), each with SX and TX pin functions
A USB port paired with serial, simultaneously sending and receiving data from the serial function via USB protocol

I'm currently sending MIDI data over serial1 with the required baud rate of 31250. I want to configure another serial function (assumingly with a different baud rate to match the IDE serial monitor) in order to monitor Serial.print messages simultaneously for debugging.
In setup():
Serial1.begin(31250);  //MIDI baud rate
Serial.begin(115200);

and then, in a for loop i want to monitor each value i in the array loop1[i]):
Serial.print(String(loop1[i]) + " ");

However, i can't seem to make it work... My question is, is it possible to transmit the MIDI data via serial, in parallel with serial.print data with a separate serial function?

you should show your code. didn't you forget Serial.begin()?

Added some code

You can't use MIDI on Serial and use Serial.print at the same time. You can though use MIDI on Serial1 and use Serial.print at the same time (or Serial2 etc).

I am using midi on Serial1. Tried different variations of sending MIDI on Serial2, combined with Serial.print, Serial1.print or Serial3.print. No luck though...

Then there must be something else fundamentally wrong with your sketch.

Yeah, i have now been able to use Serial and Serial1 simultaneously. Your feedback answers my original question. Will look more into the function that i want to debug.

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


text:
Alternative to polling interrupt flag from main loop?
I am using an ISR, which is written to be as minimal as possible:
volatile bool interrupt1{};

void ISR1() {
    interrupt1 = true;
}

The interrupt is handled by polling the interrupt1 variable in loop():
if (interrupt1 == true) {

// Do stuff

interrupt1 = false;
}

Even though the interrupt signal coming in on the gpio isn't polled, the method described above is instead polling the interrupt variable from loop().
As an alternative to the above, is it possible to use some kind of push logic on the software side whenever an interrupt occurs, instead of continuously polling the interrupt variable? I hesitate to handle the full task from the ISR, as it's performing a lot of things.
What are my options here?

if (interrupt1 == true)  the true is redundant ... use  if (interrupt1) instead

volatile bool interrupt1{}; - what are the braces for?

@NickGammon This is an empty braced-init-list, I think blindly added or because of source code guidelines.

@Nick Gammon Uniform initialization

@jsotola I know it's redundant, but i prefer the verbosity in this case

Depending on what you need to do, you may reach the limits of what Arduino can do here, and you may be better off using an RTOS and threads (and queues or locks or mutexes to wait until the condition is met). On some platforms Arduino is built on top of an RTOS and there are libraries to expose that. No idea if that applies to the Teensy (though that possibly depends on which model).

If the task is pretty short and time sensitive, your best option is to
put it in the interrupt handler.
If the task is big and not too urgent (like: it could well wait for a
millisecond or so), your approach of polling the flag within loop() is
the best one, provided the main program is non-blocking.
If the task is both big and urgent... you may have a difficult problem.
You could try both approaches and see which one works best. Or you may
try to split the task into a top half (short and urgent) and a bottom
half (long but not so urgent). The interrupt handler would then perform
the top half and set a flag, whereas the main loop would poll the flag
and perform the bottom half.
Edit: for a short discussion on the top half / bottom half approach,
see the first paragraphs of this article on Linux kernel
development.

Thanks for your reply. Last portion is particularly interesting. I might be able to refactor the responsibilities for a better tradeoff between timing and heavy lifting, so to speak...

It can be tricky to think about what part of a task is "urgent". The ISR handler should take care of anything that will go wrong if you wait (like anything that's necessary to prepare the hardware for another event, if it arrives before you've finished with this one.)

Since you tagged it Teensy: You could also reduce the priority of the interrupt, so that it can be interrupted by higher priority interrupts. Thus you can implement interrupts with longer durations without blocking important system functions.
Here is an example using the GPT1 and GPT2 timers running at different priorities:
#include "Arduino.h"
#include "TeensyTimerTool.h"

using namespace TeensyTimerTool;

PeriodicTimer loPrioTimer(GPT1);
PeriodicTimer hiPrioTimer(GPT2);

void onLowPrioTimer() // some long task running from interrupt with low prio
{
    Serial.printf("  Start low prio isr @t=%d ms\n", millis());

    for (int i = 0; i < 10; i++)
    {
        Serial.printf("    lowPriority task %d\n",i);
        delay(10);
    }

    Serial.println("  Stop low prio isr");
}

void onHiPrioTimer() // high prio, will interrupt the low prio isr
{
    Serial.printf("high priority @t=%d ms\n", millis());
}

void setup()
{
    while (!Serial) {}

    loPrioTimer.begin(onLowPrioTimer, 500ms); // GPT1
    hiPrioTimer.begin(onHiPrioTimer, 50ms);   // GPT2

    NVIC_SET_PRIORITY(IRQ_GPT1, 128); // lowest prio
    NVIC_SET_PRIORITY(IRQ_GPT2, 16);  // high prio
}

void loop()
{
}

which prints:
high priority @t=1057 ms
high priority @t=1107 ms
high priority @t=1157 ms
high priority @t=1207 ms
high priority @t=1257 ms
high priority @t=1307 ms
high priority @t=1357 ms
high priority @t=1407 ms
high priority @t=1457 ms
high priority @t=1507 ms
  Start low prio isr @t=1507 ms
    lowPriority task 0
    lowPriority task 1
    lowPriority task 2
    lowPriority task 3
    lowPriority task 4
high priority @t=1557 ms
    lowPriority task 5
    lowPriority task 6
    lowPriority task 7
    lowPriority task 8
    lowPriority task 9
high priority @t=1607 ms
  Stop low prio isr
high priority @t=1657 ms
high priority @t=1707 ms
high priority @t=1757 ms
high priority @t=1807 ms
high priority @t=1857 ms
high priority @t=1907 ms
high priority @t=1957 ms
high priority @t=2007 ms
  Start low prio isr @t=2007 ms
    lowPriority task 0
    lowPriority task 1
    lowPriority task 2
    lowPriority task 3
    lowPriority task 4
high priority @t=2057 ms
    lowPriority task 5
    lowPriority task 6
    lowPriority task 7
    lowPriority task 8
    lowPriority task 9
high priority @t=2107 ms
  Stop low prio isr
high priority @t=2157 ms
high priority @t=2207 ms
high priority @t=2257 ms
high priority @t=2307 ms

This shows that the high priority timer (running at 50 ms interval) intercepts the low priority ISR which runs every 500 ms for about 100 ms.

Thanks for your reply. I've never used interrupt priority. Wanna elaborate?

@Erik  added an example

Very interesting, thank you!

What if an interrupt of the same kind occurs? For example, if it was counting something, wouldn't it miss a count increment (it presumably isn't a reentrant ISR)?

What baud rate was used for 'Serial'?

If an interrupt of the same kind occurs while the first one is serviced it will set the interrupt flag again and the isr will be called again (unless you delete the flag at the end of the ISR). However, this can not handle more than one interrupt request while an isr runs. Here some information about the ARM Nested Interrupt System: https://microcontrollerslab.com/nested-vectored-interrupt-controller-nvic-arm-cortex-m/

Baud rate: there is no such thing as a baud rate for "usb-Serial" aka CDC. The data will always be transmitted with the full USB bandwidth. (Up to some 20MByte/s on a T4x). Also, Serial.begin() is just some compatibility function. It used to be empty. These days it provides some waiting for connection code, I prefere a simple while(!Serial){}

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


text:
How to break out the due power supply and USB connectors?
I am planning a build with my own enclosure for the arduino due. As an alternative i would like to bypass the power jack and usb port that are factory soldered onto the board, in order to use jacks mounted on the enclosure, along with a power switch.
I've looked at the info regarding the boards pin configuration at https://www.arduino.cc/en/pmwiki.php?n=Main/arduinoBoardDue, and would appreciate if someone could confirm or correct this:

Can i use an external 9V adapter through a jack connected to the Vin and GND pins, respectively?

According to This question, you can't connect an alternative programming USB port to Serial 0 TX/RX pins (Mega board). If this applies to the due as well, what do i need to break out the programming USB port?

Edit: Perhaps one of these puppies is the least complicated solution?

You can't connect a USB socket or USB cable - but you can connect an FT232 adapter cable / board.

your Edit is the answer ... use pigtails for all connections ... insert a switch into the power pigtail

you could reprogram the ATmega16U2 to existing programming port and release the serial0 pins for your use ... or use the ATmega16U2 as a serial port gateway between JP5 and serial0

@jsotola Thanks for your input!

the first part of my comment sounds like nonsense ... i did not proofread it ... it should say something like you could reprogram the ATmega16U2 to stop being the programming port and release the serial0 pins for your use

so 1 - yes. the VIN pin has a common trace with the barrel jack, you can verify with a multimeter in continuity/beep mode. ive actually put power out through the barrel jack on a mega.
2- i cant find a clear schematic for the due at the moment, but on the mega the rx/tx pins are also common with the usb pins, thus they are not usable while plugged into usb


text:
How do i make this map() application work as intended?
I want to map the value range 0-63 like this:
x       y
0-15  = 0
16-31 = 1
32-47 = 2
48-63 = 3

However, using map function y = map(x, 0, 63, 0, 3); returns:
x       y
0-15  = 0
16-31 = 0
32-47 = 1
48-63 = 2

Is this due to truncating fractions, or something else?
Is there a better alternative?

you can use y = x  / 16

map() doesn't quite work as you'd expect.  The formula is:
(x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min

And all those values are long, which is a "long" integer. So all operations are done as integers, and that means that you lose an awful lot of precision in the calculation, since all decimal components are completely ignored.
It means that you only get the maximum output when you put in the maximum input.
As Michael Keijzers notes your expected output is x/16 (or x>>4 in bitwise notation), and that can be achieved with map() if you set the maximum input to be 48, not 63.
However a simple right shift 4 bits (or divide by 16 if the compiler is clever enough to implement it as a right shift) is a more efficient solution by far, since the processing involved is almost negligible, whereas multiplying and dividing is a relatively expensive set of operations.

Re “if the compiler is clever enough to implement it as a right shift”: it will do so only if the divided is unsigned, or if it can convince itself that it can never be negative.

You could try:
y = map(x, 0, 64, 0, 4);

Majenko showed you the formula used by map(). You can check that the
formula works nicely if you think in terms of half-open intervals:
[0, 64) → [0, 4)
But this is still way less efficient than a bit shift.


text:
How can I compensate for a joysticks offset value in neutral position?
I have a joystick that outputs the values 0 - 4095. I want to map these values in this fashion (Yes, the reversed mapping is intended):
outputValue = map(inputValue, 4095, 0, -2048, 2047);

However, the neutral central position of the joystick is offset, outputting 145 instead of 0.
Is there a way to map these values - taking the offset value in account - and still have the output values ranging from -2048 to 2047? I fail to do this with the map() function alone, and could need some help with the specific math involved.

your joystick may have a mechanical adjustment

You can only approximate it, you have to sacrifice something.
The basic problem is that your input range is asymmetric in respect to the mid point. Let's visualize it this way (with a bit of visual exaggeration):
min                     mid      max
0----------------------2193-----4095

Another problem is that the whole range 0..4095 may not be physically reachable by the joystick, so your usable range may actually look like this:
min                mid        max
433---------------2193-------3722

So, to calibrate your joystick, you need to measure the min, mid and max points that you can physically reach with exactly that joystick on the input scale (joysticks are analog devices, so their actual ranges can differ from joystick to joystick and even from axis to axis in the same physical joystick).
Now, if you have these numbers (I call those calibration values joy_min, joy_mid and joy_max), you need to map both parts of your range separately:
if( joy_input < joy_mid ) {
  output = map(joy_input, joy_min, joy_mid, -2048, 0);
} else {
  output = map(joy_input, joy_mid, joy_max, 0, 2047);
}

The downside is that any step in the output may represent a slightly different distance in the movement, depending on whether you are currently lower or higher than the measured midpoint. But I expect that to be negligible.
Also, keep in mind that this is only for one axis of the joystick. You may need completely different calibration values for the other axis. In addition, you may want to implement a "dead zone" around the midpoint, i.e. always returning output = 0 for joy_mid-10 < joy_input < joy_mid+10 or something like that.
And as the joystick range may drift (with temperature, age, etc...) and map does not constrain the output range, it might be a good idea to apply a output = constrain(output, -2048, 2047) afterwards.
(In my code, I assume that you want to map 0..4095 to -2048..2047 as you say in the text; but in your code, you map 4095..0 to -2048..2047, basically flipping the direction. If that part of your code is correct and the text is not, just swap -2048 with 2047 in my code.)

Thanks for your reply. With regards to the reversed mapping, it's intended. I've updated my question.


text:
How to find out whether an arduino can control a servo motor
I have a servo motor with following specs
Torque - 1.08Nm
Max rpm - 3000
Current rating - 7.8 amp
Max voltage - 56V DC
Please tell me how to calculate whether an arduino board - uno rev 3 can control the servo motor? If not, how to find out how many such boards are required?

Is it a standard 3-pin servo?

Generally something this big isn't going to be a 3-wire hobby servo but a large motor with some form of position encoder built-in to it. A link to a data sheet would clear this up.

Do you hace exact refs of your servo? That could help people answer.

Yes its a 3 pin servo. This is the link to the data sheet of the encoder HEDS - 5540 - A12
http://www.avagotech.com/docs/AV02-1046EN

The datassheet you have provided is of the optical encoder that can work fine with Arduino, but that is just to provide feedback of the location of the shaft. What about the motor? That is the part that will need high current so unless there is a driver you;ll have to add one.

Sorry, I forgot to provide this the last time. The datasheet for motor is
http://www.parvex.com/fichesmot/english/rx/rx320e.pdf

One important point that is not obvious from your question is "what do you want to control on this motor: speed, torque, angular position?" Then how it can be done (voltage level?) does not look clear to me from the datasheet.

Also, I don't know where you're getting "three pin servo" from, but that encoder alone is a 5-pin device, and the motor has two additional pins. At minimum (ignoring all the required control and driver electronics), you'd need 7 pins.

An Uno most definitely cannot directly control that motor. According to the specs here,

They operate at 5 volts. Each pin can provide or receive a maximum of 40 mA

So your motor has needs about ten times the voltage and 200 times the amps that the Uno can supply. Of course, you can always get a driver of some sort for the servo.

Agreed. However, I'm not sure any of the common driver chips will be suitable for this situation. I guess a MOSFET is requested in this case.

The optical encoder you link to has 500 pulses per revolution. This means at 3000rpm , you will be generating pulses 25,000 times a second. You will also need to deal with overshoot (as there is nothing worse than a motor going overspeed and the feedback loop being unable to detect it).
Dealing with an optical encoder generating pulses this quickly is actually quite a challenge, especially with Arduino (which has rather slow native I/O using digitalRead and digitalWrite), and the ATmega328 (which doesn't have any dedicated hardware to deal with high speed optical encoders).
Driving a 56VDC, 7.8A motor isn't an easy challenge either - a motor driver for this isn't going to be easy to design.
I'd probably look for a dedicated servo or CNC motor controller to deal with something like this.

You could probably manage 25K interrupts/second without too much trouble. You'd just need to wire the encoder a/b into the INT1/INT0 pins (and maybe use the pin-change interrupt for index). You'd have to write a decent interrupt handler, though. The ATmega328P may be capable of handling the encoder and servo duties, but there isn't going to be much arduino left in your code at that point.

You really need to manage a fair bit higher than that - overspeed could be as much as 50% on some systems, so 4500rpm. Then you have two sets of pins on the optical encoder. It's not impossible, but it is a lot of work. Other micros have functionality designed to deal with optical encoders and servos.


text:
Splitting Integers
I have bluetooth (HC-05) connected on Serial port of Arduino Mega and two TM1637, I am receiving Strings from an Android phone with an app with two Time picker (Fajar and Zohar)
I am sending time which is set by time picker in a formatted way.
The format is
< : Start of number delimiter.
ID : is the number 1 or 2 (1 for Fajar and 2 for Zohar), it indicates from which time picker the data has come.
HH : Hours, set from time picker.
MM : Minutes, set from time picker.
> : End of number delimiter.

Here in the example, first data which comes in is <10320> , which is starting delimiter "<" first digit "1" is the ID from Fajar time picker,03 Hours and 20 minutes and ending delimiter ">". Second data is <21830>, which is from Zohar time picker and vice versa.
I am parsing the incoming string and converting them into integers using the code found on Arduino Forum.
const char startOfNumberDelimiter = '<';
const char endOfNumberDelimiter   = '>';

void setup ()
 {
 Serial.begin (9600);
 Serial.println ("Starting ...");
 } // end of setup

void processNumber (const long n)
 {
 Serial.println (n);
 }  // end of processNumber

void processInput ()
 {
 static long receivedNumber = 0;
 static boolean negative = false;

 byte c = Serial.read ();

 switch (c)
   {

   case endOfNumberDelimiter:
     if (negative)
       processNumber (- receivedNumber);
     else
       processNumber (receivedNumber);

   // fall through to start a new number
   case startOfNumberDelimiter:
     receivedNumber = 0;
     negative = false;
     break;

   case '0' ... '9':
     receivedNumber *= 10;
     receivedNumber += c - '0';
     break;

   case '-':
     negative = true;
     break;

   } // end of switch
 }  // end of processInput

void loop ()
 {

 if (Serial.available ())
   processInput ();

 // do other stuff here
 } // end of loop

with the code above, i can convert string to integers and remove delimiters.
See output of the code in serial monitor.

Problem is : I have to separate ID and Hours and Minutes from that integer and wrap Hours and Minutes that up in
int8_t Digits [] = {1, 2 , 3 , 4 };

Here {1,2,3,4} is {H,H,M,M} Hours and Minutes which displays digits on one of the TM1637.
and also ID with "1" should change the digits on one of the TM167 and the ID with "2" should change digits on another TM1637.
Here is my full code :
#include "TM1637.h"

#define CLK1 2
#define DIO1 3

#define CLK2 4
#define DIO2 5

TM1637 Display1 (CLK1, DIO1);

TM1637 Display2 (CLK2, DIO2);

const char startOfNumberDelimiter = '<';
const char endOfNumberDelimiter   = '>';

void setup ()
{
  Display1.set ();
  Display1.init ();

  Display2.set();
  Display2.init();

  Serial.begin(9600);
  Serial.println ("Starting ...");
}

void loop ()
{
  if (Serial.available ())
    processInput ();
  fajar();
  zohar();
}

void processNumber (const long n)
{
  Serial.println (n);
}  // end of processNumber

void processInput ()
{
  static long receivedNumber = 0;
  static boolean negative = false;

  byte c = Serial.read ();

  switch (c)
  {

    case endOfNumberDelimiter:
      if (negative)
        processNumber (- receivedNumber);
      else
        processNumber (receivedNumber);

    // fall through to start a new number
    case startOfNumberDelimiter:
      receivedNumber = 0;
      negative = false;
      break;

    case '0' ... '9':
      receivedNumber *= 10;
      receivedNumber += c - '0';
      break;

    case '-':
      negative = true;
      break;

  } // end of switch
}  // end of processInput

void fajar ()
{
  int8_t Digits [] = {1, 2 , 3 , 4 };
  Display1.display (Digits);
  Display1.point(POINT_ON);
}

void zohar ()
{
  int8_t Digits [] = {1, 2 , 3 , 4 };
  Display2.display (Digits);
  Display2.point(POINT_ON);
}

Please Help
EDIT : Here is my edited code with Majenko shown technique.
#include "TM1637.h"

#define CLK1 2
#define DIO1 3

#define CLK2 4
#define DIO2 5

uint8_t fajar[4];
uint8_t zohar[4];

uint8_t address = 0;
uint8_t ptr = 0;

TM1637 Display1 (CLK1, DIO1);

TM1637 Display2 (CLK2, DIO2);
void setup ()
{
  Display1.set ();
  Display1.init ();

  Display2.set();
  Display2.init();

  Serial.begin(9600);
}

void loop ()
{
  int c = Serial.read();
  switch (c) {
    case '<': // Start of string - reset everything
      address = 0;
      ptr = 0;
      break;
    case '>': // End of string

       fajartime (); // Edited
       zohartime (); // Edited

      break;
    default:
      if ((c >= '0') && (c <= '9')) {
        if (address == 0) {
          address = c - '0';
        } else if (ptr < 4) {
          switch (address) {
            case 1:
              fajar[ptr] = c - '0';
              break;
            case 2:
              zohar[ptr] = c - '0';
              break;
          }
          ptr++;
        }
      }
  }
}

void fajartime ()
{

  Display1.display (fajar);
  Display1.point(POINT_ON);
}

void zohartime ()
{

  Display2.display (zohar);
  Display2.point(POINT_ON);
}

Thank you

You're thinking the wrong way. At the moment you are receiving individual characters, then combining them into a single integer, and then you want to split that integer back into individual characters. But you start with individual characters already. You don't need, nor want, to convert the string into an integer to then split it again.
If you take each character as it comes in as a separate number and store it separately you have no need for splitting.
For instance, you could have two 4-byte arrays for the two times. You don't need to store the first byte, since it's just an indicator of destination (we can call it a register address if you like).
A simple Finite State Machine for receiving in the correct way will make things easier:
uint8_t fajar[4];
uint8_t zohar[4];
uint8_t address = 0;
uint8_t ptr = 0;

int c = Serial.read();
switch (c) {
    case '<': // Start of string - reset everything
        address = 0;
        ptr = 0;
        break;
    case '>': // End of string
        // Do whatever with the data here
        break;
    default:
        if ((c >= '0') && (c <= '9')) {
            if (address == 0) {
                address = c - '0';
            } else if (ptr < 4) {
                switch (address) {
                    case 1:
                        fajar[ptr] = c - '0';
                        break;
                    case 2:
                        zohar[ptr] = c - '0';
                        break;
                }
                ptr++;
            }
        }
}

You could simplify things by combining zohar and fajar into a single 2D array keyed on the address (though take care that address never gets an invalid value in that case), or you can reduce memory usage by only having one 4-byte array if you don't care about keeping the data separate at all times (you use it and throw it away as soon as it's arrived).

Ahh! i have realized that, the code that i got from an Arduino Forum takes single characters from Serial and make an integer of that, I was thinking in a wrong way!
I am new to pointers, i haven't actually used it before - can you please check my code again.. i have edited the question.
thank you

Using void fajartime (); etc in the middle of your code isn't calling the function - it's defining the function prototype. Lose the void.

ohh! My bad, I have edited that again, Please check

Looks reasonable - though I don't know about the functions you use to display - if they take a 4-byte array like that or not.

Also you only really need to update the display for the address you have at the time.

That works! YAY! , How can i add more displays.? I can add more Time pickers with different address or IDs

Just add more arrays and matching address entries in the main FSM.

I'm not sure I know what you need help with.  You have code that reads a 5 character string from between .

If i == 1 you pass the remaining 4 characters to fajar.
If i == 2 you pass the remaining 4 characters to zohar.

You then need a function to convert the 4 characters into 4 separate integers.  You might need to map these integers onto a code that displays the correct lights or you might have a library to do this already.  (You already have the code for this function).  All you need to do then is push the number to the display.  That might be the problem you have, but how you do that depends on you library and connections.
TM1637 Displays[2] = {(CLK1, DIO1), (CLK2, DIO2)};
void loop()
{
    char buffer[1 + 5 + 1 + 1];
    buffer = readNumber (buffer);
    if (buffer[0] == '1')          // Treating as a character not a number.
        fajar(&(buffer[1]));
    else
        zohar(&(buffer[1]));
}
void fajar(char const* buffer) { displayValue(1, buffer);}
void zohar(char const* buffer) { displayValue(2, buffer);}
void displayValue (const int& displayID, char const* buffer)
{
    int numericValues[4];
    convertToNumbers (buffer, numericValues);  // The code in the switch statement.
    Display[displayID].display (numericValues);
    Display[displayID]..point(POINT_ON);
}

The above code is only a guide, never compiled and it is riddled with issues that could, if bad data was received, cause a major problem.  You are going to have to add error and bounds checking before you do anything more than dev test it, but it should work :)


text:
Disabling Timer2
I am working on a Heart Rate Monitoring project, using this Sensor from sparkFun, plugged to Arduino pro mini and reading proper BPM, I have an LED connected to pin 13 of my Arduino that blinks when the pulse happen.
The code given on SparkFun page works on Timer2
I have two more LEDs connected to pin12 and pin11, which indicates battery percentage - because i am powering my Arduino using a 2 cell lithium ion battery with Voltage regulator.. I also have a voltage divider circuit at the voltage regulator with 1K resistors and connected to analog pin A0 for monitoring battery voltage.
I have assigned LED connected on pin 13 as LED1, on 12 as LED2 and 11 as LED3
LED1 for low charge
LED2 for half charge
LED3 for full charge
Here is the problem :
When i connect charger ,Arduino reads data from voltage divider and outputs levels to LEDS
Here - LED1 is conflicting between the pulse sensor (which is working on Timer2) and also for indicating the low level charging, and LED1 is flickering.
how to overcome with this issue.? disabling Timer2 helps.? if'Yes' then how to do that.?
Note : I don't want to sample Heart Rate Pulse when charger is connected!
Thank you very much.
Best
void charging() {
TCCR2A = 0;
usbState = digitalRead(usb_detect);
while (usbState == HIGH) {
usbState = digitalRead(usb_detect);
// read the input on analog pin 0:
int sensorValue = analogRead(A1);
// Convert the analog reading (which goes from 0 - 512) to a voltage (0
- 3.3V):
float voltage = sensorValue * (3.3 / 512.0);
// print out the value you read:
if (voltage >= 2.5 && voltage <= 3.3)
{

  unsigned long currentMillis = millis();

  if (currentMillis - previousMillis >= interval) {
    // save the last time you blinked the LED
    previousMillis = currentMillis;

    // if the LED is off turn it on and vice-versa:
    if (ledState == LOW) {
      ledState = HIGH;
    } else {
      ledState = LOW;
    }
    digitalWrite(gps_led, ledState);
    digitalWrite(blinkPin, LOW);
    digitalWrite(save_led, LOW);
  }
}

if (voltage >= 3.4 && voltage <= 3.7)
{
  unsigned long currentMillis = millis();

  if (currentMillis - previousMillis >= interval) {
    // save the last time you blinked the LED
    previousMillis = currentMillis;

    // if the LED is off turn it on and vice-versa:
    if (ledState == LOW) {
      ledState = HIGH;
    } else {
      ledState = LOW;
    }

    // set the LED with the ledState of the variable:
    digitalWrite(blinkPin, ledState);
    digitalWrite(gps_led, HIGH);
    digitalWrite(save_led, LOW);
  }
}

if (voltage >= 3.8 && voltage <= 4.1)
{
  unsigned long currentMillis = millis();

  if (currentMillis - previousMillis >= interval) {
    // save the last time you blinked the LED
    previousMillis = currentMillis;

    // if the LED is off turn it on and vice-versa:
    if (ledState == LOW) {
      ledState = HIGH;
    } else {
      ledState = LOW;
    }

    // set the LED with the ledState of the variable:
    digitalWrite(save_led, ledState);
    digitalWrite(blinkPin, HIGH);
    digitalWrite(gps_led, HIGH);
  }

}

Serial.println(voltage);

delay(1);        // delay in between reads for stability

}
}

What code are you running? The "Getting Advanced Code"? Or something different?

I suggest you just change what pins you use for your LEDs. One function per LED. Trying to use one LED for two functions is a bit daft really. What do you want the LED to be - low charge, or pulse? Make your mind up.

Yes, I am running "Getting Advance Code" from SparkFun page..
I cannot change or add more pins to my system, it's sealed in an enclosure..

Timer 2 is fundamental to that code. It is used to sample the heart rate sensor at a regular period. If you disable that timer you will never sample the sensor.
You cannot have two functions on one LED - it makes no sense. You should decide on one and only one function to use that LED for. If you want to use it for the battery status then remove the code from the timer interrupt that controls the LED. If you want to use it to display the hear beat then you will have to make do with just two LEDs for your battery status.
If the two operations are mutually exclusive then yes you can disable the timer. Just turn it off, then turn it on again when you want sampling to start again.
Off:
TCCR2B = 0;

On (assuming you are using this
code):
TCCR2B = 0x06;

I can reset my Arduino using Software Reset when i disconnect the charger.
Which means i can disable timer when i connect charger and re-enable it when the arduino reset..?
Will this work.?

By the way! i don't want to sample Heart Rate pulse when i connect to charger.

See my edit....

Rather than clearing TCCR2A (the CTC mode), I would clear either TCCR2B (to stop the timer) or TIMSK2 (which leaves the timer running but disable the interrupt).

I have added TCCR2A = 0; in my code at charging(); ,Please see my edited question

I am unable to upload the code.
I have created a new call back function call charging(); when ever i connect charger, complier comes in this function. in the first line i have added TCCR2A=0;
and it didn't worked..
By the way, how can i upload my .ino file here.?

You don't upload code, you paste it into your question paying attention to markdown formatting.

@EdgarBonet I am not familiar with AVR timers. Feel free to edit my answer to change it to your suggestion.

Hey, I have not seen @EdgarBonet comment earlier, I have used TCCR2B = 0; and it seems to be working, I have to do some test to conclude..
Thank you very much.

Pease edit this answer, TTCCR2B = 0; worked :)
Thanks a lot

in the linked repo in the product page you linked there is a explanation page how to use the device without using timers buried at the bottom of a file:
https://github.com/WorldFamousElectronics/PulseSensor_Amped_Arduino/blob/master/PulseSensorAmped_Arduino_1.5.0/Timer_Interrupt_Notes.ino#L217
In essence instead of using the timer interrupt you put the sampling code in the loop() body triggered by a software timer and make sure that there are no delay() or busy loops happening in it.

I have used delay(); function in void loop

it's not that hard to rewrite the loop to avoid delay() though.

you provide lots of information that has nothing to do with your question, and at the same time omitted critical information that can help other help you.

how to overcome with this issue.?

the simplest would be to move the pins so they have their dedicated pins.

disabling Timer2 helps.? if'Yes' then how to do that.?

if you want to reuse the pins -> multiple functions on the same pin, you may have to code as such. For example, you disconnect the led briefly, read the pulse sensor, and then restore the led. if you do that sufficiently quick, you wouldn't notice that the led had been disconnected.
the feasibility of such approaches will depend on the sensors connected to that pin and your ability to code.


text:
Can I use NodeMCU 12E (ESP8266) as wifi shield for arduino Nano?
Update:
Point 1- I don't want to program ESP, I just want to use it as a wifi shiled. cause I'm not familiar with flashing or writing sketch for ESP, so still feel comfortable with arduino. beside my existing projects need to upgrade to wifi version. Not possible to turn everying into esp instead of arduino.
Point 2- If anyone can provide me a complete working sketch, where arduino sending a value to ESP, ESP receiving it and then sending to some data server (even sparkfun type will do).
I was working on Arduino based project for last couple of months, where I had to read several sesor data (e.g. temp, humidity, light, sound, motion etc) and save these data to a remote mysql server. I was doing well with Arduino Uno and Ethernet shield, where I connect through RJ45 cable to make my Arduino UNO able using internet.
here is the code for that:
#include <SPI.h>
#include <Ethernet.h>
#include <MySQL_Connection.h>
#include <MySQL_Cursor.h>

byte mac_addr[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };

IPAddress server_addr(1.1.10.);  // IP of the MySQL *server* here
char user[] = "root";              // MySQL user login username
char password[] = "007";        // MySQL user login password

// Sample query
char INSERT_DATA[] = "INSERT INTO database (message, sensor_num, value) VALUES ('%s',%d,%s)";
char query[128];
//char temperature[10];

int potPin = 4;
float temperature = 0;
long val=0;

EthernetClient client;
MySQL_Connection conn((Client *)&client);

void setup() {
  Serial.begin(115200);
  while (!Serial); // wait for serial port to connect
  Ethernet.begin(mac_addr);
  Serial.println("Connecting...");
  if (conn.connect(server_addr, 3306, user, password)) {
    delay(200);
    // Initiate the query class instance
    MySQL_Cursor *cur_mem = new MySQL_Cursor(&conn);
    // Save
    //dtostrf(50.125, 1, 1, temperature);
    sprintf(query, INSERT_DATA, "test sensor", 24, temperature);
    // Execute the query
    cur_mem->execute(query);
    // Note: since there are no results, we do not need to read any data
    // Deleting the cursor also frees up memory used
    delete cur_mem;
    Serial.println("Data recorded.");
  }
  else
    Serial.println("Connection failed.");
  conn.close();
}

void loop() {
  val = analogRead(potPin);
    temperature = (val*0.0048828125*1000);
    delay(2000);
}

Later, I found it's not convenient to use a whole bunch of cable around, so I was thinking to make it wireless. At beginning I was thinking of RF24OL but it also can't connect internet directly. Then I found ESP8266 module which can directly connect to wifi.
Now, I bought some ESP8266 12e (not ESP-01), which got one USB port to connect with computer, which made things way more sipmle comparing previous versions of ESP. I also installed ESP supporting files on my Arduino IDE, tested and it's working fine.
But, the problem is, whenever I upload the code only for ESP(like connectiong to wifi), it compile and upload proerply.
Like this code works:
void setup() {
  pinMode(BUILTIN_LED, OUTPUT);

}

void loop() {
  digitalWrite(BUILTIN_LED, LOW);

  delay(500);
  digitalWrite(BUILTIN_LED,HIGH);
  delay(300);

}

this also works fine,
/*
 *  This sketch trys to Connect to the best AP based on a given list
 *
 */

#include <ESP8266WiFi.h>
#include <ESP8266WiFiMulti.h>

ESP8266WiFiMulti wifiMulti;

void setup() {
    Serial.begin(115200);
    delay(10);

    wifiMulti.addAP("ssid_from_AP_1", "your_password_for_AP_1");
    wifiMulti.addAP("ssid_from_AP_2", "your_password_for_AP_2");
    wifiMulti.addAP("ssid_from_AP_3", "your_password_for_AP_3");

    Serial.println("Connecting Wifi...");
    if(wifiMulti.run() == WL_CONNECTED) {
        Serial.println("");
        Serial.println("WiFi connected");
        Serial.println("IP address: ");
        Serial.println(WiFi.localIP());
    }
}

void loop() {
    if(wifiMulti.run() != WL_CONNECTED) {
        Serial.println("WiFi not connected!");
        delay(1000);
    }
}

That means, my Arduino IDE, ESP8266 12e all got no problems. But whenever I add something more, like DHT11 library, it shows error compiling.
this code doesnt compile:
#define SSID       "Itead_1(Public)"                //type your own SSID name
    #define PASSWORD   "27955416"                                //type your own WIFI password

#include "uartWIFI.h"
#include <SoftwareSerial.h>
WIFI wifi;

extern int chlID;        //client id(0-4)

// for yeelink api
#define APIKEY         "3a362e99d6f1daf974561163a8c99a85" // replace your yeelink api key here

//replace the device ID and sensor ID for temperature sensor.
#define DEVICEID0       15483 // replace your device ID
#define SENSORID0       26660 // replace your sensor ID

//replace the device ID and sensor ID for humidity sensor.
#define DEVICEID1       15483 // replace your device ID
#define SENSORID1       26661 // replace your sensor ID

char server[] = "api.yeelink.net";   // name address for yeelink API

unsigned long lastConnectionTime = 0;          // last time you connected to the server, in milliseconds
boolean lastConnected = false;                 // state of the connection last time through the main loop
const unsigned long postingInterval = 5*1000; // delay between 2 datapoints, 5s
String returnValue = "";
boolean ResponseBegin = false;

int DHT11PIN=25;                        //Connect D25 to data pin of DHT11

int humidity;
int temperature;

int post_number;

void setup()
{

  wifi.begin();
  bool b = wifi.Initialize(STA, SSID, PASSWORD);
  if(!b)
  {
    DebugSerial.println("Init error");
  }
  delay(8000);  //make sure the module can have enough time to get an IP address
  String ipstring  = wifi.showIP();
  DebugSerial.println(ipstring);                //show the ip address of module

}
void loop()
{
  char message[400];
   // if you're not connected, and ten seconds have passed since
  // your last connection, then connect again and send data:
  if((millis() - lastConnectionTime > postingInterval)) {

  //read dht11
  int chk = dht11_read(DHT11PIN);
  if(chk==0)
  {
        if(post_number==0)
        {
                sendData(DEVICEID0,SENSORID0,temperature);
                post_number++;
        }
        else
        {
                post_number = 0;
                sendData(DEVICEID1,SENSORID1,humidity);
        }

  }

  }

  // if there's incoming data from the net connection.
  // send it out the serial port.  This is for debugging
  // purposes only:
  if(wifi.ReceiveMessage(message))
  {
      DebugSerial.println(message);
  }

  delay(10);

}

// this method makes a HTTP connection to the server:
void sendData(int device_id,int sensor_id,int thisData) {
  // if there's a successful connection:
  if (wifi.ipConfig(TCP,server, 80)) {
    DebugSerial.println("connecting...");
    // send the HTTP PUT request:
    String cmd;
        cmd = "POST /v1.0/device/";
        cmd += String(device_id);
        cmd += "/sensor/";
        cmd += String(sensor_id);
        cmd += "/datapoints";
        cmd += " HTTP/1.1\r\n";
        cmd += "Host: api.yeelink.net\r\n";
        cmd += "Accept: *";
        cmd += "/";
        cmd += "*\r\n";
        cmd += "U-ApiKey: ";
        cmd += APIKEY;
        cmd += "\r\n";
        cmd += "Content-Length: ";
        int thisLength = 10 + getLength(thisData);
    cmd += String(thisLength);
        cmd += "\r\n";
        cmd += "Content-Type: application/x-www-form-urlencoded\r\n";
        cmd += "Connection: close\r\n";
        cmd += "\r\n";
        cmd += "{"value":";
        cmd += String(thisData);
        cmd += "}\r\n";

        DebugSerial.println(cmd);

    wifi.Send(cmd);
    // note the time that the connection was made:
    lastConnectionTime = millis();
  }
  else {
    // if you couldn't make a connection:
    DebugSerial.println("connection failed");
    DebugSerial.println("disconnecting.");
    wifi.closeMux();
  }
}

int getLength(int someValue) {
  // there's at least one byte:
  int digits = 1;
  // continually divide the value by ten,
  // adding one to the digit count for each
  // time you divide, until you're at 0:
  int dividend = someValue /10;
  while (dividend > 0) {
    dividend = dividend /10;
    digits++;
  }
  // return the number of digits:
  return digits;
}

int dht11_read(int pin)
{
        // BUFFER TO RECEIVE
        int bits[5];
        int cnt = 7;
        int idx = 0;

        // EMPTY BUFFER
        for (int i=0; i< 5; i++)
        {bits[i]= 0;}[/i]

[i]        // REQUEST SAMPLE[/i]
[i]        pinMode(pin, OUTPUT);[/i]
[i]        digitalWrite(pin, LOW);[/i]
[i]        delay(18);[/i]
[i]        digitalWrite(pin, HIGH);[/i]
[i]        delayMicroseconds(40);[/i]
[i]        pinMode(pin, INPUT);[/i]

[i]        // ACKNOWLEDGE or TIMEOUT[/i]
[i]        unsigned int loopCnt = 10000;[/i]
[i]        while(digitalRead(pin) == LOW)[/i]
[i]                if (loopCnt-- == 0) return -2;[/i]

[i]        loopCnt = 10000;[/i]
[i]        while(digitalRead(pin) == HIGH)[/i]
[i]                if (loopCnt-- == 0) return -2;[/i]

[i]        // READ OUTPUT - 40 BITS => 5 BYTES or TIMEOUT[/i]
[i]        for (int i=0; i<40; i++)[/i]
[i]        {[/i]
[i]                loopCnt = 10000;[/i]
[i]                while(digitalRead(pin) == LOW)[/i]
[i]                        if (loopCnt-- == 0) return -2;[/i]

[i]                unsigned long t = micros();[/i]

[i]                loopCnt = 10000;[/i]
[i]                while(digitalRead(pin) == HIGH)[/i]
[i]                        if (loopCnt-- == 0) return -2;[/i]

[i]                if ((micros() - t) > 40) bits[idx] |= (1 << cnt);[/i]
[i]                if (cnt == 0)   // next byte?[/i]
[i]                {[/i]
[i]                        cnt = 7;    // restart at MSB[/i]
[i]                        idx++;      // next byte![/i]
[i]                }[/i]
[i]                else cnt--;[/i]
[i]        }[/i]

[i]        // WRITE TO RIGHT VARS[/i]
[i]        // as bits[1] and bits[3] are allways zero they are omitted in formulas.[/i]
[i]        humidity    = bits[0]; [/i]
[i]        temperature = bits[2]; [/i]

[i]        int sum = bits[0] + bits[2];  [/i]

[i]        if (bits[4] != sum) return -1;[/i]
[i]        return 0;[/i]

So, I decided to use ESP and arduino nano together. so that, ESP will work as wifi shiled to connect to internet, like ethernet shield was doing before, arduino will handle parts of sensors data reading and so on. I tried to connect to internet through connecting RX-TX and TX-RX between Arduino-ESP, but it doesn't work. I uploaded wifi connecting script to ESP and it connects to wifi properly, then i uploaded sensor data reading and saving to mysql script to arduino, then conneted arduino tx & rx to esp rx & tx. but arduino can't connect to internet.
Now, my problem is, how I can use ESP8266 12e NodeMCU only as ethernet shield so that my arduino can connect to internet and upload data to my sql server? My ESP will only act as a wifi shield, i don't want to configure esp to read sensor data, cuase it got lack of GPIO pins, most importantly it doesn't work as smoothly as arduino does. So please don't suggest me to use only esp with sensors, because i also wanted to upgrade my existing projects to wifi which done with ethernet shields.
Thanks in advance

If you are trying to send data to the server then I think that connecting tx-tx and rx-rx should maybe work. Or else you could write a code that reads Arduino's messages and sends it to the server.

I tried with both way, doesn't work. And don't know how to write code to esp that will read from arduino, or other way arond. do you have any working code sample? @ Sagnik Pradhan

I don't really have.

@hypocrite420 - The connections should be Tx to Rx not Tx-Tx.

It sounds like you have installed your own custom firmware into the ESP8266 and then are expecting to still be able to communicate with it as if it had AT firmware installed? Or have you written your own software in your sketch to manage the transfer of data from the Arduino to the ESP8266 for the ESP8266 to forward it on through the internet to your chosen server?

@Code Gorilla i tried bot Tx-TX and TX-RX, but no luck.

@Majenko first of all, this ESP can be done everythig as like other arduino. before that you have to add supportng scrits to Arduino IDE. then u can code like arduino. e.g, u can write blinking code same way as do2 arduino, compile and upload. when u upoad ur code, it overwrite existing firmwire on ESP. in my case, it works well when i try to connect or scan wifi networks. but doesn't work when i try to read data from dht11 sensor. so what i did, i put data reading code to arduino & wifi connection code to esp. i was expecting my arduino would b able to connct to server this way, but not

I know exactly what the ESP8266 is. If you look through the bundled examples in the ESP8266 core you'll find at least one written by me.  To use the ESP8266 with an Arduino board you have to have firmware installed in the ESP8266 that communicates with the Arduino. Normally the ESP8266 comes preinstalled with this firmware, called the "AI Thinker AT Firmware". Or you can write your own firmware to communicate between the two boards. Installing some random firmware that scans WiFi access points and connects to one will not allow communication with the Arduino because you haven't...

...written ESP8266 firmware that will communicate with the Arduino.

@hypocrite420 - Does the DHT library you are using work with an ESP?

@Majenko my bad, I'm pretty new and no idea whom i was talking with. sorry for that. btw, I thought u r the right guy to ask then. let me come to the point: No, i didn't write anything that will communicate between arduino and ESP. i just thought it would work like ethernet shield do, that's why connected TX-RX and RX-TX. however, i searched for codes and found a few with allow to talk between them. but i'm not clear to upload my data into mysql server where should i write my code, also how i would communicate? it would look like: Sesnore->arduino->esp8266->mysql. just don't know exact way.

The simplest method is to install the AI Thinker AT firmware and follow one of the many Arduino -> ESP8266 tutorials. Don't talk to MySQL - talk to a website which then performs the MySQL transactions for you (PHP, for example).

@Code Gorilla no, it's not. otherwise i would use esp directly skipping arduino nano part.

@Majenko my ESP exact version is NodeMCU 1.0 (ESP8266 12e), which got usb port to connect. I saw tons of tutorial where esp reading several sensors data and sending to webserver, buy in my case I'm getting always error "NodeMCU 1.0 compiling error". any idea or suggesstion to get rid of that? [i found a tutorial and followed it two remove older version folder from ..\Arduino15\packages\esp8266\hardware\esp8266 directory, but still having same error.] do i need to change sensor library file designed for ESP?

If it is just do get the values from the DHT to the SQL Server, the are a lot of sketch exambles out there using just the NODECPU

OK you have made it very clear that, you want to use the ESP as a serial to WIFI bridge.  You have a Node-MCU ESP12 board, which is normally configured for programming using Luna.

You need to have the correct firmware for this "AI Thinker AT Firmware" and you need to find the correct tool chain for loading this on your board.  It would be easier to but an ESP7 (or lower) to be honest that already comes with the correct firmware.
You want to communicate with the ESP from the Nano.  To do this you will need to use Software Serial on the Nano and cross connect the software serial port to the ESPs serial port.  You must not connect to the nano's serial port, you need this to program the nano.
To configure the ESP to talk to a wireless network you will need to send it AT commands (from the nano) these will need to be part of the setup of you program.  Technically this is programming the ESP, but I'm guessing you'll be OK with this.
Now you can add in your DHT-11 sensor and library and it will work.

However
You would find it so much easier to download the board support package for the ESP, take one of the Web server/client examples and add the DHT-11 code to that.  You'll find, since it is all written in the same dialect of C++ as the Arduino uses, very easy.  In fact the biggest problem you will have is finding something to weight the USB cable down to stop it from rolling the Node-MCU over.
BTW your code doesn't compile because you have left the italic mark-up tags in when you copied it off the website.  Try removing all the [i] and [/i] tags.

Gorila Thx a lot, I was exactly looking 4 somethng as specific as u mentioned. Let me search each steps as well try&see wht happened. Feels ur answer is more informative and very specific. beside everything let me answer few points based on ur steps: 1) I think the board got pre-installed firmware, and I used arduino IDE to program it instead of Luna. Tried ESploere to upload some .lua files, but for some unknown(to me) reasons failed. 2) Made sense. 3) my ESP working fine for conn. wifi or even the first code to send data to mysql server, just was not working when added dht11 library.

I was looking for sample and got two other threads whre which aimed to achieve similar goal: (1) https://arduino.stackexchange.com/questions/17787/communication-via-ip-adress-with-arduino-ide-and-esp8266?rq=1  (2) https://arduino.stackexchange.com/questions/35908/communication-between-two-esp8266?rq=1

UPDATE: If someone looking for easier solution: I got something better, where seems I don't need to use AT command everytime after flashing once: http://www.instructables.com/id/ESP8266-Wifi-Add-on-for-Arduino-Made-Simple/


text:
2 sensors, add delay between each reading
I have two temperature sensors, an MCP9808 and a DS18B20, connected to an arduino and I've read that it could be advantageous to set a small delay between temperature readings. What I wonder is where I should set the delay, in the setup function:
tempsensor.begin();                           //initialize communication with mcp9808
sensors.begin();                              //initialize communication with dc18b20
readSensors();

or the readSensors function?:
temp = tempsensor.readTempC();              //read current temperature and save value inside "temp"
sensors.requestTemperatures();              // Send the command to get temperatures
temp2 = sensors.getTempCByIndex(0);

As you can probably tell I am very new to all of this, intuition tells me that I should set the delay within the readSensors function.
Any alternative suggestions about how I should be readings temperature data from two different sensors connected to one arduino would be appreciated.
EDIT
after re-reading question and based on first answer I haven't made it unequivocally clear my intention; I want to delay the time between the mcp9808 and the ds18b20 temperature readings, so that it waits X seconds between each. I have read that this may help to reduce noise.

(After your EDIT): These are 2 different devices.  It is unlikely one affects the other.  That said, reading them back to back should be feasible.  The interval between reading the same device may be of concern. How fast you can do that may be in the specification sheets I linked to in my answer.  As for reducing noise?  As I said, these devices likely already implement some averaging.  If you do not mind the added delay, you could add more averaging in your code to further "smooth" out the temperature response.  Ask if you need me to add example of this in my answer.

your proposed delay only makes sense using analog sensors powered solely by the MCU and being read solely by the MCU, and depending on the MCU. Consider a nodeMCU that immediately sends a server it's reading; the power spike from the wifi transmit could jitter the ADC's ref voltage and affect the next reading. that should not be an issue in your setup.

The essence of your question is actually about managing processor to processor communications.  As the temperature sensors you have chosen appear as peripheral processors which communicate to your processor over SMBus (MCP9808) or 1-Wire bus (DS18B20).
Both temperature sensors actually abstract you from the details of (likely) thermistor Analog to Digital Conversion (ADC) sampling and (likely) exponential averaging over multiple samples in order to reduce noise by providing a digital communication interface.  As you can see, there may be many steps taken before the temperature data is available over the digital communication interface.  Each step takes a finite amount of time.
In almost all cases there is a microprocessor busy at work inside the temperature probe.  How well that processor's code is written dictates how much you can (skip reading the MCP9808 and DS18B20 specification sheet(s) and) "abuse" the protocol.
If you ask for the data faster then the temperature probe can obtain a new sample, in the best case, it is likely you will be supplied with duplicate values or values clearly designated as errors.  In the worst case, you may get back incorrect values indistinguishable from normal values.  Read the specification sheets and consider the source of the parts.
All this said, it may be that the 2 libraries you have chosen to use are not compatible.  Yes, one library is using the SMBus / I2C approach and the other is using the 1-Wire bus approach.  However, if both libraries use any single Arduino resource (for example a hardware timer or a hardware interrupt) at the same time, they may interfere with one another.
To test this, comment out the instantiation and code for one of the approaches and see if the other begins working as you expected in the first place.  Then repeat the experiment commenting out the other.
In the end, it is almost always better to use as few libraries as possible when assembling software for an Arduino.  There may be some effort to make some libraries work together.  But it is impractical to test all library combinations.  For this specific case, using several temperature devices of the same type (all using the same serial bus) and assigning different addresses to each would allow you to restrict your self to only including / using one library.

I'm waiting 30 seconds between requests. the reason for my concern is that the temperature readings for both sensors are almost perfectly correlated, on an absolute basis they're different but on a relative basis they follow one another so well I'm worried that they're in some way "working together" (as silly as this sounds). You mention the steps taken before the temperature reading is available, is there a way I can listen for this reading before moving on to the sensor reading of the ds18b20, or is this performed by default?

It is almost certain 30 seconds is long enough to wait.  Likely you need not worry until you get down to fractions of a second.  I work a lot with temperature sensors.  Often, when the ambient temperature is about 20C (~70F), I can cause a noticeable temperature change after a few seconds by just pinching my fingers around the probe or chip.  Alternatively, you can use a hair-dryer or a can of freeze-spray.  It is a good test, what you are doing, to validate the sensors independently.  As for when the data is actually ready, maybe there is something in the specification sheet that could help.

Ah, we all forgot to consider that you are using 2 different libraries.  And that they may not be compatible.  If you can not get "different" temperatures out of your 2 devices, consider my amended answer.

I've read that it could be advantageous to set a small delay between
  temperature readings

Although temperature is typically a measure that changes slowly in time, there is nothing in programming/device side preventing you from making readings in short intervals; unless this added time is necessary to prevent issues on other tasks, but so it should be not related to that.

Apologies please read my edit, hopefully clear now.


text:
Programmatically activate a specific Arduino
If I have multiple Arduinos plugged into the same computer, is there a way that I can control them both with the same script while also being able to select which one I want to control programmatically?
For instance, the pseudo code may look something like:
stop controlling Arduino2; // Make sure Arduino 2 is not listening
start controlling Arduino1; //Make sure Arduino 1 is listening
set pin 10 high; //Set pin 10 on Arduino 1 to high
stop controlling Arduino1; // Make sure Arduino 1 is not listening
start controlling Arduino2; // Make sure Arduino 2 is listening
set pin 10 high; // Set pin 10 on Arduino 2 high
Windows OS
Currently using Arduino built in language, open to using anything though.

What OS are you on? What scripting language are you using?

Each Arduino will appear as a distinct serial device to programs on the host.  It would be easiest to have something which "finds" all of them, and then keeps track of which is which so that it can talk to the desired one.  Giving each a unique response to a "who are you?" query would help.


text:
Pull EN pin of regulator to ground
I have an Adafruit Huzzah Feather with ESP8266 board, but I think my question will apply to most all boards (as most all have an onboard regulator). Most regulators have an Enable pin (EN) as does my Adafruit board. Apparently, I can shut down the regulator by pulling this pin low. I have a specific application where an external device will provide a high signal to me when I want the device to turn on, otherwise, I want it off at all times. So, what I have is a 1k resistor pulling the EN pin low, to ground. I tried other values 10-20k but they did not pull enough low to shut down the regulator. For example, 20k pulled me down from 3.3V to 2.6V but the regulator stayed on. On the other hand, 1k pulls me down to .3V on the EN pin and this shuts it down.
Then, when the external device gives me the high signal, which I have also tied to the EN pin, this will pull it back up and turn on the regulator.
This seems to be working just fine, but I wanted to ask if this sounds reasonable (I know this is a general question but I want to know if there is a better way). A specific, related question would be am I wasting too much power by using a 1k resistor when powered up or pulled high since some of the supply current will be dumped via the 1k resistor to ground.
UPDATE: In looking at the schematic on the Adafruit site, it appears that they have pulled EN to the input via a 10k resistor. So, I am fighting that which is probably why values over 10k do not pull it down enough to turn off. If I was doing the board design, I would have reversed this and pulled EN low by default but this is not the case when using the off the shelf board. So, I guess any value below 10k should work, like 4.7k? I guess I could also remove their pull up if I wanted to get really crazy. Thoughts on all of this?
Thanks!

A better solution would be to use a PNP transistor to control the EN pin. A PNP is ON when the input to it is LOW (or lower than the collector minus 0.7V, that is).
Take this circuit, for instance:

simulate this circuit – Schematic created using CircuitLab
When the GPIO is HIGH the transistor Q1 is turned off (GPIO >= VCC-0.7). Also if the GPIO pin is disconnected it is turned off because R3 pulls it up to VCC.
Set the GPIO LOW and Q1 turns on since the base is now lower than VCC-0.7V. With Q1 turned on it connects the EN pin to ground, so it becomes LOW.
If you replace the PNP with an NPN (there's more chance you have one in your bits box) you can basically invert the logic:

simulate this circuit
Now when the GPIO is LOW or pulled down by R3 Q1 is off and EN is pulled HIGH. Set the GPIO HIGH and Q1 turns on and connects EN to ground setting it LOW.
In both these scenarios the EN pin defaults to HIGH. If you want it to default to LOW until you activate the GPIO pin (i.e., during bootloader operation when the GPIO is in INPUT mode) you can reverse R3 so it becomes a pull-down (for the PNP) or a pull-up (for the NPN).


text:
Not able to get response from esp using Arduino uno
I am new to Arduino & ESP modules, here am trying to communicate with ESP-01 via Arduino UNO. I have gone through multiple websites for initial setup. But when i upload my code to UNO, ESP is not responding back.Below is the code i have used.
#include<SoftwareSerial.h>
SoftwareSerial ESP(0,1); // RX, TX
//ESP RX-->1(UNO) TX-->0(UNO)

void setup() {
// Open serial communications and wait for port to open:

    Serial.begin(9600);
    while (!Serial) {
        ; // wait for serial port to connect. Needed for native USB port only
    }

   // Serial.println("Goodnight moon!");

    // set the data rate for the SoftwareSerial port
    ESP.begin(9600);

}

void loop() {
      ESP.write("AT\r\n"); //Normally ESP responds to AT command with "OK"
    while (ESP.available()) {
        char inData = ESP.read();
        Serial.println("Got reponse from ESP8266: ");
        Serial.write(inData);
    }

}

Source: Link of the url
My observation on this is

ESP is blinking blue light when i reset UNO
UNO TX onboard LED is blinking
when i am trying to do  Serial.println("Goodnight moon!"); it is printing
Serial.println("Got reponse from ESP8266: ");         Serial.write(inData); is not printing

My questions are:

Is there any need to flash ESP with Firmware or is it default enabled.(i have 3 esp's with me all of them not responding with above code)
If no need then what is the possible mistake i am doing.

Here is the screenshot https://i.sstatic.net/mOklg.png
Note: I haven't used breadboard for connection, directly connected UNO-TX -> ESP RX and UNO-RX -> ESP TX, 3.3v VCC and ground.In the above screenshot on upload nothing prints, only when i type something "Got reponse from ESP8266: " is printing

Hi all i found out the solution after a long struggle. issue was with the ch_pd as per the ESP documentation ch_pd has to be active high that means it has to get 3.3v, only then it will communicate.
soon after that all my problems got cleared.thank you

There's a good chance your ESP and SoftwareSerial baud rates are not matched. The last handful of ESP-01s I bought came with default baud rates 115200. You may need to change yours to 9600 baud to use with SoftwareSerial. See my answer to a similar question.
Update:

tried all the available baud rates....!!Still the same issue..

Three possible issues come to mind:

Your terminal program must be at the same baud rate you set the ESP to.
SoftwareSerial is pretty much limited to a max of 9600 baud, although it can usually transmit successfully at 115200.
The serial connections must be cross-wired - Rx->Tx and Tx->Rx.

I think you had addressed 3) when you were trying to use pins 0 & 1, at least, as I read your comments. Together, 1) and 2) mean you'll need to use SS at 115200 to change the ESP's baud rate to 9600, then change SS to 9600 to carry on any further.
Also try moving the ESP.write("AT\r\n"); command to the setup() function. As your code is written, anytime the while loop finds no character waiting, the while loop will end and the loop() function will exit and restart, sending a new command to the ESP. Your code might never get a chance to print anything at all.

tried all the available baud rates....!!Still the same issue...

SoftwareSerial ESP(0,1); // RX, TX

Pins 0 and 1 are hardware serial on the Uno, used with the Serial object, these pins are used to communicate with your computer (e.g. Serial Monitor) via the USB-serial chip on the Uno.
There is absolutely no reason you should ever use SoftwareSerial with pins 0 and 1. If you want to use software serial then connect the ESP8266 to pins other than 0 and 1. Otherwise don't use SoftwareSerial at all, but be aware that using Serial to communicate with the ESP8266 and with the computer is problematic and can also cause issues when you try to upload to your Uno.

if i dont use SoftwareSerial how am i supposed to communicate with esp?my assumption is SoftwareSerial is a library to communicate with ESP.

SoftwareSerial is a library that allows you to do serial communication on pins that don't support hardware serial. Please take the time to study and understand https://www.arduino.cc/en/Reference/SoftwareSerial


text:
A4988 Vref too low
I'm driving a stepper rated at 5V/1.7A using an A4988-based driver circuit with a 12V power supply.  An Arduino controls the stepping sequence.
According to the datasheet for my A4988, I should be calculating Vref as:
Imax = Vref / (8 * Rs)  so,
Vref = I * (8 x Rs) (where Rs is 0.1 ohm on this particular board and confirmed with meter).
So, Vref should be (1.7A x .8) or 1.36V to drive 1.7amps.
The problem is, I cannot adjust the A4988 to get Vref up that high.
With the adjustment pot full swing, the best I can get is .9 to 1V.  When I energize and hold the motor and use an amp meter, the coil is drawing about .9 amps -- which is still less than the 70% of 1.7 Amps I would like (using full-step mode).
Is Vref potential limited by the input voltage of 12 volts?  Is there something else I'm missing?
Thanks in advance.
Added:  This is the circuit I am using:

Can you please provide your circuit diagram/schematic. I suspect your wiring is wrong.

Image of circuit added..

I see the circuit but not the adjustment pot referenced in the question, so can't answer yet.

The adjustment pot is built into the circuit board and came that way.  Rs is also built into the circuit.  http://www.elegoo.com/product/elegoo-stepstick-stepper-motor-driver-module-a4988-heat-sink-for-3d-printer-reprap-cnc-machine-or-roboticspack-of-5/

You have a 30K resistor divider in series with the trimmer. Change the 30K resistor for one rated at 27K to obtain those higher values. ;)


text:
The sensors don't send correct data
I try to make a weather station, but I don't understand why it doesn't work. I had tried to read a lot of the sensors but I doesn't find my errors.

The code:

 #include "DHT.h"
 #include "SFE_BMP180.h"
 #include "Wire.h"
 #include "MQ135.h"
 #include "SPI.h"
 #include "Adafruit_GFX.h"
 #include "Adafruit_ILI9341.h"
#define DHTPIN 2
 #define DHTTYPE DHT11
 DHT dht(DHTPIN, DHTTYPE);
SFE_BMP180 bmp180;
 double PresionNivelMar=1013.25;
int UVOUT = A3;
 int REF_3V3 = A1;
#define PIN_MQ135 A0
 MQ135 mq135_sensor = MQ135(PIN_MQ135);
#define TFT_DC 9
 #define TFT_CS 10
 Adafruit_ILI9341 tft = Adafruit_ILI9341(TFT_CS, TFT_DC);
void setup() {
  Serial.begin(9600);
  dht.begin();
  if (bmp180.begin())
          Serial.println("BMP180 iniciado correctamenten");
        else {
          Serial.println("Error al iniciar el BMP180");
        }
  pinMode(UVOUT, INPUT);
  pinMode(REF_3V3, INPUT);
tft.begin();
  tft.setRotation(0);
  tft.fillScreen(ILI9341_BLACK);
  tft.setTextColor(ILI9341_DARKGREEN);
  tft.setTextSize(2);
  tft.setCursor(70,20);
  tft.print("S.E.M.S.");
  tft.setTextSize(1);
  tft.setTextColor(ILI9341_WHITE);
  tft.setCursor(20,310);
  tft.print("Colegio Panamericana");
  tft.setTextSize(1.5);
}
void loop() {
  char a;
  double T,P,A;
  float h = dht.readHumidity();
  float t = dht.readTemperature();
  float rzero = mq135_sensor.getRZero();
  float correctedRZero = mq135_sensor.getCorrectedRZero(t, h);
  float resistance = mq135_sensor.getResistance();
  float correctedresistence = mq135_sensor.getCorrectedResistance(t, h);
  float ppm = mq135_sensor.getPPM();
  float correctedPPM = mq135_sensor.getCorrectedPPM(t, h);
Serial.println();
  Serial.print("Temperatura: ");
  Serial.print(t);
  Serial.print(" °C ");
  Serial.println();
  Serial.print("Humedad: ");
  Serial.print(h);
  Serial.print(" %RH");
  Serial.println();
a = bmp180.startTemperature();
  if (a != 0) {
    delay(a);
    a = bmp180.getTemperature(T);
     if (a != 0) {
         a = bmp180.startPressure(3);
        if (a != 0) {
                  delay(a);
                        a = bmp180.getPressure(P,T);
                 if (a != 0) {
                  A= bmp180.altitude(P,PresionNivelMar);
                 }
              }
           }
       }
Serial.print("Temperatura: ");
  Serial.print(T);
  Serial.print(" °C , ");
  Serial.println();
  Serial.print("Presion: ");
  Serial.print(P);
  Serial.print(" mb");
  Serial.println();
  Serial.print("Altitud: ");
  Serial.print(A);
  Serial.print(" m s.n.m.");
  Serial.println();
int uvLevel = averageAnalogRead(UVOUT);
  int refLevel = averageAnalogRead(REF_3V3);
  float outputVoltage = 3.3 / refLevel * uvLevel;
  float uvIntensity = mapfloat(outputVoltage, 0.99, 2.8, 0.0, 15.0);
Serial.print("Output: ");
  Serial.print(refLevel);
  Serial.print(" v");
  Serial.println();
  Serial.print("ML8511 output: ");
  Serial.print(uvLevel);
  Serial.print(" v");
  Serial.println();
  Serial.print("ML8511 voltage: ");
  Serial.print(outputVoltage);
  Serial.print(" v");
  Serial.println();
  Serial.print("UV Intensity (mW/cm^2): ");
  Serial.print(uvIntensity);
  Serial.println();
  Serial.print("MQ135 RZero: ");
  Serial.print(rzero);
  Serial.println();
  Serial.print("Corregido RZero: ");
  Serial.print(correctedRZero);
  Serial.println();
  Serial.print("Resistance: ");
  Serial.print(resistance);
  Serial.println();
  Serial.print("Corregido Resistencia: ");
  Serial.print(correctedresistence);
  Serial.println();
  Serial.print("PPM: ");
  Serial.print(ppm);
  Serial.println();
  Serial.print("Corregido PPM: ");
  Serial.print(correctedPPM);
  Serial.println("ppm");
  Serial.println();
escribir(14,40,1,"ILI9341_GREEN","Temperatura");
  escribir(14,60,0.6,"ILI9341_RED",String(t));
  escribir(14,60,0.6,"ILI9341_RED","°C");
  escribir(14,80,1,"ILI9341_GREEN","Humedad");
  escribir(14,100,0.6,"ILI9341_BLUE",String(h));
  escribir(14,100,0.6,"ILI9341_BLUE","%RH");
  escribir(14,120,1,"ILI9341_GREEN","Presión");
  escribir(14,140,0.6,"ILI9341_LIGHTGREY",String(P));
  escribir(14,140,0.6,"ILI9341_LIGHTGREY","psi");
  escribir(14,160,1,"ILI9341_GREEN","Calidad del Aire");
  escribir(14,180,0.6,"ILI9341_CYAN",String(correctedPPM));
  escribir(14,180,0.6,"ILI9341_CYAN","ppm");
  escribir(14,200,1,"ILI9341_GREEN","Radiación UV");
  escribir(14,220,0.6,"ILI9341_MAGENTA",String(uvIntensity));
  escribir(14,220,0.6,"ILI9341_MAGENTA","mW/cm^2");
}
int averageAnalogRead(int pinToRead) {
  byte numberOfReadings = 8;
  unsigned int runningValue = 0;
  for(int x = 0 ; x < numberOfReadings ; x++)
          runningValue += analogRead(pinToRead);
          runningValue /= numberOfReadings;
    return(runningValue);
}
float mapfloat(float x, float in_min, float in_max, float out_min, float out_max) {
  return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
}
void escribir(int X,int Y, int tam, short color, String mensaje){
  tft.setCursor(X,Y);
  tft.setTextSize(tam);
  tft.setTextColor(color);
  tft.print(mensaje);
}
Also I adds a little screen.
I make this:

Sorry for the size, the original image was too heavy to upload, in addition to the disorder.
I bought on: naylampmechatronics.com .
And I used his information.
And I read a bit of adafruit.com

In your fritzing drawing, use color coding with red=+, black=- and others when appropriate. Just using blue is to hard to figure out for me so I don't.

Some solderless breadbord have the power rail slit into two parts, left side and right side, check if that is the case.

i don't see the resistor for your raw DHT11.

Do you think it might help instead of just saying "I can't find the errors" to actually tell us what it does that is wrong or what errors you see?  Are we supposed to look at this and guess what it does and guess what you wanted it to do?

@MatsK I'm sorry for that.

@MatsK I tried to prove other form to connect the sensors.

@Delta_G I'm sorry but I tried to told I can't find the errors with the connections and the program because its doesn't work correct. Also I'm a beginner.

But you can tell us what are the symptoms right?  Look, you have some code and it does something.  You want it to do something else.  How can we help you if we don't know what those two things are?  You can draw a better schematic can't you?  There's lot you can do without knowing the exact error in your code to help us help you.  Something like, "I expect the light to come on when I press the button but it doesn't."  Does that make sense?

@dandavis My dht11 have a little board-controller with which I only connect direct.

@Delta_G sorry again, the dht11 sensor does not send data, the sensor bmp180 if it measures the pressure, but to correct it uses the dht11, so it does not correct, besides the ML8511 gives erroneous data, the mq135 if it works well but also corrects with the dht11, so it does not work well when corrected.

@Delta_G  I will make a new fritzing drawing.

OK.  Still waiting on that schematic.  Did you notice the comment by @dandavis?  Sounds like your main issue is with the dht11 and he spotted an issue with that.  Do you think you should address that issue?

NOT FRITZING.  They're impossible to decipher.  Just draw a schematic.

@Delta_G Yes, because I cannot see my errors. Fritzing I only use how place to draw the connections.

@Delta_G I have to changed a little of the post. Thanks for your tips.

Fritzing is the only way you know?  You don't know how to use a pencil and paper?

@Delta_G Jajajajaja, I have left all my materials at school.

The method for troubleshooting is: 1. Disconnect everything. 2. Add one sensor. 3. Verify if the sensor works. 4. If it works repeat step 2 for next sensor. 5 If it doesn't work, why? is it the connections correct?

The method for troubleshooting is:

Disconnect everything.
Add one sensor.
Verify if the sensor works.
If it works repeat step 2 for next sensor.
If it doesn't work, why? is it the connections correct?