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.

MCP9808 uses I2C; DS18B20 uses One Wire. Both are digital protocol that run on different pins and different wires: no cross talk and being digital, no noise. Or you read a temperature or you don't; there is no in-between.

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:
Using Interrupt on Arduino
I'm currently working on a project in which I'm supposed to make an Arduino car dodge any kinds of obstacles. I know how to do without using Interruptions but as I was searching online I found out that this is something that is used and would turn out better. Is it really possible? And if so, I don't exactly grasp the concept of using it to make (for example) the car stop once it senses an object. I know that it is supposed to be the first thing it will do if I program it that way but, can I program how the Interrupt will act upon the machine? And if so, how exactly?
Thanks

Interrupts help if an event needs to be dealt with over the time period of a few processor clock cycles. Such as the deployment of air bags.  If the accumulated delay of not responding in a few processor clock cycles adds up to considerable error.  Such as a Real Time Clock (RTC). Or, if an event is so short that it might be missed during periodic polling (checking). Such as counting flashes of lighting during a storm.
If this type of response time is not needed, interrupts may be more trouble than they are worth.
This is because interrupts can stop the processor from executing the normal program and force it to execute the interrupt program.  This can be very confusing to new programmers.  At any moment an interrupt may stop their program and possibly erase or change what that program was working on.  Both the program that is running and the interrupt program need to be written to tolerate this processor behavior.
It is almost always easier to "poll" the state of obstacle sensors (in this case) rather than tying its state to an "interrupt".  Using the Arduino paradigm, the purposes of the loop() entry point is to do just this.  A function which will be called over and over again.  Each time it is called you can "poll" the sensor and cause the model car to vier around an obstacle.

Yeah, your bot would have to be moving awfully fast to really need an interrupt to respond to an obstacle.  For most of these types of bots you have a few milliseconds to react.

See How do interrupts work on the Arduino Uno and similar boards?

I was searching online I found out that this is something that is used and would turn out better. Is it really possible?

That's very vague. What did you find online?

And if so, I don't exactly grasp the concept of using it to make (for example) the car stop once it senses an object.

Set a flag in the interrupt, which you detect in your main loop. In the main loop make the car stop when the flag becomes true.

Is it really possible?

anything is possible.

And if so, I don't exactly grasp the concept of using it to make (for example) the car stop once it senses an object.

all an interrupt does is to take the execution to a different place. in practical terms, an interrupt would execute some quick functions and set some flags for the main loop to execute.
interrupts are critical to embedded engineering and it is very difficult for a real-world code to run without interrupts.

source: Stack Exchange

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

sort: votes


text:
Audio.h Library Issues
I'm trying to incorporate audio into my Arduino project for the first time, and have been have a lot of issues. I originally couldn't get the Audio library to work, but after installing it through the Arduino application, I figured the Audio.h library would work fine. However, it spit out this error:

WARNING: library Audio claims to run on (sam) architecture(s) and may be incompatible with your current board which runs on (avr) architecture(s).
  In file included from /Documents/Arduino/libraries/Audio/src/Audio.h:16:0,
                   from /Documents/Arduino/boxgame/boxgame.ino:1:

Then it lists plenty of syntax issues, none of which have to do with my code. I think it's giving errors from the library, but I'm not really sure what's happening. Here's an example of one of the slew of errors:

/Users/tschadius/Documents/Arduino/libraries/Audio/src/DAC.h:37:2: error: 'IRQn_Type' does not name a type
    IRQn_Type isrId;

Any ideas as to how I can fix this? The error message goes on for quite a while, but none of them appear to be from my code that I've written.
Thanks!

Need a bit more information to be able to answer this.  Which particular board are you using?

Using a SparkFun redboard, which is essentially identical to the uno!

The Uno cannot use that library. The Uno has no DAC.

Occasionally people do not realize how many platforms the Arduino paradigm has been ported to.  In almost all cases the ported to platform far exceeds the features found on an Arduino Uno.  So there exists a considerable amount of software that can not run on an Arduino Uno or on an Arduino Uno with out additional hardware.  But, usually, such software is surrounded by "text", "web-pages" and other "readme"  type files explaining the situation.
For the Arduino Audio library, the web-page says this:

Audio
Compatible with Arduino Due only
The Audio library enables an Arduino Due board to play back .wav files
  from a storage device like an SD card.
The Due uses the DAC0 and DAC1 pins to play sounds.

Thank you, I really appreciate your comment. I'll be sure to be more thorough about reading all associated documents next time.

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


text:
Wifi radio with an Arduino
I've done a Wifi radio with a headless Raspberry Pi in the past (connecting a radio MP3 stream available on internet directly on boot, without any user input), and now I'm wondering: would it be possible to do the same with an Arduino, battery-powered?
Please correct me if I'm wrong but it seems that all these features are available:

battery-powered: this is definitely possible with a few AAs
audio output (easily possible with a DAC I think?)
Wifi (possible with a shield, right?)
Internet access to http://198.51.100.0/myradio.mp3 stream
real-ime MP3 stream decoding (Is an Atmega enough for this?)

Does this mean that a Wifi radio based on Arduino is possible?

real-ime MP3 stream decoding (Is an Atmega enough for this?) -- Certainly not, no.  I have managed it with a 200MHz PIC32. I wouldn't even begin to consider doing it with a tiny 8-bit MCU...

@Majenko I looked at ESP8266, and it seems possible. Is this really true, or do you think it relies on additional hardware chip?

Have you read the readme?

After re-reading now, yes it seems it's possible without any other chip, but not recommended (RAM is a plus for buffering and DAC for better output quality)

I have/had a wifi radio in the OpenWRT part of a Arduino Yún. OpenWRT is a minimal linux. For software decoding, I strongly advise to use some kind of linux computer, because they already have packages for mp3 decoding. There are Arduino projects using the VS1053 as a hardware MP3 decoder. An Arduino board with Ethernet Shield uses a lot of power, that is not something for a battery. What about an ESP32 with a hardware MP3 decoder ?

There are many types of Arduino boards (reads: many different platforms and processors) and many Arduino hardware add-ons.  If you spend enough, eventually you may find a platform and / or hardware combination capable of supporting your feature list.  However, it is likely the RaspberryPi will be able to support your feature list for far less money.  Certainly in much less time and effort.

if the ESP8266 looks possible, the ESP32 should be a lot better, what with it's dual-core and all...


text:
COM port problem when uploading bootloader to SAMD21G
I use an ATSAMD21E16B-AU in my circuit and I want to upload the bootloader with the SAM-BA flash programming tool in this official link:
http://www.atmel.com/Images/Atmel-42366-SAM-BA-Bootloader-for-SAM-D21_ApplicationNote_AT07175.pdf.
I will use that directly with USB cable signals D+, D-, 5V, GND (SAMD microprocessor has internal USB serial hardware and D+ D- pins)
Before I try to upload it, it needs to appear in Device Manager on Windows as a "COM port" with EDBG driver. Because it didn't, SAM-BA doesn't show any COM port as EDBG in the "Select the connection" section.
Can I burn a bootloader to ATSAMD without an JTAG device? For example, I want learn if I can do that with Arduino Zero?

External condition: Reset the part and make sure the Hardware Bootloader Entry pin (PA15) is pulled low
when reset is released.  e.g. push button then apply power.

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


text:
Changing the order of blinking LEDs with the push of a button

I am new to Arduino and I have written code that makes 3 LEDs blink while the push button is off, so the lights are blinking from left to right (1,0,0)(0,1,0)(0,0,1) and then repeat from left to right.
Now I am trying to modify this code so that whenever the system receives a High from the switch it reverses the order, so it should start blinking from right to left and keep blinking that way until I press the push button and then return to left to right.
I hope my issue is clear. I only know how to use the if & else.
Here is my code:
int switchState;
int switchst = LOW;
int d=LOW;

void setup() {
  pinMode(3,OUTPUT);
  pinMode(4,OUTPUT);
  pinMode(5,OUTPUT);
  pinMode(2,INPUT);
}

void loop() {
  switchState = digitalRead(2);
  if (switchState == HIGH) {
    d= ~d;
    if(d==LOW) {
    digitalWrite(3,~switchst);
    digitalWrite(4,switchst);
    digitalWrite(5,switchst);
    delay(200);
    digitalWrite(3,switchst);
    digitalWrite(4,~switchst);
    digitalWrite(5,switchst);
    delay(200);
    digitalWrite(3,switchst);
    digitalWrite(4,switchst);
    digitalWrite(5,~switchst);
    delay(200);
  }  else {
    digitalWrite(3,switchst);
    digitalWrite(4,switchst);
    digitalWrite(5,~switchst);
    delay(200);
    digitalWrite(3,switchst);
    digitalWrite(4,~switchst);
    digitalWrite(5,switchst);
    delay(200);
    digitalWrite(3,~switchst);
    digitalWrite(4,switchst);
    digitalWrite(5,switchst);
    delay(200);
  }
}

The problem with this code is that it doesn't keep blinking if I release the push button.
This is the old code. It only goes from left to right and keeps repeating.
int switchState = 0;
int switchst = LOW;

void setup() {
  pinMode(3,OUTPUT);
  pinMode(4,OUTPUT);
  pinMode(5,OUTPUT);
  pinMode(2,INPUT);
}

void loop() {
  switchState = digitalRead(2);
  if (switchState == switchst) {
    digitalWrite(3,~switchst);
    digitalWrite(4,switchst);
    digitalWrite(5,switchst);
    delay(200);
    digitalWrite(3,switchst);
    digitalWrite(4,~switchst);
    digitalWrite(5,switchst);
    delay(200);
    digitalWrite(3,switchst);
    digitalWrite(4,switchst);
    digitalWrite(5,~switchst);
    delay(200);
  } else {
    digitalWrite(3,switchst);
    digitalWrite(4,switchst);
    digitalWrite(5,switchst);
  }
}

You need to learn more constructs than if and else.  Learn to use a loop, you can then blink the LEDs in an infinite loop, with less and cleaner code too.

hi thanks for your comment I have done it in the class with only if & else but I forgot how and I am only allowed to use if and else.

You also need to present code properly indented for legibility. Use blank lines only to separate logical sections. I've edited the first few lines for you ... and you've just overwritten the changes with a simulataneous edit. Oh well!

The first thing I saw was a cartoon where apparently a schematic should have been.  Not gonna look at the rest, so closing as unclear.

What on earth are you studying if you're not allowed to use loops?

@Oskar Skog - The requirement for a student to "only use if else" to solve a problem is common when people are first learning how to write code. It's possible that Bro JJ has not been taught how to work with "loops" yet. That may be tomorrows lesson.

I'm voting to close this question as off-topic because it's a generic programming problem, not Arduino specific.

The easiest is to use a 'mode', which is a boolean that keeps the state if it is blinking right, let's call it blinkToRight. Initially this is true.
An if statement will be used to change the order.
So the program will be something like (not tested):
global:
bool blinkToRight = true;

in Setup:
pinMode(3,OUTPUT);
pinMode(4,OUTPUT);
pinMode(5,OUTPUT);
pinMode(2,INPUT);

In Loop:
// Check if loop is reversed
blinkToRight = checkReverse();

if (blinkToRight)
{
   show(true, false, false);
   show(false, true, false);
   show(false, false, true);
}
else
{
   show(false, false, true);
   show(false, true, false);
   show(true, false, false);
}

void show(bool led1, bool led2, bool led3)
{
   digitalWrite(2, led1);
   digitalWrite(3, led2);
   digitalWrite(4, led3);
   delay(200);
}

checkReverse will check the input button and returns true if the mode should be reversed.
However, you cannot simply check for the button state. The problem is bouncing. But check in the Arduino examples to a debounce example for this problem and the program should work as expected.
See example: Debounce example
Since only one led will be on, you can also use the following functions for Loop and show:
In Loop:
// Check if loop is reversed
blinkToRight = checkReverse();

if (blinkToRight)
{
   show(3);
   show(4);
   show(5);
}
else
{
   show(5);
   show(4);
   show(3);
}

Show:
void show(int ledOn)
{
   digitalWrite(ledOn == 3);
   digitalWrite(ledOn == 4);
   digitalWrite(ledOn == 5);
   delay(200);
}

And it's even better to use constants:
const int LED1   = 3
const int LED2   = 4
const int LED3   = 5
const int BUTTON = 2

Setup:
pinMode(LED1  , OUTPUT);
pinMode(LED2  , OUTPUT);
pinMode(LED3  , OUTPUT);
pinMode(BUTTON, INPUT);

Loop
// Check if loop is reversed
blinkToRight = checkReverse();

if (blinkToRight)
{
   show(LED1);
   show(LED2);
   show(LED3);
}
else
{
   show(LED3);
   show(LED2);
   show(LED1);
}

Show:
void show(int ledOn)
{
   digitalWrite(ledOn == LED1);
   digitalWrite(ledOn == LED2);
   digitalWrite(ledOn == LED3);
   delay(200);
}

you should add some delays between the "show()" functions, or have some kind of timing, othewise all the LED will appear as ON...

@next-hack Thanks for the comment, you are absolutely true, and I updated my answer (part of the show function).

In my opinion, there are two things I'd change. The first one is that delay functions should be avoided whenever possible, the other is that the switch bounces.
In order to solve the bounces, you will have to wait some time to stabilize the signal:
if (debouncedValueOfButton != (digitalRead(button_pin) == HIGH))
{ // Is there a change?
    if (((byte)currMillis) - lastMillisForButton) >= millisButtonDebounce)
    { // Yes, without bounces
        debouncedValueOfButton = !debouncedValueOfButton;
        if (debouncedValueOfButton)
        { // Rising edge
            if (increment > 1)
                increment = 1; // Go in one direction
            else
                increment = 2; // Go in the other direction
        }
    }
}
else
    lastMillisForButton = (byte)currMillis;

So, if the value is different from the one I think it is I'll wait for some milliseconds; if it is stable then I change the value I think it is.
As for removing the delay, I think it is better to use an approach similar to the "blink without delay" sketch:
if ((((uint16_t)currMillis) - lastMillisForBlink) >= millisBetweenBlinks)
{
    lastMillisForBlink += millisBetweenBlinks;
    currentLed = (currentLed + increment) % 3;

    digitalWrite(led0_pin, currentLed == 0);
    digitalWrite(led1_pin, currentLed == 1);
    digitalWrite(led2_pin, currentLed == 2);
}

In this implementation, you use a variable increment to decide whether you have to go forward or backwards; when increment is 1 the led to be colored are 0 -> 1 -> 2 -> (3)0 -> 1 ...; when it is 2 the led are 0 -> 2 -> (4)1 -> (3)0 -> 2 ....
The complete code is (DISCLAIMER: NOT TESTED)
const byte led0_pin = 3;
const byte led1_pin = 4;
const byte led2_pin = 5;
const byte button_pin = 2;

int8_t currentLed, increment;
unsigned int lastMillisForBlink;
const unsigned int millisBetweenBlinks = 200;

bool debouncedValueOfButton;
byte lastMillisForButton;
const byte millisButtonDebounce = 50;

void setup() {
    pinMode(led0_pin,OUTPUT);
    pinMode(led1_pin,OUTPUT);
    pinMode(led2_pin,OUTPUT);
    pinMode(button_pin,INPUT);

    increment = 1;
    currentLed = 2; // At first run, currentLed will be increased by 1, so it starts at 0
    lastMillisForBlink = millis() - millisBetweenBlinks; // trigger a refresh at first loop

    debouncedValueOfButton = (digitalRead(button_pin);
}

void loop() {
    unsigned long currMillis = millis();

    if ((((uint16_t)currMillis) - lastMillisForBlink) >= millisBetweenBlinks)
    {
        lastMillisForBlink += millisBetweenBlinks;
        currentLed = (currentLed + increment) % 3;

        digitalWrite(led0_pin, currentLed == 0);
        digitalWrite(led1_pin, currentLed == 1);
        digitalWrite(led2_pin, currentLed == 2);
    }

    if (debouncedValueOfButton != (digitalRead(button_pin) == HIGH))
    { // Is there a change?
        if (((byte)currMillis) - lastMillisForButton) >= millisButtonDebounce)
        { // Yes, without bounces
            debouncedValueOfButton = !debouncedValueOfButton;
            if (debouncedValueOfButton)
            { // Rising edge
                if (increment > 1)
                    increment = 1; // Go in one direction
                else
                    increment = 2; // Go in the other direction
            }
        }
    }
    else
        lastMillisForButton = (byte)currMillis;
}


text:
Cannot spin motor 28BYJ-48 with controller board ULN2003APG
I'm a beginner with Arduino. I managed to grasp the basic understanding and try to use each component/shield that came with my Arduino kit.
I'm unable to use the following component:

Step Motor 28BYJ-48
Step Motor controller board ULN2003APG

I connected the Arduino to the ULN2003APG and put some coding such that I can see that the ULN2003APG's LED turned on from 1, 2, 3, 4, 1, 2, 3, 4, and so on. So this is as expected as per programming below.
My issue:

I noticed the LED in the ULN2003APG is not as bright as a regular
LED.
Once I plugged in the 28BYJ-48 to the ULN2003APG, the ULN2003APG's LED all off.
The motor (28BYJ-48) doesn't spin - at all.
I tried to spin the motor with my 2 fingers, it seems pretty heavy - is this normal?

Is this a faulty ULN2003APG or is it a faulty 28BYJ-48 or is it a faulty programming? please help.
Program:
#include <Stepper.h>

int pin1=8;
int pin2=9;
int pin3=10;
int pin4=11;
int _step=0;
void setup() {
    Serial.begin(9600);
    pinMode(pin1, INPUT);
    pinMode(pin2, INPUT);
    pinMode(pin3, INPUT);
    pinMode(pin4, INPUT);
}

void loop() {
  switch (_step){
    case 0:
      digitalWrite (pin1, HIGH);
      digitalWrite (pin2, LOW);
      digitalWrite (pin3, LOW);
      digitalWrite (pin4, LOW);
      break;
    case 1:
      digitalWrite (pin1, LOW);
      digitalWrite (pin2, HIGH);
      digitalWrite (pin3, LOW);
      digitalWrite (pin4, LOW);
      break;
    case 2:
      digitalWrite (pin1, LOW);
      digitalWrite (pin2, LOW);
      digitalWrite (pin3, HIGH);
      digitalWrite (pin4, LOW);
      break;
    case 3:
      digitalWrite (pin1, LOW);
      digitalWrite (pin2, LOW);
      digitalWrite (pin3, LOW);
      digitalWrite (pin4, HIGH);
      break;
  }
  _step ++;
  if (_step == 4){
    _step = 0;
  }
  Serial.println(_step);
  delay(250);

}

What happens if you change
pinMode(pin1, INPUT);
pinMode(pin1, INPUT); // Pin 2 ?
pinMode(pin3, INPUT);
pinMode(pin4, INPUT);

to
pinMode(pin1, OUTPUT);
pinMode(pin2, OUTPUT);
pinMode(pin3, OUTPUT);
pinMode(pin4, OUTPUT);

Answer for Q1 - Q3. You are using pinMode as an input. Using digitalWrite() on an INPUT will enable (HIGH) or disable (LOW) the internal pullup resistor on the input pin. The pin will not be able to "source" enough current to operate the stepper motor.
A4. The stepper motor has a "mechanical" 1/64 gear ratio. This is why it is hard to turn by hand.
Here are 2 pages that will help you to understand the issue: https://www.arduino.cc/en/Reference/PinMode and https://www.arduino.cc/en/Reference/DigitalWrite.

Hey, sorry let me fix that.

It works, thanks a lot! I noticed the typo on the pin1 and pin1. Then, as you point out the INPUT should be OUTPUT. Thanks again!


text:
Adafruit RTC begin() not returning false
I am programming my arduino with the capability to keep time with the DS3231 from Adafruit. I do not have the module yet, but am trying to figure out the rest of the build without it.
However, it seems like the way to determine RTC is working does not work, as it returns true, even without the module.
Example code from the Adafruit RTC library for using this module:
// Date and time functions using a DS3231 RTC connected via I2C and Wire lib
#include <Wire.h>
#include "RTClib.h"

RTC_DS3231 rtc;

char daysOfTheWeek[7][12] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};

void setup () {

#ifndef ESP8266
  while (!Serial); // for Leonardo/Micro/Zero
#endif

  Serial.begin(9600);

  delay(3000); // wait for console opening

  if (! rtc.begin()) { // part that fails. begin() returns true when should return false
    Serial.println("Couldn't find RTC");
    while (1);
  }

  if (rtc.lostPower()) {
    Serial.println("RTC lost power, lets set the time!");
    // following line sets the RTC to the date & time this sketch was compiled
    rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
    // This line sets the RTC with an explicit date & time, for example to set
    // January 21, 2014 at 3am you would call:
    // rtc.adjust(DateTime(2014, 1, 21, 3, 0, 0));
  }
}
....

If you look at the library source code it will be clear why begin() returns true.
From https://github.com/adafruit/RTClib/blob/1.2.0/RTClib.cpp#L434-L437:
boolean RTC_DS3231::begin(void) {
  Wire.begin();
  return true;
}

I suppose they plan to eventually make the return value of begin() mean something but for now it does not.

This should not happen anymore.
Actually, if you have a look at the last version of the source code on GitHub (1.13.0), you will see that now the developers implemented also a case in which the method returns false.
from https://github.com/adafruit/RTClib/blob/1.13.0/RTClib.cpp#L1537-L1543 :
boolean RTC_DS3231::begin(void) {
  Wire.begin();
  Wire.beginTransmission(DS3231_ADDRESS);
  if (Wire.endTransmission() == 0)
    return true;
  return false;
}

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


text:
How to make two WIR 1186 RF transceivers communicate over serial communication?
I want to have two RF transceivers communicate, one as transmitter and one as a receiver, for longer distances. For that I'm using WIR 1186 RF modules with Arduino.
Pin connections are as below:

Arduino :5v,gnd,RX,TX,2,3
WIR1186 :VCC,gnd,Tx,Rx,prg,cts

But Arduino is not serially communicating with the WIR1186 module.
Below is the code:
char ch;
int prog = 2;
int cts = 3;
int stat;
unsigned int output;

void setup() {
  Serial.begin(9600);
  pinMode(prog, OUTPUT);
  digitalWrite(prog, LOW);
  stat = digitalRead(prog);
  Serial.println(stat);
  Serial.write("B=9600\r\n");
  output = Serial.read();
  Serial.println(output);
  digitalWrite(cts, HIGH);
}

void loop() {
  Serial.write('a');
  delay(1000);
}

Here is the datasheet of WIR1186
Please help me out with this.

digitalWrite(cts, HIGH); --- Are you sure about that?

yes,clear to send should be high when we are sending

Err... have you read the datasheet?

yes i referred that and i have downloaded WIR library from GIthub, based on the header file function i have given cts High, Before that the commands in setup are also not sending to WIR module

Is your WIR-1186 on some kind of carrier board with voltage regulator and logic level translation?

If you use pin 2 and 3 for serial communication you have to use SoftSerial, because Serial is hardwired to pin 0 and 1.

pin 2 and 3 of arduino has connected to prog and cts pins of WIR module

Two things are wrong:

You aren't setting PROG to HIGH to enable transmit mode - you are stuck in programming mode.
CTS is an output from the module to an input on the Arduino. You don't set it high - you look to see what level it is to see if it is safe to send more data.

To quote from the datasheet you link to:

The WIR-1186 offers data flow control hardware to allow for zero data over-run and loss when sending large
files and data packets. The internal data buffer on the WIR-1186 module is 128bytes. When the data terminal1
sends a large file for wireless transmission the module2 will except 128bytes and then set the CTS pin LOW to
alert the data terminal to wait for the CTS to back HIGH before sending more data over UART.

(footnotes mine)
Also you cannot use pins 0 and 1 for serial if you are at the same time using them for USB debugging. You will either have to move to another pair of pins and use SoftwareSerial, or invest in a better Arduino with more than one UART.
Another thing of importance: If your WIR-1186 isn't on some kind of carrier board with voltage regulator and logic level translation it's safe to say that you have killed it. Well done.

Warnings

The maximum allowable voltage on any of the interface pins with respect to GND is 3.6V
The maximum input voltage VCC with respect to GND is 3.6V
The baud rate setting in configure mode is fixed 9600bps
Do not leave the UART_TX input pin of the module open. The module will send junk data on thewireless channel. It must be pulled up to VCC if not used.

1 Arduino
2 WIR-1186

but it is not entering into command mode also ,when i send a command in setup as in the program it is not giving any response

Your program isn't looking for a response. It's looking to see if there's a single character in the RX buffer at the moment you send the command. Learn the basics of serial before trying to use it. https://hackingmajenkoblog.wordpress.com/2016/02/01/reading-serial-on-the-arduino/

no response is getting, Serial.read() is printing -1


text:
Can Arduino Mega ADK charge connected smartphone?
I suppose Arduino Mega ADK acts as the USB host for the connected smartphone.
Is it capable of providing power to the smartphone?

If you read the documentation, you will see this paragraph:

NB: Because the MEGA ADK is a USB Host, the phone will attempt to draw power from it when it needs to charge. When the ADK is powered over USB, 500mA total is available for the phone and board.The external power regulator can supply up to 1500mA. 750mA is available for the phone and MEGA ADK board. An additional 750mA is allocated for any actuators and sensors attached to the board. A power supply must be capable of providing 1.5A to use this much current.

So yes (though slowly), if you connect it to a suitable power supply.


text:
How to embed a 5V-range Arduino-based controller in a 12V-range DC circuit?
We have an installation that provides:

a common line (C), which divides into two wires;
an input line (I), which carries the signal from a button (between I and C there's normally 0V, and 12V when the button is pressed);
an output line (O), which carries a signal to a bell (between O and C there's always 12V).

simulate this circuit – Schematic created using CircuitLab
A controller is to close the OC circuit every time a given temporal pattern shows in I (say, a concrete Morse-like -short/long- sequence of pulses), so the bell will ring if the concrete word is recognized at the input. Such a controller has been implemented in C++ and uploaded to an Arduino Nano, and it works fine on a protoboard, with a button as input and led as output, all in the same electrical range.
Since both the IC and the OC are 12V circuits, and the controller is in the 5V range, what is the minimal circuit to embed the controller between the IC and the OC circuits?

You may wish to look at: https://electronics.stackexchange.com/questions/43498/how-can-i-use-a-12-v-input-on-a-digital-arduino-pin and https://electronics.stackexchange.com/questions/167411/how-to-mosfet-to-drive-12v-relay-from-microcontroller-logic-high-is-3-3v-using

easy:
1) use a transistor's b-c junction;
2) use a mosfet;
3) use a relay, solid state or mechanical;
4) find a chip with 12-compliant pins;
...

Just use a transistor that can handle 12V with the base connected to the Arduino and that's it...
Maybe I didn't get what you were trying to say, but anyway, I think that's what you are looking for.

I think you can use "mosfet" control 12v with 5v voltage also if you think this is insufficient you can add the relay, control relay with mosfet without how much voltage as you want.
I made disco lights with rgb strip led and when I run the circuit different time and different type of led turn on and turn off I used 3 mosfets and 3 arduino outputs the strip led work with 12v.


text:
How to send HTTP requests using wifi of Arduino Primo board?
I have bought an Arduino Primo board. I have configured it to connect to my wifi router and changed it to STA mode. Now, how do I program it to send HTTP requests to a server? Which library file I should use? Any tutorial?

With Arduino Primo use the WiFi Link library. Look at WiFi Link Examples in IDE menu.
Arduino org web archive pages


text:
Grounding issues Arduino Ethernet Shield makes WS2811 LEDs flicker
I have an Arduino Due with an Arduino Ethernet Shield V2 that I use to control multiple daisy-chained WS2811 LED strips.
When I turn on most of the LEDs the Arduino and attached wires seem to become an antenna, picking up fluctuations that make the LEDs flicker, by messing with the data on the WS2811 data line. Touching the data cable, touching the ethernet plug on the shield, or simply hovering my hand over the Arduino adds noise that causes flickering in the lights.
When I pull out the ethernet plug, it stops. (The Arduino continues to update the WS2811 chips, even without network connection)

The flickering is especially strong when I set the first couple of LEDs in the chain to White (biggest draw of current), while having red or green colored LEDs at the beginning causes milder flickering (even if there are LEDs set to White further back in the chain).
Some more observations:

The LED strips are powered from both sides. It doesn't seem to be a power issue.
I tried with a different Arduino Due, a different Ethernet shield, a different router and Ethernet cable, and a different power supply.
The router the Arduino is plugged into, is positioned on the same table, and powered from the same power bar as the LED/Arduino power supply.
I tried running the Arduino and the LEDs from different power supplies but that didn't help. Rather the opposite (which makes sense)
This happens no matter how long the equipment has already run or how hot it is.

Another mystery:
You might notice the lose ground cable from the LED strip connector. When I plug that into the Arduino Due, the LEDs don't get turned on at all. When I plug that ground cable into the Ethernet shield sitting on the Due, then some lights turn on wrong. No matter if Ethernet is plugged in or not (though there's a difference in the 'wrongness' of the lights when Ethernet is plugged in). Note, that the Arduino and the LED strips already share ground 1 foot away as they are both fed by the same 12V power supply.
Where are all these grounding issues coming from and how do I get rid of them? What else could I try?

I suspect that the signal driving the LED strip does not have enough voltage swing. And that ground noise/resistance is what makes the system sometimes appear to work correctly.
With 12 volt LED strips, the data signal into the WS2811 should swing at least 0.3x to 0.7x 12 volts, or below 3.6 volts (low) to above 8.4 volts (high).
The Arduino Due has output signals from 0 volts to 3.3 volts.
Which would explain the observation that if ground is connected directly between Due and LED then the Due output is never high enough to signal the LEDs.
I would try using a logic level converter between the Arduino Due output and the LED strip data input.

Thank you, this does sound like it's the most logical conclusion. I had already tested a quick logic-level conversion with npn-transistors I had lying around. But that didn't work, either because of the specs of the transistors I picked, or because I only attempted to upgrade it to 5V. I will order a logic-level converter board now to do a proper test.

I first got the "SparkFun Logic Level Converter - Bi-Directional" but that one didn't help much, then I read up a bit more and ordered a 74HCT245 (which is able to handle much faster switching) and now it works!


text:
Arduino nano ATmega328p with CH341 won't upload
When I try to upload a sketch to an Arduino Nano, it stays stuck on uploading, and after a time it shows the following error code:

stk500_getsync() attempt 1 of 10: not in sync: resp=0xc2
stk500_getsync() attempt 2 of 10: not in sync: resp=0xc2
stk500_getsync() attempt 3 of 10: not in sync: resp=0xc2
stk500_getsync() attempt 4 of 10: not in sync: resp=0xc2
stk500_getsync() attempt 5 of 10: not in sync: resp=0xc2
stk500_getsync() attempt 6 of 10: not in sync: resp=0xc2
stk500_getsync() attempt 7 of 10: not in sync: resp=0xc2
stk500_getsync() attempt 8 of 10: not in sync: resp=0xc2
stk500_getsync() attempt 9 of 10: not in sync: resp=0xc2
stk500_getsync() attempt 10 of 10: not in sync: resp=0xc2

Sometimes the resp=0xc2 variable changes to another hex code.
The weird thing here is that before this happened everything worked fine. I could upload and the serial communication was fine. But after trying to upload the same sketch with a different variable, this started to happen.
Windows recognizes the COM port, in Arduino the COM port is selected. Sometimes, without doing anything, the Arduino works fine again, I can see the serial communication fine, but after some time the serial communication stops sending and again I can't upload the sketch.
I have 2 Arduino Nanos. Both of them start presenting the same problem. But the other one has the Power, RX, and TX led always on and this one never worked again, like the other one that sometimes can upload the sketch and see the serial communication that the last sketch was sending. I have an Arduino Mega, this one has the ATmega16U2 to communicate to USB and this one works fine. And I also have a NodeMCU Lua, with CH341. But this one works just fine.

Do you have an oscilloscope? If so, check on the RX and TX pins if, when writing something in a serial terminal, a signal passes through the USB/UART bridge. If it does, the problem is the microcontroller (maybe flash the bootloader again). If it doesn't, the CH341 is broken. Also check the +5V voltage...

I don't have an oscilloscope :(. I manage to upload the Blink program and at first time it was blinking at the rate of 1 second, but after some time the blink start going wild and start blinking really fast. About the serial communication, I put RST to ground, and connect RX to TX and I opened the serial monitor and I start sending words and both RX and TX light up every time i hit enter. But nothing show in terminal. I already flash the bootloader again in both and still the same. In the one that the TX and RX are always on, it didnt let me flash the bootloader.

The suggestion by John Allen is exactly what it took to get my 1.8.5 IDE to upload successfully to my Nano boards. Happy Day!!
Just a note - the 'ATMega328P (Old bootloader)' option does not seem to be available in IDE 1.8.5 on my old WinXP machine.

If you are using a fairly recent version of the Arduino IDE, try using the old bootloader for the 328P.
Go to Tools --> Processor:"ATmega329P" --> ATmega328P(Old Bootloader)

Open your device manager in computer if ot would show your arduino nano as USB 2.0 then you need to install CH340G DRIVERS from Google install it and then again connect it to the computer your problem would be solved but remember to remove TX and RX pins before uploading code...


text:
Connecting Arduino Mega + SIM800L to a car battery
I need to make a car tracker powered from a car battery. The problem is the SIM800L needs to be powered with 3.8v to 4.2v, and at 2A preferably. I want to connect the car battery to my Mega first then the Mega powers the SIM800L.
So:
Car battery > Mega > SIM800L
What do I need to achieve this?
This is the SIM800L model:

With this setup you are overstressing the onboard regulator, while wasting a lot of power (not suggested on a battery setup, even if the battery is quite big).
First of all, the power. You have a MEGA, which runs at 5V/few mA, and a SIM800L, which runs at 4V/2A. I suggest you to have two power supplies. On ebay you can find cheap XL4015 converters rated at 5A. You connect IN+ to the +12V, IN- to the ground, then set the first one to output 5V, while the other to 4V. If you want to have the most correct powering scheme connect the 5V to the USB port, otherwise connect it to the +5V pins (note that you will exclude the fuse).
Then there is another problem: the UART levels. As a first approximation you can hope that the arduino reads the correct levels, so you'll just have to lower the TX voltage from 5V to 3.3V. You can do this by using a voltage divider with a 4.7k resistor between arduino TX and SIM RX and a 10k resistor between SIM RX and ground (see, for instance, how they did it in this image).

I want to connect the car battery

The Mega has an NCP1117 linear voltage regulator onboard. This is qualified for automotive use, however the max. output current at 12V input voltage is only 1A, which is too less to supply your SIM800.
Next thing you should consider: The car voltage is not stable. Voltage peaks up to 40V can occur, especially when starting the engine. This will stress your components, and destroy them in worst case.
I would use two DC/DC converters with high enough input voltage and adjust one to 7V output (for the Arduino), the other one to 4V (for the SIM) and connect the ground lines together.
For voltage level matching between Arduino and SIM Uart see page 32 of SIM800 hardware manual.


text:
Why is there a limitation in using Serial.println on ESP8266?
I'm trying to upload this code on ESP8266, and when I do, it just resets continuously.  This also happens when you have memory bugs, but obviously, this code has no memory bugs!  Here is the code:
#include "Arduino.h"

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

void loop()
{

}

void foo(){
    for(unsigned int i = 1; i <= 10000; i++){
        Serial.println("FOOBAR");
    }
}

Also, in the serial monitor, I get this (per reset):
Soft WDT reset

ctx: cont
sp: 3ffef130 end: 3ffef390 offset: 01b0

>>>stack>>>
3ffef2e0:  feefeffe feefeffe feefeffe 00002580
3ffef2f0:  0000001c 00000001 3ffe85b1 402023d4
3ffef300:  feefeffe 00000005 3ffe842d 3ffee364
3ffef310:  3fffdad0 00000006 3ffee340 40201fd1
3ffef320:  3ffe85b0 00000000 3ffee340 40201fd1
3ffef330:  3ffe8428 00000000 3ffee340 40201fec
3ffef340:  00000001 feefeffe 3ffee340 40202010
3ffef350:  feefeffe 00000000 00002580 40201c00
3ffef360:  3fffdad0 00000000 3ffee35c 40201c2e
3ffef370:  feefeffe feefeffe feefeffe 402021c8
3ffef380:  feefeffe feefeffe 3ffee370 40100718
<<<stack<<<
Õ®(ŽL‰Ì==   I5

So, why is this happening?

It's happening because you're not giving the ESP8266 a chance to do its housekeeping activities and the watchdog (which is enabled by default) is timing out - as evidenced by the very first line of your output:

Soft WDT reset

You need to allow the MCU to do other things at the same time as you are printing to serial:
void foo(){
    for(unsigned int i = 1; i <= 10000; i++){
        Serial.println("FOOBAR");
        yield();
    }
}

What does yield() does? Curious to know that.

the ESP8266 uses the same cpu for maintaining wifi as running sketch code. if your sketch code runs too long, the wifi routine freaks out about not being able to maintain a connection and resets. yield() pauses sketch code while the wifi does its thing.

Is there a way to modify time out?

@dandavis Very useful comment +1.

With Arduino/ESP8266 you have to break your tasks in little pieces so setup and loop takes as little time as possible.
Your elemental tasks is executing one Serial.println. We first reformulate foo to run a single elemental task in each invocation. Then, we move the call to loop, so setup ends quickly. In loop we use the variable iterations to controls calls to foo. When it reaches zero it signal the end of the "setup" part.
#include "Arduino.h"
int iterations = 10000;
void setup()
{
    Serial.begin(9600);
}
void loop()
{
  if (iterations > 0) {
    iterations--;
    foo();
  }
}
void foo(){
  Serial.println("FOOBAR");
}

It can be tricky to break some big code in small parts, but it's something you must learn to do, because there is no other way.

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

Majenko, did you see my comment on your answer? Or, rather, the question?


text:
Current Draw for LED Projects
I am working on a project with LED strips that would consume 12V and 20A. The problem is that the household wall outlet limitation is 15A, and 20A current draw would potentially start a fire. I have been searching for tutorials of large current LED project, and none of them really addresses the current draw problem.
I found an adequate power supply. It is Meanwell RSP-320-12. http://www.mouser.com/ProductDetail/Mean-Well/RSP-320-12/?qs=Uzd%2Fwh%252bZzhBChmc2p7rgKQ%3D%3D.
How can I make it work with a 15A wall outlet limitation?
Thanks in advance!

When you say 15V in your last sentence, do you actually mean 15A?

only if you used a linear power supply, which nobody uses for hi-power LEDs...

Drawing 20A on 12V means 240W which on 110V is 1A and a bit (a bit more once you consider efficiency of the conversion).
The spec sheet of the power supply you linked says that it will draw 2.7A max on a 115V input.
The power supply will convert the high voltage low amps into low voltage high amps.

The power outlet is either 110V AC or 230/240V AC. Ignoring modern Switch-mode power supplies, to convert the power outlet voltage down to 12V, you first need to step down the voltage (using a transformer) and then rectify the AC voltage to DC voltage.
Working backwards, to get 12V DC you need: 12 x square_root(2) = 16.97 V AC.
A transformer can step down AC voltage. For example it can step down 110V AC down to 16.97 V AC.
The formula for an ideal transformer is:
V x i (primary side) = V x i (secondary side)

And using this to find the current draw on the primary side:
110 x i (primary side) = 16.97 x 20 (secondary side)

i (primary side) = 16.97 x 20 / 110

i (primary side) = 3.08 A

So if you have an outlet that provides 110 V AC then an ideal AC-DC converter would draw 3.08 A.

12Vp-p is 8.485Vrms, not 16.97Vrms. You need to divide, not multiply.

@Majenko you are correct for a bridge rectifier circuit, however my calculations are correct for a full wave rectifier. http://www.sowter.co.uk/rectifier-transformer-calculation.php

People still use those...? For that matter, people still use transformers...?!


text:
digitalRead not reading input pin of ESP8266-01
I am trying to use a on-off switch with the ESP8266 to change whether GPI02 is HIGH or LOW. I am using GPIO3 as input. My circuit looks like this:

The red area to the right is a relay, I wasn't sure how to make it work in fritzing but I am sure that it is wired correctly, it just has a signal, +, and -, pin. The more important stuff is happening with the ESP8266. First, here is the code:
/*
  This a simple example of the aREST Library for the ESP8266 WiFi chip.
  This example illustrate the cloud part of aREST that makes the board accessible from anywhere
  See the README file for more details.

  Written in 2015 by Marco Schwartz under a GPL license.
*/

// Import required libraries
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <aREST.h>

// Clients
WiFiClient espClient;
PubSubClient client(espClient);

// Create aREST instance
aREST rest = aREST(client);

// Unique ID to identify the device for cloud.arest.io
char* device_id = "ew1zard";

// WiFi parameters
const char* ssid = "MaisonBlanche";
const char* password = "7932gLBw";

// Functions
void callback(char* topic, byte* payload, unsigned int length);

void setup(void)
{
  // Set input / output pin
  pinMode(3, INPUT);
  pinMode(2, OUTPUT);
  //pinMode(2, OUTPUT);
  //digitalWrite(3, 0);

  // Start Serial
  Serial.begin(115200);

  // Set callback
  client.setCallback(callback);

  // Give name & ID to the device (ID should be 6 characters long)
  rest.set_id(device_id);
  rest.set_name("esp8266");

  // Connect to WiFi
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected");

  // Set output topic
  char* out_topic = rest.get_topic();
}

void loop() {

  // Connect to the cloud
  rest.handle(client);

  int read3 = digitalRead(3);
  Serial.println(read3 + " input");
  digitalWrite(2, read3);

}

// Handles message arrived on subscribed topic(s)
void callback(char* topic, byte* payload, unsigned int length) {

  Serial.println("request from interwebs");
  rest.handle_callback(client, topic, payload, length);

}

The output of the Serial.println is always input (there is no HIGH or LOW or 1 or 0, or whatever it should be, before the input. I have verified that the switch is working. In the on position it is sending 3.3v to GPIO3 (I have measured it with my multimeter) and still the input never changes. In the off position it sends 0v and the ESP8266 just acts as if there is nothing to read it seems. Since I am using this with aREST and you can set the mode of pins through that, I thought maybe I had to set the pinMode with the aREST request cloud.arest.io/xxxxx/mode/3/i and it verifies with a JSON response that the pin is being set to input, but still no reading. Do I not have the ESP8266 wired correctly for this? Maybe I need some pull-ups/pull downs or I can't use the pins in the configuration I am using them? One other thing, when I set the input pin with aREST, it turns on the relay (sending something through GPIO2 for some reason). If I don't set the input with aREST the relay stays off.
UPDATE
I tried with this code to rule out that it might be aREST:
void setup() {
  // put your setup code here, to run once:
  pinMode(3, INPUT);
  pinMode(2, OUTPUT);

  // Start Serial
  Serial.begin(115200);
}

void loop() {
  // put your main code here, to run repeatedly:
  int read3 = digitalRead(3);
  Serial.print(read3);
  Serial.println(" input");
  digitalWrite(2, read3);
}

It always outputs 0 input, the ESP8266 seems to be ignoring that input pin.
UPDATE
I am now trying with GPIO0 as input. I have the switch wired to ground, and it leads to GPIO0. When I turn it on, GPIO0 reads 1 (on), then I use the switch and it turns the relay off correctly, then I try and turn it on again, and nothing happens, GPIO0 continues to be read at 0. So I can't use the switch past the initial off.

The expression read3 + " input" performs pointer arithmetic, i.e. you either add 0 or 1 to the start adress of " input", so you get either " input" or "input". Does the leading space disappear when pressing the button?
To correct your code you can print the number separately:
Serial.print(read3);
Serial.println(" input");

You should get rid of the rest and pub-sub code. You can add this later after having solved the problem with the button.
Also note that GPIO03 uses the same pin as RX. The docs state the following:
Serial uses UART0, which is mapped to pins GPIO1 (TX) and GPIO3 (RX).

So it should work after disabling Serial and after providing a pull down resistor. The resistor is needed to prevent having a floating input.

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

The issue occurs when you try to use the RX port (3) and you also define Serial.begin. This is double dipping. You can only use the RX/TX as a single unit of digital or serial communication.

There are certain pins that output a 3.3V signal when the ESP8266 boots. This may be problematic if you have relays or other peripherals connected to those GPIOs. The following GPIOs output a HIGH
signal on boot: GPIO1, GPIO3, GPIO9, GPIO10. GPIO3:  pin must high at BOOT and is pulled up to that position. I have no idea what will happen if low at that point.  Since I2C I/O modules are cheep I use them and do not worry about the rest of the pins. Not the cheapest but keeps me out of trouble. It makes my life a bit easier as well as I pull up the I2C lines to the 3.3V and connect the PCF8574 to 5 Volts. No problem as the SCL and SCI are by definition Open Drain or Open Collector (Bipolar parts). This made my first try with a LCSD work first shot. I tried the 3.3V and it would not work.


text:
Posting data to ASP web service from GSM using AT commands - where am I going wrong
I'm using an Arduino uno with a SIM900 GSM shield.  I'm trying to connect the Arduino to my (ASP MVC) website.  I've written an API which i've successfully tested with postman, and whilst the GET Command works fine, I've had no success with POSTING data as yet.  Using the arduino to echo serial monitor input, I've done the following...
So, some setup commands
    AT+CGATT?
    AT+SAPBR=3,1,"CONTYPE","GPRS"
    AT+SAPBR=3,1,"APN","internet"    (vodafone UK parameters
    AT+SAPBR=3,1,"USER","web"
    AT+SAPBR=3,1,"PWD","web"
    AT+SAPBR=1,1
    AT+SAPBR=2,1     (confirms i have an IP address)

i then do the following...
    AT+HTTPINIT
    AT+HTTPPARA="CID",1
    AT+HTTPPARA="PROIP","212.183.137.12"   (vodafone uk proxy settings)
    AT+HTTPPARA="PROPORT","8799"
    AT+HTTPPARA="CONTENT","application/json"
    AT+HTTPPARA="URL","http://mywebsite.co.uk/api/obs"
    AT+HTTPDATA=83, 10000    (gives the download command).
    {"SensorName": "TestSensor", "ObsValue": 31, "ObsDateTime": "2017-10-01T03:30:00"}
    AT+HTTPACTION=1

and I just get an "OK" back, no httpaction response, and no data stored on the database.
Is there anything I'm doing that is obviously wrong?  Does HTTPACTION come before the data?
Are there commands I can use to check the status of my http session on the GSM board? to confirm that my settings are correct?
Finally, I keep getting messages like
    +CREG: 1,"002A","0F48"

Always the 1 (presumably the CID i'm using), and always the 002A, but the final part varies.
Any help would be hugely welcome.  Thanks.

Check the web server logs, and sniff your network traffic for port 83 using whatever tools are suitable for your operating system. Put the SIM in a phone and try browsing the web - it may need activating first and Vodaphone are redirecting the traffic to their own activation page.

Also I have never had to use a proxy with GSM access on vodaphone. Try without.

this is a sim i've taken from an IPAD, and had been working fine.  Before I put the proxy stuff in, I was getting a 602 DNS error on my GET command, but I can give it a go :)    My website is being hosted on a commercial hosting site (1and1) so I'm not sure whether sniffing traffic is a viable option, but many thanks for the suggestiongs

so, I removed the proxy settings - and its worked!  once - still thats more often than before.

+CREG: 1,"002A","0F48"

That's the registration status. "1" is "Registered on your 'home' network", "002A" is your LAC (Location Area Code) and "0F48" is the Cell ID (CI).

so these are just messages when the serving cell changes?  Having left the serial monitor up for a while, I do see the same numbers repeating - thanks for the info.


text:
Writing a value to 7-segment max7219 displays
I am new to arduino and I am trying to build an interface for my flight simulator. I am using a plugin for the simulator software which returns a float variable to my arduino, which I then want to display on a series of 7-segment displays. I have connected three max7219 modules, each with 8 digits.
I found the LedControl library which I managed to get to display on my modules like this:
#include <LedControl.h>

// inputs: DIN pin, CLK pin, LOAD pin. number of chips
LedControl mydisplay = LedControl(48, 44, 46, 3);

void setup() {
  mydisplay.shutdown(0, false);  // turns on display
  mydisplay.shutdown(1, false);  // turns on display
  mydisplay.setIntensity(0, 7); // 15 = brightest
  mydisplay.setDigit(0, 0, 9, false);
  mydisplay.setDigit(0, 1, 8, false);
  mydisplay.setDigit(0, 2, 7, false);
  mydisplay.setDigit(0, 3, 6, false);
  mydisplay.setDigit(0, 4, 5, true);
  mydisplay.setDigit(0, 5, 4, false);
  mydisplay.setDigit(0, 6, 3, false);
  mydisplay.setDigit(0, 7, 2, false);

  mydisplay.setDigit(1, 0, 9, false);
  mydisplay.setDigit(1, 1, 8, false);
  mydisplay.setDigit(1, 2, 7, false);
  mydisplay.setDigit(1, 3, 6, false);
  mydisplay.setDigit(1, 4, 5, true);
  mydisplay.setDigit(1, 5, 4, false);
  mydisplay.setDigit(1, 6, 3, false);
  mydisplay.setDigit(1, 7, 2, false);

}

void loop() {
}

The arduino code however for the plugin I am using has this function:
void ProgOut(byte id, float val) {

  if (id == 1)
  {
       // print this to display
  }
}

So my question is, right now based on the LedControl test sketch, I have to display each individual character one by one, but I receive a float variable.. so how can I just do something like "mydisplay.set(floatvariable)" ?

Why not use a library that supports that directly? https://github.com/mikaelpatel/Arduino-LCD. Then you can write code like "led.print(3.1415, 4)", i.e. use the same interface as Serial.

I didn't know about that library. I'll check it out, thanks.

how can I just do something like "mydisplay.set(floatvariable)" ?

write your own code.
let's say that you want to display up to two decimal points. Multiply the float vary by 100, save it into an int variable, and utilize the existing code to display that integer variable + decimal point at the right digit.


text:
Do I need a relay to control a monitor's power with an Arduino?
I'm trying to use an Arduino to switch a monitor's power on and off. I'm going to wire the Arduino to the monitor's power switch. I've tested the power switch with a multimeter, and when pressed, there is a 3.3V current running through it that triggers the power on and off. The monitor itself is takes 12VDC to power. I know that a relay is used when switching larger power sources from a low voltage source so as not to damage the lower voltage source, but since the switch in question only runs at 3.3V would it be safe to use the Arduino without a relay?

I think that behind the switch you tested might be already a relay that switches the 12V.

It's always better to use MOSFET as a switch (or relay) like this:

It can handle loads up to 24V, 5A. The load is powered from an external supply. It is based on a IRF520 Mosfet and cost 0.55 a piece in Aliexpress. Search "Arduino IRF520 module"
You need one Arduino pin to switch on/off the load.
It's very handy and provide posts for power input/output.
I understand that you will still power the monitor from the wall, replacing only the original switch with Arduino. Otherwise, you will need a bigger relay

The monitor is actually being powered by a 12VDC battery. Will this MOSFET work with DC instead of AC? Could you add a link to where I can get this? Or possibly link to some more information on them?

Well; it's a MOSFET, so it's works only with DC. A MOSFET can only be used to control DC loads since it is a unidirectional switch - current flow can be controlled when it is flowing from drain to source, but can not be controlled from source to drain. Goto aliexpress.com and search "arduino irf520 module".


text:
Mapping string values
I have a bunch of thermometers (between 1 and 128). The thermometers have an internal OneWire ID such as "28edce1e500e5" and it is not readable by humans.
Normally I would make an associative array like this:
map["28edce1e500e5"] = "Temp1";
map["28ffd33b9116420"] = "Temp2";

Serial.print(map[printAddress(allDevices[i])]);
Serial.print(" : ");
Serial.print(sensors.getTempC(allDevices[i]));

But it looks like the only hashmap library for Arduino is no longer supported and appears to be quite expensive.
The solution does not have to involve associative array.
The values are populated from a JSON file, loaded from an SD card.
I'm looking for a solutiuon to the problem, not a way to implement an associative array. (Unless that's the best way to solve the problem)

What is your question? Where to find a library? How to implement an associative array?

There you go, i formulated it as a question now.

Actually the 1-Wire ROM identity is not a string. It is 8-bytes which actually includes a family code (1 byte) and a CRC code (1-byte). You can simply use uint64_t or uint8[8] instead. Put them sorted in a vector and use binary search for the mapping. The standard clib has support for that. http://www.nongnu.org/avr-libc/user-manual/group__avr__stdlib.html#ga885c1ccefb716ff16ab73a57003140be

Make a struct containing the name and id.
struct device{char[MAX_ID_LENGTH] id; char[MAX_NAME_LENGTH] name; }

Then store the those pairs in an array which you can have sorted by one field or the other. That way you can binary search on that field.

I cannot make it work with chars, but String it works, do you know what is wrong ?

Ok this is working and on the NodeMCU it got enough memory not to be a problem. Though it could be improved im going to accept this answer!

Taking the device structure from rachet freak's post you could implement a map of your own using something like this:
template  <class K, class V> class MyMap
{
public:
    MyMap()
    {
    }

    void Add(K key, V value)
    {
    }

    void Remove(K key)
    {
    }

    V operator[](const& K)
    {
    }

private:
}

But I think templates are expensive under Arduino so you might want to manually instantiate it to drop the template.


text:
Code runs, then doesn't run after I add some routine code
I am programming an ESP8266-01.
I have this code which I am using to operate an on-off switch, which is being used as an override switch for when the relay is turned on and off over the internet:
void loop() {

  // Connect to the cloud
  rest.handle(client);

  // put your main code here, to run repeatedly:
  int read3 = digitalRead(0);

  Serial.print(read3);
  Serial.println(" input (1 is off)");

  if(read3 == 0) {
    if(pressed2) {
      Serial.println("in on");
      digitalWrite(2, 1);
      pressed = true;
      pressed2 = false;
    }
  }
  else {
    Serial.println("in off");
    if(pressed) {
      Serial.println("in off once");
      digitalWrite(2, 0);
      pressed = false;
      pressed2 = true;
    }
  }
}

The above code never starts to run (nothing gets output on the serial) and the relay turns on. The thing is, this code works:
void loop() {

  // Connect to the cloud
  rest.handle(client);

  // put your main code here, to run repeatedly:
  int read3 = digitalRead(0);

  Serial.print(read3);
  Serial.println(" input (1 is off)");

  if(read3 == 0) {
    Serial.println("in on");
    digitalWrite(2, 1);
    pressed = true;
  }
  else {
    Serial.println("in off");
    if(pressed) {
      Serial.println("in off once");
      digitalWrite(2, 0);
      pressed = false;
    }
  }
}

Basically the way the code is set up, it is handling things so that the pin doesn't get read after the instance first instance that it is read (this is what the bool pressed is helping to do).
Why doesn't the first version work?
UPDATE
Whole working sketch:
/*
  This a simple example of the aREST Library for the ESP8266 WiFi chip.
  This example illustrate the cloud part of aREST that makes the board accessible from anywhere
  See the README file for more details.

  Written in 2015 by Marco Schwartz under a GPL license.
*/

// Import required libraries
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <aREST.h>

// Clients
WiFiClient espClient;
PubSubClient client(espClient);

// Create aREST instance
aREST rest = aREST(client);

// Unique ID to identify the device for cloud.arest.io
char* device_id = "ew1zard";

// WiFi parameters
const char* ssid = "MaisonBlanche";
const char* password = "7932gLBw";

bool pressed = true;

// Functions
void callback(char* topic, byte* payload, unsigned int length);

void setup(void)
{
  // Set input / output pin
  pinMode(0, INPUT);
  pinMode(2, OUTPUT);

  // Start Serial
  Serial.begin(115200);

  // Set callback
  client.setCallback(callback);

  // Give name & ID to the device (ID should be 6 characters long)
  rest.set_id(device_id);
  rest.set_name("esp8266");

  // Connect to WiFi
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected");

  // Set output topic
  char* out_topic = rest.get_topic();
}

void loop() {

  // Connect to the cloud
  rest.handle(client);

  // put your main code here, to run repeatedly:
  int read3 = digitalRead(0);

  Serial.print(read3);
  Serial.println(" input (1 is off)");

  if(read3 == 0) {
    Serial.println("in on");
    digitalWrite(2, 1);
    pressed = true;
  }
  else {
    Serial.println("in off");
    if(pressed) {
      Serial.println("in off once");
      digitalWrite(2, 0);
      pressed = false;
    }
  }
}

// Handles message arrived on subscribed topic(s)
void callback(char* topic, byte* payload, unsigned int length) {

  Serial.print("request from interwebs: ");
  Serial.println(topic);
  rest.handle_callback(client, topic, payload, length);

}

Post you complete, working sketch.

i updated my quesiton with the full sketch

Pin 0 is uses for communications. You are using both inside your sketch.

im pretty sure pin 3 and pin 1 are for serial on esp8266

pin 0 is just gpio...all i do to make it not work is add a bool variable at the top, ad an if statment, and the places where the bool gets set

yup, i dont understand how what i am adding could break it, is it having two bool variable declared up top? or maybe i need to add delay somewhere?

I used this - it does the same thing basically, just moved where the bool variables were.
if(read3 == 0) {
    if(pressed2) {
      Serial.println("in on");
      digitalWrite(2, 1);
      pressed2 = false;
    }
    pressed = true;
  }
  else {
    Serial.println("in off");
    if(pressed) {
      Serial.println("in off once");
      digitalWrite(2, 0);
      pressed = false;
    }
    pressed2 = true;
  }


text:
In a circuit with a switch and a pull-down resistor, why does the high impedance of the input not discourage current from flowing into pin?
I'm a beginner to Arduino and circuits. I've spent the last couple hours hung up on the concept of how current flows through switches and pull-down resistors, having read every thread and watched every YouTube video I could find on the subject.
I understand that pull-down (and pull-up) resistors are necessary in order to prevent pins from floating. What confuses me is that, if the input pins effectively have a built-in 100 megohm resistance (according to this page), then how is it that a 10k ohm pull-down resistor is enough to dissuade current from flowing directly into ground even when the switch is closed?
Here is a diagram of my circuit:

Am I conflating the high-impedance state of input pins with resistance more generally?
Would really appreciate any clarification on this. Thanks!

Huh? 5V across 10kohm is 500uA.

@IgnacioVazquez-Abrams Sorry, I'm not totally sure what you're getting at.

I'm not sure what your question means. Of course some current flows from the positive rail to ground when the button is closed. How much? Well...

@IgnacioVazquez-Abrams Ah, I'm wondering why all the current doesn't proceed across the resistor to ground when the switch is closed, given that there's a very high built-in resistance right before the pin. If I'm missing something really obvious, I apologize. You may be overestimating my knowledge here.

Ohm's Law

@IgnacioVazquez-Abrams Right, I feel like I have a working grasp of Ohm's Law, but can't see how it directly relates to my question. I've hit upon a mental block around how the current is flowing through this circuit from the point that it emerges from the closed switch / button. It seems to be skipping the path through the resistor and instead making its way through the wire into input 2. Is this correct?
Edit: The system is recommending I move this to chat to avoid a protracted discussion in the comments, but I don't have enough reputation to do that. Apologies if I'm making this hard.

Current goes through all possible paths simultaneously. A little goes into pin 2. A lot more goes through the resistor.

@IgnacioVazquez-Abrams Got it, thank you.

Yes, all of the current that flows goes through that resistor to ground.  That way almost all the voltage drops across that one resistor and you are able to read the voltage with the pin on the high side of it.  Only a very very small amount of current flows into the pin when you read a voltage.  It just needs to charge up a very small capacitor.

Thank you! Just to clarify high side vs low side (these terms are new to me) - in the diagram in my question, isn't my pin reading it on the low side, between ground and load? I'm getting my understanding of these concepts from this page. Let me know if I'm missing something.

@T.Peppers. In your circuit your input pin is connected to the low side: when your switch is open, you pin read 0V.

But when you press the button, your pin is on the high side of that resistor.  The button has almost no resistance compared to the resistor, so all the voltage drops across the resistor.


text:
Arduino Fails to Read Thermocouple on External Power
I'm having what I believe to be a power issue with an Arduino project. I've tried 3 different power supplies (all separately):

My computer via USB B
A 5V USB "outlet" via USB B
A 5V USB "outlet", through a 5V->9V boost converter, to the arduino's barrel jack

I can run the sketch without an issue when connected to my computer (supply 1), even if the computer is sleeping and the Arduino program is closed. However, when using supply 2 or 3, everything works EXCEPT reading the pilot light thermocouple through the MAX6675 module. It runs without throwing errors, but always reads 32.0 degrees F from the pilot light thermocouple. The other thermocouples run and update as expected.
Details:

Arduino Uno (bought ~November 2016)
Running Arduino 3 for programming (downloaded October 2017)
Code and Wiring Schematic below

Thanks for your help!
EDIT 1
I can run the Arduino with no problems off a small battery bank (like the kind you use to charge a phone with on the go). This isn't a permanent solution because the battery banks will only last 1-2 days powering the arduino. Anyway, I think this indicates that there's something to do with isolation/noise issues from the USB outlet, or something to do with not having a common ground.
Also, to clarify, the 5V USB outlet is powered by a 12V deep cycle battery, hooked up to a solar system with charge controller, other circuits, etc. I don't know if this is relevant, just trying to provide as much information as possible.
//-------------------------------------------------------------------------------------------
//--------------Inputs-----------------------------------------------------------------------

// DS18B20 Thermocouples
#include <Wire.h>
#include <OneWire.h>
#include <DallasTemperature.h>

// High temp thermocouple
#include <max6675.h>

// LCD Libraries
#include <Adafruit_RGBLCDShield.h>
#include <utility/Adafruit_MCP23017.h>
// The shield uses the I2C SCL and SDA pins. On classic Arduinos
// this is Analog 4 and 5 so you can't use those for analogRead() anymore
// However, you can connect other I2C sensors to the I2C bus and share
// the I2C bus.
Adafruit_RGBLCDShield lcd = Adafruit_RGBLCDShield();

// Set temperature
int heatSetTemp = 60; // deg F
int bandwidth = 2; // if temp is within "bandwidth" of set point, it's acceptable

float freshWaterTemp; // deg F, current fresh water temp
float insideTemp; // deg F, current indoor temp
float outsideTemp; // deg F, current outside temp
float pilotTemp; // deg F, pilot light temperature

boolean pilotIsOn = false;
char pilotIsOnText = 'n';
boolean gasIsOn = false;
char gasIsOnText = 'n';

// Set up high temp thermocouple
int pilotThermo_sck_pin = 10;
int pilotThermo_cs_pin = 9;
int pilotThermo_so_pin = 8;
MAX6675 pilotThermo(pilotThermo_sck_pin, pilotThermo_cs_pin, pilotThermo_so_pin);

// Set up pilot light solenoid relay
// pin 3 is saved for A/C control - to be implemented
int ac_relay_pin = 3;
int gasSolenoid_pin = 2;

// Pin 4 has a wire jammed in it - not used

// Set up ambient thermocouples
int freshWaterThermo_pin = 5;
int insideThermo_pin = 6;
int outsideThermo_pin = 7;

OneWire freshWaterThermo(freshWaterThermo_pin);
DallasTemperature freshWaterThermoSensor(&freshWaterThermo);
OneWire insideThermo(insideThermo_pin);
DallasTemperature insideThermoSensor(&insideThermo);
OneWire outsideThermo(outsideThermo_pin);
DallasTemperature outsideThermoSensor(&outsideThermo);

// Set up LCD for user interface
int firstLCDLine = 0;
boolean backlightIsOn = true;

//-------------------------------------------------------------------------------------------
//--------------Functions--------------------------------------------------------------------
void turnGasOn() {
  digitalWrite(gasSolenoid_pin, LOW);
  gasIsOn = true;
  gasIsOnText = 'y';
}

void turnGasOff() {
  digitalWrite(gasSolenoid_pin, HIGH);
  gasIsOn = false;
  gasIsOnText = 'n';
}

void blinkLED() {
  digitalWrite(LED_BUILTIN, HIGH);
  delay(100);
  digitalWrite(LED_BUILTIN, LOW);
  delay(100);
  digitalWrite(LED_BUILTIN, HIGH);
  delay(100);
  digitalWrite(LED_BUILTIN, LOW);
}

void writeTempsLine() {
  lcd.print("In:"); lcd.print(insideTemp, 1);
  lcd.print(" Out:"); lcd.print(outsideTemp, 1);
}

void writeSetLine() {
  lcd.print("Set:"); lcd.print(heatSetTemp);
  lcd.print(" Wt:"); lcd.print(freshWaterTemp, 1);
}

void writeGasLine() {
  lcd.print("P:"); lcd.print(pilotTemp, 1);
  lcd.print(" P:"); lcd.print(pilotIsOnText);
  lcd.print(" G:"); lcd.print(gasIsOnText);
}

void toggleBacklight() {
  if (backlightIsOn) {
    lcd.setBacklight(0x0);
    backlightIsOn = false;
  }
  else {
    lcd.setBacklight(0x1);
    backlightIsOn = true;
  }
}

//-------------------------------------------------------------------------------------------
//--------------Setup------------------------------------------------------------------------
void setup() {
  Serial.begin(9600);

  // Set up relay to gas solenoid
  pinMode(gasSolenoid_pin, OUTPUT);
  turnGasOff(); // Set solenoid to closed by default

  // Start DallasTemperature Library
  freshWaterThermoSensor.begin();
  insideThermoSensor.begin();
  outsideThermoSensor.begin();

  // set up the LCD's number of columns and rows:
  lcd.begin(16, 2);

  // Indicator LED
  pinMode(LED_BUILTIN, OUTPUT);
}
//-------------------------------------------------------------------------------------------
//--------------Main Program-----------------------------------------------------------------
void loop() {

  // Read Temperatures
  pilotTemp = pilotThermo.readFahrenheit();

  freshWaterThermoSensor.requestTemperatures();
  insideThermoSensor.requestTemperatures();
  outsideThermoSensor.requestTemperatures();
  freshWaterTemp = freshWaterThermoSensor.getTempFByIndex(0);
  insideTemp = insideThermoSensor.getTempFByIndex(0);
  outsideTemp = outsideThermoSensor.getTempFByIndex(0);

  // Check Pilot Light
  pilotIsOn = (pilotTemp > 300); // flame temp goes here in degF
  if (pilotIsOn) { pilotIsOnText = 'y'; }
  else { pilotIsOnText = 'n'; }

  // Actuate Relay
  if (insideTemp < (heatSetTemp - bandwidth)) // Temp too cold, gas not on yet
  {
    if(pilotIsOn) { turnGasOn(); }
    else { turnGasOff(); } // because pilot is off
  }
  else if (gasIsOn && insideTemp < heatSetTemp) // Temp still too cold, but gas already on
  {
    if(pilotIsOn) { //leave gas on
    }
    else { turnGasOff(); } // because pilot is off
  }
  else // Temp is hot enough
  {
    turnGasOff();
  }

  //Check for button presses
  uint8_t buttons = lcd.readButtons();
  if (buttons) {
    if (buttons & BUTTON_UP) {
      Serial.println("button up pressed");
      firstLCDLine++;
    }
    if (buttons & BUTTON_DOWN) {
      Serial.println("button down pressed");
      firstLCDLine--;
    }
    if (buttons & BUTTON_RIGHT) {
      Serial.println("button right pressed");
      heatSetTemp++;
    }
    if (buttons & BUTTON_LEFT) {
      Serial.println("button left pressed");
      heatSetTemp--;
    }
    if (buttons & BUTTON_SELECT) {
       Serial.println("button select pressed!!!");
       toggleBacklight();
    }
  }

  // Output to Serial Monitor
  Serial.println(String("Fresh Water: ") + freshWaterTemp);
  Serial.println(String("Inside: ") + insideTemp);
  Serial.println(String("Outside: ") + outsideTemp);
  Serial.println(String("Pilot: ") + pilotTemp);
  Serial.println(String("Pilot Is On: ") + pilotIsOn);
  Serial.println(String("Gas Is On: ") + gasIsOn);
  Serial.println(String("Heat Set Temp: ") + heatSetTemp);
  Serial.println(String("firstLCDLine: ") + firstLCDLine);
  Serial.println();

  // Output to LCD
  lcd.clear();
  if(firstLCDLine % 3 == 0) {
    lcd.setCursor(0, 0); writeTempsLine();
    lcd.setCursor(0, 1); writeGasLine();
  }
  else if (firstLCDLine % 3 == 1) {
    lcd.setCursor(0, 0); writeGasLine();
    lcd.setCursor(0, 1); writeSetLine();
  }
  else {
    lcd.setCursor(0, 0); writeSetLine();
    lcd.setCursor(0, 1); writeTempsLine();
  }

  // Automatic scrolling
  firstLCDLine++;

  // Indicate "heartbeat" of sketch
  //blinkLED();
}

Try to remove some power consumption, like the relay board.

@MatsK Thanks for the suggestion. I tried disconnecting the relay board, and it still runs exactly the same way. The only other thing I can think of that the LCD (this one from Adafruit) is drawing a lot of power, but it doesn't seem likely.

There is a method to troubleshoot and it's called reduce the circuit to a barebone and then add and see when it fails.


text:
Software Interrupts in Arduino or nodeMCU
The code given below is an example code I found on the internet. This is to use my nodeMCU as a server. For my application, I believe that these lines of code...:
if (request.indexOf("/LED=ON") != -1)  {
            digitalWrite(ledPin, HIGH);
            value = HIGH;
          }
          if (request.indexOf("/LED=OFF") != -1)  {
            digitalWrite(ledPin, LOW);
            value = LOW;
          }

... from the below program should run thereby interrupting every processes.
 #include <ESP8266WiFi.h>

    const char* ssid = "Linux"; // SSID i.e. Service Set Identifier is the name of your WIFI
    const char* password = "0123456789"; // Your Wifi password, in case you have open network comment the whole statement.

    int ledPin = 13; // GPIO13 or for NodeMCU you can directly write D7
    WiFiServer server(80); // Creates a server that listens for incoming connections on the specified port, here in this case port is 80.

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

      pinMode(ledPin, OUTPUT);
      digitalWrite(ledPin, LOW);

      // Connect to WiFi network
      Serial.println();
      Serial.println();
      Serial.print("Connecting to ");
      Serial.println(ssid);

      WiFi.begin(ssid, password);

      while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        Serial.print(".");
      }
      Serial.println("");
      Serial.println("WiFi connected");

      // Start the server
      server.begin();
      Serial.println("Server started");

      // Print the IP address
      Serial.print("Use this URL to connect: ");
      Serial.print("http://");
      Serial.print(WiFi.localIP()); //Gets the WiFi shield's IP address and Print the IP address of serial monitor
      Serial.println("/");

    }

    void loop() {
      // Check if a client has connected
      WiFiClient client = server.available();
      if (!client) {
        return;
      }

      // Wait until the client sends some data
      Serial.println("new client");
      while(!client.available()){
        delay(1);
      }

      // Read the first line of the request
      String request = client.readStringUntil('\r');
      Serial.println(request);
      client.flush();

      // Match the request

      int value = LOW;
      if (request.indexOf("/LED=ON") != -1)  {
        digitalWrite(ledPin, HIGH);
        value = HIGH;
      }
      if (request.indexOf("/LED=OFF") != -1)  {
        digitalWrite(ledPin, LOW);
        value = LOW;
      }

    // Set ledPin according to the request
    //digitalWrite(ledPin, value);

      // Return the response
      client.println("HTTP/1.1 200 OK");
      client.println("Content-Type: text/html");
      client.println(""); //  do not forget this one
      client.println("<!DOCTYPE HTML>");
      client.println("");

      client.print("Led pin is now: ");

      if(value == HIGH) {
        client.print("On");
      } else {
        client.print("Off");
      }
      client.println("

");
      client.println("<button>Turn On </button>");
      client.println("<button>Turn Off </button>
");
      client.println("");

      delay(1);
      Serial.println("Client disconnected");
      Serial.println("");

    }

How can we achieve this kind of software Interrupt(s)?
PS: Timer Interrupt won't work -- I believe.

That doesn't need an interrupt.  Think about it, just check it right after you read it from the client.  So the response will be immediate.  It's not like it can suddenly become true at some other point without being read from the client.  You're already using a blocking read so if the first part of the message has arrived you'll stop right there and wait for it.  The loop should turn over really fast, keep it fast and non-blocking anywhere else and you can count on even if the message starts coming in immediately after your read the loop will make it back around to read again before the end of the message gets there.

+Delta_G I think I couldn't make my problem clear. When there are some other additional code (which are not shown here) within loop(), I think we do need interrupt. That's why we need a software interrupt.

Why do you think that?  How will either of those conditions ever become true except in concert with a read from the client?  If you think this other code causes some problem then please edit the question and post it.  But I stand by this answer.  The stuff coming in from the client is very very slow.  You have a lot of time between the time that the message starts the arrive and the point where it ends that you could do a lot of other things in that long time.

As long as you get back to the point where you read at some point during your message, your code will stop there and not do the other things until the message is complete since you use readString.  So the only thing that your interrupt could possibly ever interrupt is the next line after the readString command which is the section that you want to put in the interrupt.  If you think about the overhead of an interrupt vs just letting the code hit that next line, the interrupt would actually make your code slower and add more lag.

+Delta_G Thank you that seemed to work. But I still have one more problem: Because of these lines
if (!client) {
return;
}
  // Wait until the client sends some data
  Serial.println("new client");
  while(!client.available()){
    delay(1);
  }

the rest of embedded system project has become so slow. How can I run these code alongside my actual embedded system project?

The while(!client.available()) line says, stop right here and do absolutely nothing until we get some message from the client.  Then you use readString() which also waits until the transmission ends.  That's blocking code, it stops the program to wait on something.  If you don't want it to work like that you'll have to do a lot of rewriting.


text:
How to connect Arduino Nano with ESP8266 and BMP180?
I have an issue with my application.
Hardware used:

ESP8266 Serial Wi-Fi Wireless Transceiver Module for IOT
Robodyn Micro USB Compatible for Arduino Nano V3.0 ATmega168 CH340G
SENSOR: BMP180

Connections:

Arduino Nano to ESP8266
CH-PD to Vcc
GPIO0 to GND
Rx to Rx
Tx to Tx
3.3v to 3.3v
Reset to GND
GND to GND

Arduino Nano to BMP180

3.3v to VIN
GND to GND
A5 to SCL
A4 to SDA

Sketch used (uploaded in Generic ESP8266 Board):
#include <DHT.h> //  DHT.h library
#include <ESP8266WiFi.h> // ESP8266WiFi.h library
#include <SFE_BMP180.h>
#include <Wire.h>

SFE_BMP180 pressure;

const char* ssid     = "GOPI-LAPTOP";
const char* password = "kcejava123";
const char* host = "api.thingspeak.com";
const char* writeAPIKey = "CQSHDFP4EZFCDWKO";

void setup() {
  // Initialize sensor
  Serial.begin(9600);
  delay(1000);
  if (pressure.begin())
    Serial.println("BMP180 init success");
  else {
    Serial.println("BMP180 init fail\n\n");
  }
  //  Connect to WiFi network
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
  }
}

void loop() {
  char status;
  double T, P, p0, a;
  status = pressure.startTemperature();
  if (status != 0) {
    // Wait for the measurement to complete:
    delay(status);
    status = pressure.getTemperature(T);
    if (status != 0) {
      // Print out the measurement:
      Serial.print("temperature: ");
      Serial.print(T,2);
      Serial.print(" deg C, ");
      Serial.print((9.0/5.0)*T+32.0,2);
      Serial.println(" deg F");
    } else
      Serial.println("error retrieving pressure measurement\n");
  }
  status = pressure.startPressure(3);
  if (status != 0) {
    delay(status);
    status = pressure.getPressure(P, T);
    if (status != 0) {
      // Print out the measurement:
      Serial.print("absolute pressure: ");
      Serial.print(P, 2);
      Serial.print(" mb, ");
      Serial.print(P*0.0295333727, 2);
      Serial.println(" inHg");
      p0 = 1013.25; // we're at 1655 meters (Boulder, CO)
      Serial.print("relative (sea-level) pressure: ");
      Serial.print(p0, 2);
      Serial.print(" mb, ");
      Serial.print(p0*0.0295333727, 2);
      Serial.println(" inHg");
      a = pressure.altitude(P, p0);
      Serial.print("computed altitude: ");
      Serial.print(a, 0);
      Serial.print(" meters, ");
      Serial.print(a*3.28084, 0);
      Serial.println(" feet");
    }
  }
  // make TCP connections
  WiFiClient client;
  const int httpPort = 80;
  if (!client.connect(host, httpPort)) {
    return;
  }
  String url = "/update?key=";
  url+=writeAPIKey;
  url+="&field1=";
  url+=String(T);
  url+="&field2=";
  url+=String(P);
  url+="\r\n";
  // Request to the server
  client.print(String("GET ") + url + " HTTP/1.1\r\n" +
    "Host: " + host + "\r\n" +
    "Connection: close\r\n\r\n");
  Serial.print(String("GET ") + url + " HTTP/1.1\r\n" +
    "Host: " + host + "\r\n" +
    "Connection: close\r\n\r\n");
  delay(30000);
}

Serial Output:
BMP180 init fail

GET /update?key=CQSHDFP4EZFCDWKO&field1=8.04&field2=8.08
 HTTP/1.1
Host: api.thingspeak.com
Connection: close

GET /update?key=CQSHDFP4EZFCDWKO&field1=8.04&field2=8.08
 HTTP/1.1
Host: api.thingspeak.com
Connection: close

Queries:
• How to enable BMP180 to sense? When I configure BMP180 with Arduino (without ESP8266), I get the output in the serial terminal.
• How to send data to Thingspeak.com from BMP180 using the specified hardware?

I get the feeling you are getting a little confused about what is doing what. It looks like you are using the Arduino as a USB to UART converter, and programming the ESP8266 - and then connecting the BMP180 to the Arduino which you aren't programming and isn't even running.

why not just run the BMP from the ESP?

Connections:
[...]

Rx to Rx
Tx to Tx

That's not gonna fix your problem with initializing the BMP180, but you have to cross the lines, Rx to Tx and Tx to Rx, if you want to get anything on the serial terminal... Besides, your Nano is 5V, your ESP 3.3V. Connecting directly the Nano's Rx/Tx lines at 5V to the ESP's Rx/Tx 3.3V lines might not be very safe.
As for the BMP180, is it rated for 3.3V, or only 5V? If it is 5V only, it might not work on the ESP. Hence the init fail.

For I2C to work you must have pull up resistors.  Normally 4.7K connected between SCL and VIN and SDA and VIN make thinks work.
You probably should use a logic level convertor to convert 3.3 to 5V (not a resistor divider, not sharp enough edges for digital signals).  If I remember correctly the ESP can take 7V on its pins before you kill it (its in the chip spec) but that doesn't mean its a good idea to do it.
As mentioned above you need to cross the serial leads to make the connection.  The Nano's Rx lead needs to be connected to the ESP's Tx lead and vice versa.