text:
ESP8266 working as station while in AP mode
I'm programming an ESP8266 via the Arduino IDE with Arduino libraries.  I explicitly set the WiFi mode to WIFI_AP, but then, as described below, I'm still able to use it as both AP and station.  That leaves me unclear what's meant by the three modes available (WIFI_AP, WIFI_STA, and WIFI_AP_STA) since it seems that I've set to WIFI_AP explicitly but am getting behavior consistent with WIFI_AP_STA.
I have read various documents online about these modes. I think I'm clear on the conceptual difference between them.  What concerns / confuses me is that the actual behavior does not appear to match the specified behavior.
More detail:
Near the beginning of my setup function, I have this code
WiFi.mode(WIFI_AP);
WiFi.softAP(ssid, key);

server.begin();

where ssid and key are strings defined with appropriate values, and server is a global variable of type WiFiServer that has been initialized outside of setup.  When run, I see the network with the given name on my phone and can connect to it with the given password.  I can then browse to the IP address assigned by the ESP8266 and set the webpage sent by the server that's been defined in code.  So far so good.
At some point later, inside my loop, a condition triggers the ESP8266 to connect to my router.  Specifically, I have this sequence of code that runs once that trigger occurs:
WiFi.disconnect();
WiFi.begin(router_ssid, router_key);
auto status = WiFi.status();
while ( (status != WL_CONNECTED) && (status != WL_CONNECT_FAILED) ) {
    delay(500);
    status = WiFi.status();
}

As before, router_ssid and router_key are variables declared elsewhere with the proper values for my router.  I can verify from subsequent print statements, that the connection succeeds and get the IP address as assigned by my router. It is clear that the new IP is assigned by the router because it is on the subnet used by my router, which is different than the subnet the ESP8266 is defining in AP mode.
The ESP8266 is configured to serve a small webpage, as noted above. I can now reach that page using my phone, which is connected directly to the ESP8266 via the IP address assigned initially by the ESP8266 in AP mode, and I can also reach the same page from my laptop (connect to my router) using the IP address assigned by my router.  It would seem that I'm effectively in "AP+STA" mode now, despite having explicitly set to "AP" mode at the beginning.
So what's happening here?  Did I automatically switch to "AP+STA" mode when I called WiFi.begin?  If yes, what's the point (if any) of calling WiFi.mode?  If no, then why am I able to operate as if in "AP+STA" mode given the explicit setting of "AP" mode?

WiFi.begin() is a function of the ESP8266WiFiSTAClass. It changes the WiFi mode for you to STA or AP+STA based on the current mode.
begin functions are in ESP8266WiFiSTA
enableSTA function is in class ESP8266WiFiGeneric


text:
Parsing example code in Adafruit GPS library with Ultimate Adafruit GPS
I've synced my Uno with the Arduino IDE and I'm using the below code to get the GPS coordinates.
// Test code for Adafruit GPS modules using MTK3329/MTK3339 driver
//
// This code shows how to listen to the GPS module in an interrupt
// which allows the program to have more 'freedom' - just parse
// when a new NMEA sentence is available! Then access data when
// desired.
//
// Tested and works great with the Adafruit Ultimate GPS module
// using MTK33x9 chipset
//    ------> http://www.adafruit.com/products/746
// Pick one up today at the Adafruit electronics shop
// and help support open source hardware & software! -ada

#include <Adafruit_GPS.h>
#include <SoftwareSerial.h>

// If you're using a GPS module:
// Connect the GPS Power pin to 5V
// Connect the GPS Ground pin to ground
// If using software serial (sketch example default):
//   Connect the GPS TX (transmit) pin to Digital 3
//   Connect the GPS RX (receive) pin to Digital 2
// If using hardware serial (e.g. Arduino Mega):
//   Connect the GPS TX (transmit) pin to Arduino RX1, RX2 or RX3
//   Connect the GPS RX (receive) pin to matching TX1, TX2 or TX3

// If you're using the Adafruit GPS shield, change
// SoftwareSerial mySerial(3, 2); -> SoftwareSerial mySerial(8, 7);
// and make sure the switch is set to SoftSerial

// If using software serial, keep this line enabled
// (you can change the pin numbers to match your wiring):
SoftwareSerial mySerial(3, 2);

// If using hardware serial (e.g. Arduino Mega), comment out the
// above SoftwareSerial line, and enable this line instead
// (you can change the Serial number to match your wiring):

//HardwareSerial mySerial = Serial1;

Adafruit_GPS GPS(&mySerial);

// Set GPSECHO to 'false' to turn off echoing the GPS data to the Serial console
// Set to 'true' if you want to debug and listen to the raw GPS sentences.
#define GPSECHO  true

// this keeps track of whether we're using the interrupt
// off by default!
boolean usingInterrupt = false;
void useInterrupt(boolean); // Func prototype keeps Arduino 0023 happy

void setup()
{

  // connect at 115200 so we can read the GPS fast enough and echo without dropping chars
  // also spit it out
  Serial.begin(115200);
  Serial.println("Adafruit GPS library basic test!");

  // 9600 NMEA is the default baud rate for Adafruit MTK GPS's- some use 4800
  GPS.begin(9600);

  // uncomment this line to turn on RMC (recommended minimum) and GGA (fix data) including altitude
  GPS.sendCommand(PMTK_SET_NMEA_OUTPUT_RMCGGA);
  // uncomment this line to turn on only the "minimum recommended" data
  //GPS.sendCommand(PMTK_SET_NMEA_OUTPUT_RMCONLY);
  // For parsing data, we don't suggest using anything but either RMC only or RMC+GGA since
  // the parser doesn't care about other sentences at this time

  // Set the update rate
  GPS.sendCommand(PMTK_SET_NMEA_UPDATE_1HZ);   // 1 Hz update rate
  // For the parsing code to work nicely and have time to sort thru the data, and
  // print it out we don't suggest using anything higher than 1 Hz

  // Request updates on antenna status, comment out to keep quiet
  GPS.sendCommand(PGCMD_ANTENNA);

  // the nice thing about this code is you can have a timer0 interrupt go off
  // every 1 millisecond, and read data from the GPS for you. that makes the
  // loop code a heck of a lot easier!
  useInterrupt(true);

  delay(1000);
  // Ask for firmware version
  mySerial.println(PMTK_Q_RELEASE);
}

// Interrupt is called once a millisecond, looks for any new GPS data, and stores it
SIGNAL(TIMER0_COMPA_vect) {
  char c = GPS.read();
  // if you want to debug, this is a good time to do it!
#ifdef UDR0
  if (GPSECHO)
    if (c) UDR0 = c;
    // writing direct to UDR0 is much much faster than Serial.print
    // but only one character can be written at a time.
#endif
}

void useInterrupt(boolean v) {
  if (v) {
    // Timer0 is already used for millis() - we'll just interrupt somewhere
    // in the middle and call the "Compare A" function above
    OCR0A = 0xAF;
    TIMSK0 |= _BV(OCIE0A);
    usingInterrupt = true;
  } else {
    // do not call the interrupt function COMPA anymore
    TIMSK0 &= ~_BV(OCIE0A);
    usingInterrupt = false;
  }
}

uint32_t timer = millis();
void loop()                     // run over and over again
{
  // in case you are not using the interrupt above, you'll
  // need to 'hand query' the GPS, not suggested :(
  if (! usingInterrupt) {
    // read data from the GPS in the 'main loop'
    char c = GPS.read();
    // if you want to debug, this is a good time to do it!
    if (GPSECHO)
      if (c) Serial.print(c);
  }

  // if a sentence is received, we can check the checksum, parse it...
  if (GPS.newNMEAreceived()) {
    // a tricky thing here is if we print the NMEA sentence, or data
    // we end up not listening and catching other sentences!
    // so be very wary if using OUTPUT_ALLDATA and trytng to print out data
    //Serial.println(GPS.lastNMEA());   // this also sets the newNMEAreceived() flag to false

    if (!GPS.parse(GPS.lastNMEA()))   // this also sets the newNMEAreceived() flag to false
      return;  // we can fail to parse a sentence in which case we should just wait for another
  }

  // if millis() or timer wraps around, we'll just reset it
  if (timer > millis())  timer = millis();

  // approximately every 2 seconds or so, print out the current stats
  if (millis() - timer > 2000) {
    timer = millis(); // reset the timer

    Serial.print("\nTime: ");
    Serial.print(GPS.hour, DEC); Serial.print(':');
    Serial.print(GPS.minute, DEC); Serial.print(':');
    Serial.print(GPS.seconds, DEC); Serial.print('.');
    Serial.println(GPS.milliseconds);
    Serial.print("Date: ");
    Serial.print(GPS.day, DEC); Serial.print('/');
    Serial.print(GPS.month, DEC); Serial.print("/20");
    Serial.println(GPS.year, DEC);
    Serial.print("Fix: "); Serial.print((int)GPS.fix);
    Serial.print(" quality: "); Serial.println((int)GPS.fixquality);
    if (GPS.fix) {
      Serial.print("Location: ");
      Serial.print(GPS.latitude, 4); Serial.print(GPS.lat);
      Serial.print(", ");
      Serial.print(GPS.longitude, 4); Serial.println(GPS.lon);
      Serial.print("Location (in degrees, works with Google Maps): ");
      Serial.print(GPS.latitudeDegrees, 4);
      Serial.print(", ");
      Serial.println(GPS.longitudeDegrees, 4);

      Serial.print("Speed (knots): "); Serial.println(GPS.speed);
      Serial.print("Angle: "); Serial.println(GPS.angle);
      Serial.print("Altitude: "); Serial.println(GPS.altitude);
      Serial.print("Satellites: "); Serial.println((int)GPS.satellites);
    }
  }
}

When I compile and upload, it successfully does and the serial output displays something like this:
Time: 23:5:8.0
Date: 6/7/2018
Fix: 1 quality: 1
Location: 3855.8869N, 7721.3422W
Location (in degrees, works with Google Maps): 38.9314, -77.3557
Speed (knots): 0.32
Angle: 211.87
Altitude: 177.90
Satellites: 7
$PGTOP,11,2*6E
$GPGGA,230509.000,3855.8869,N,07721.3423,W,1,7,1.10,177.9,M,-33.4,M,,*64
$GPRMC,230509.000,A,3855.8869,N,07721.3423,W,0.28,211.87,060718,,,A*7F
$PGTOP,11,2*6E
$GPGGA,230510.000,3855.8869,N,07721.3424,W,1,7,1.10,177.9,M,-33.4,M,,*6B
$GPRMC,230510.000,A,3855.8869,N,07721.3424,W,0.28,211.87,060718,,,A*70
Everything seems okay except that the time is also offset by 4 hours?

GPS is probably giving you universal time (UTC).  Your profile says that you're in College Park, MD, so that's currently 4 hrs different due to daylight savings time.

Oh, I didn't know it gives UTC. Is that the norm or can be customized?

You customize it by adding 4. :)  GPS gives UTC as a standard. (EST is UTC -5, EDT is UTC -4.)

source: Stack Exchange

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

sort: votes


text:
Serial.print changes serial output before it is called
I'm making a project with an sd card where the user enters a file name over the serial port, and then the aduino does thing to that file. Right now i'm working on getting the serial input to work, but one Serial.print() is somehow changing a variable/output of another Serial.print(), but before it is even called.
Here is my code:
char input, output;
void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);
  Serial.println("Ready\nEnter input text");
  while (!Serial.available()); // wait till serial available
  delay(2000);
  byte avail = Serial.available() - 1;//extra newline char at end that we don't want
  char inBuf[avail];
  //Serial.println(avail);
  Serial.readBytes(inBuf, avail);
  Serial.read();
  Serial.print("'");
  Serial.print(inBuf);
  Serial.println("'");
  delay(1000);
  Serial.println(avail);//problematic line
}

void loop() {
  // put your main code here, to run repeatedly:

}

When i have the line uncommented, the output is:
Ready
Enter input text
'asd&.'
4

When all i have typed is 'asd' (no quotes).
With the line commented out, the output is as expected:
Ready
Enter input text
'asd'

I have no clue how it is happening, and should be physically impossible, since it is changing code before it is called.

Your string needs to end with a null character '\0'.  I think yours does not because of the way that you filled the buffer, so you're getting whatever junk is in memory next to your array printed in addition to the array itself.

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


text:
Updating Server using ESp8266 with Direction Button Pressed IN
I've connected a 5-way tactile switch to a ESP8266 module and am using the Arduino IDE to create an automatically updating web server that displays the direction that the button is pressed in when pressed. Currently the webpage displays the first direction that the button was pressed in but does not update the page after I press the button several more times. Below is my code:
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>

//ssid and password info, ommitted here for obvious reasons

int upPin = 5;
int leftPin = 4;
int centerPin = 0;
int rightPin = 2;
int downPin = 14;

ESP8266WebServer server ( 80 );

void handleRoot() {
    server.send(200, "text/html", "\
  \
    <meta http-equiv='refresh' content='1'/>\
  \
  \
  \
");   // Send HTTP status 200 (Ok) and send some text to the
browser/client
}

void setup(){
 Serial.begin ( 115200 );
 WiFi.mode ( WIFI_STA );
 WiFi.begin ( ssid, password );

 server.on ( "/", handleRoot );
 server.on ("/", button );
 server.begin();

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

void button(){
  if (digitalRead(rightPin) == LOW)
  {
    server.send(200, "text/html", "
*RIGHT#
");
    delay(10);
  }

  if (digitalRead(leftPin) == LOW)
  {
    server.send(200, "text/html", "
*LEFT#
");
    delay(10);
  }

  if (digitalRead(upPin) == LOW)
  {
    server.send(200, "text/html", "
*UP#
");
    delay(10);
  }

  if (digitalRead(downPin) == LOW)
  {
    server.send(200, "text/html", "
*DOWN#
");
    delay(10);
  }

  if (digitalRead(centerPin) == LOW)
  {
    server.send(200, "text/html", "
*CENTER#
");
    delay(10);
  }

}

so / is root or button? do you hold a switch all the time?

I changed the code so that the button function runs with "/" and took out the server.on("/", handleRoot) line, thanks to @Juraj. Sigh


text:
Wiring for Arduino Mega and multiple MPU 6050/Gy 521?
I have an Arduino Mega 2560 that I need to connect 4 MPU 6050/Gy 521's to.
I found some resources on the Mega and Uno, however I'm having trouble piecing them together.
This resource gives great detail for connecting a single MPU to a mega.
http://dummyscodes.blogspot.com/2014/07/mpu6050-gy-521-breakout-arduino-mega.html
This resource gives a trick for connecting multiple to an UNO.
https://playground.arduino.cc/Main/MPU-6050
My problem is that the wiring for the Uno and Mega are different. The resource I have for the UNO describes using the MPU AD0 (output) connecting it to different output pins for each MPU. The resource talking about the MEGA doesn't even use the AD0, and uses INT but I'm not sure if I can use the same concept.
Plus, I still don't actually understand how to connect/what other pins to use for the other 4.
I'm pretty new to Arduino, definitely new to anything with wiring.
Please help! I'm really confused about using multiple together, and about how to properly wire them.

MPU-6050 uses I2C for comm's, yes?
Connect all the SCLs in parallel to the Mega with a 4.7K, or 3.3K, pullup resistor. Same for the SDAs. I2C is D20, D21 (or D21, D22) on the Mega.
The MPU-6050 has an A0 pin to select from one of two addresses, let's call them Add0 and Add1 for simplicilty.
Connect each MPU-6050 A0 pin to a unique Mega pin.  When none are being addressed, have each Mega output high. When one MPU-6050 is to be accessed, take that device's A0 pin low and communicate with it using Add0. The other's will be looking for communications at Add1 and thus will not respond.
If the MPU6050 is a 3.3V device, then you should also remove the pullup resistor network package on the Mega that pulls SCL/SDA to 5V.  There are 2 pullups in a very little 8-pin package, the other 2 are not used. Connect the 3.3K or 4.7K pullup resistors discussed above to 3.3V.

This is the part, RN1, on the Mega R3 board. It may not be marked as such on the board. Remove it, or cut the traces next to the pad legs, one on the left side (connects to pin 3), one on the top (connects to pin 2).

I didn't know about the pullup resistor package on the Mega's I2C bus. Is that meant to be removable/replaceable, or do you have to snap it off destructively?

I wouldn't snap it off, but it would come without too much difficulty with a soldering iron.

CrossRoads' answer using the address selection pin on your MPU modules is excellent. It does tie up a GPIO line for each MPU you want to address however.
(If you are using a Mega 2560 this might not be an issue since they have tons of GPIO lines.)
You could also get a I2C addressing multiplexer. Adafruit and Sparkfun both offer them Example: https://www.adafruit.com/product/2717?gclid=EAIaIQobChMItYnah7zB4QIVAoTICh1JlAk3EAQYASABEgK7hvD_BwE
That one will multiplex up to 8 I2C devices with the same address, and doesn't require any additional pins. You send a single I2C command to it to select one of your 8 devices.
I don't know if anybody makes an I2C multiplexer that also does voltage conversion. Seems like that would be handy.


text:
How to turn off or stop Access Point network in ESP8266?
I've created a code for ESP8266 12E with Arduino IDE, in which it'll operate as "Station Mode" or "Access Point Mode" on Wifi, depending on the situation. Everything works fine except when device was configured as Access Point, even when I turn off device and then turn on again and force the Wifi initialization as "Station Mode", the Access Point network stays active.
Example: Let's suppose that I turned on the ESP8266 and initialized the Wifi as Access Point, and named the wifi network as "MY_WIFI_TEST". Let's assume now that I turned off the ESP8266 and forced it to turn on as "Station Mode". The ESP8266 typically connects to my network (the network of my gateway router 192.168.1.1), but keeps the network "MY_WIFI_TEST" active (the prior network as access point). You can not connect to this network, but it remains active.
How can I turn off or stop Access Point network?
My test code:
    #include <ESP8266WiFi.h>

    bool access_point_init(){
        // Access Point Mode

       Serial.begin(115200);
       IPAddress ip(192,168,1,254);
       IPAddress gateway(192,168,1,1);
       IPAddress subnet(255,255,255,0);
       char* ssid     = "myssidname";
       char* password = "12345678";

       WiFi.softAPConfig(ip, gateway, subnet);
       bool ret = WiFi.softAP(ssid, password);

       return ret;
    }

    void wifi_station_init(){

        // Station Mode
        Serial.begin(115200);
       Serial.printf("\n");

       WiFi.begin(net_ssid, net_pwd_ssid);

       IPAddress ip(192,168,1,10);
       IPAddress gateway(192,168,1,1);
       IPAddress subnet(255,255,255,0);

        WiFi.config(ip, gateway, subnet);

       k = 0;
       while ((WiFi.status() != WL_CONNECTED) && (k < 80)){
          delay(250);
          Serial.print('.');
          k++;
       }

       Serial.printf("\n");
       Serial.printf("IP address: ");
       Serial.println(WiFi.localIP());
    }

    void setup()
    {
        bool my_condition = false;
        //...
        // my_condition = myLoadFunction();
        //...

       if (my_condition) {
            access_point_init();
       } else {
          wifi_station_init();
       }
    }

I've already solved, by using a function of the library Wifi, specific for the connections in "Access Point" mode:
WiFi.softAPdisconnect (true);

Reference:
softapdisconnect

I fixed this by adding below command before starting the accesspoint.
 WiFi.mode(WIFI_AP);

I was trying to turn off the softAP in the new Arduino Uno R4 Wifi so I could rename it and restart it. I put a changing sensor reading in AP name so I can see the value of it by just doing a network scan without actually connecting to it.
The wifi.h lib for UNO R4 doesn't implement SOFTAPDISCONNECT. In the example AP_SIMPLEWEB server I found adding the following function shuts down the AP and allows restarting with a different name.
void endAccessPoint() {
  using namespace std;
  string res = "";
  modem.begin();
  modem.write(string(PROMPT(_DISCONNECTSOFTAP)),res,"%s%d\r\n" ,CMD_WRITE(_DISCONNECTSOFTAP),1);
}


text:
NodeMCU (Arduino IDE) 'DynamicJsonBuffer' was not declared in this scope
#include <Arduino.h>
#include <ESP8266WiFi.h>
#include <ESP8266WiFiMulti.h>
#include <ArduinoJson.h>
#include <ESP8266HTTPClient.h>
#define USE_SERIAL Serial

ESP8266WiFiMulti WiFiMulti;
String url = "http://192.168.31.170/api/mode/qwertyui";

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

  USE_SERIAL.println();
  USE_SERIAL.println();
  USE_SERIAL.println();

  for (uint8_t t = 4; t > 0; t--) {
    USE_SERIAL.printf("[SETUP] WAIT %d...\n", t);
    USE_SERIAL.flush();
    delay(1000);
  }

  WiFi.mode(WIFI_STA);
  WiFiMulti.addAP("Robotics Incubator", "XXXXXXX");
}

void loop() {
  // wait for WiFi connection
  if ((WiFiMulti.run() == WL_CONNECTED)) {
    HTTPClient http;
    http.begin(url); //HTTP
    int httpCode = http.GET();

    if (httpCode == 200) {
      // Parsing
      const size_t bufferSize = JSON_OBJECT_SIZE(1) + 50;
      DynamicJsonBuffer jsonBuffer(bufferSize);  //This was not declared error.
      JsonObject& root = jsonBuffer.parseObject(http.getString());
      // Parameters
      int Mode = root["mode"]; // 1
      Serial.print("Name:");
      Serial.println(Mode);
    }
    http.end();
  }

  if (Serial.available()) {
    url = Serial.readString();
  }
  delay(100);
}

How can I solve this problem?
I followed this tutorial - ESP8266: Parsing JSON

This error is caused by using a 6.x.x version of the ArduinoJson library with code that was written for a pre-6.x.x version of the library.
You have two options to solve the problem:
A. Downgrade the library to a version that is compatible with your code
For now, this is probably the best option because the 6.x.x version of the ArduinoJson is still in beta so it makes sense to wait until the new API is stabilized before porting your code. This is even recommended by the ArduinoJson developers:
https://arduinojson.org/v5/faq/error-jsonbuffer-was-not-declared-in-this-scope/

Sketch > Include Library > Manage Libraries...
Wait for the download to finish.
In the "Filter your search..." box, type: "arduinojson".
Click on "ArduinoJson by Benoit Blanchon".
From the "Select version" dropdown menu, select "Version 5.13.2".
Click "Update". Wait for the update to finish.
Click "Close".

Now your code will compile. If you have File > Preferences > Check for updates on startup enabled, you will continue to get updatable library notification for the ArduinoJson library but you need to refrain from updating back to a 6.x.x version or the error will come back.
B. Update your code to be compatible with the 6.x.x version of the ArduinoJson library
In this case you need to modify your deserialization code to use the new DynamicJsonDocument instead of the old DynamicJsonBuffer:
if (httpCode == 200) {
  // Parsing
  const size_t bufferSize = JSON_OBJECT_SIZE(1) + 50;
  DynamicJsonDocument jsonDocument(bufferSize);
  DeserializationError error = deserializeJson(jsonDocument, http.getString());
  if (error) {
    Serial.println("There was an error while deserializing");
  }
  else {
    JsonObject root = jsonDocument.as<JsonObject>();
    // Parameters
    int Mode = root["mode"]; // 1
    Serial.print("Name:");
    Serial.println(Mode);
  }
}

You can get more details about this here:
https://arduinojson.org/v6/doc/upgrade/

This answer needs to be updated for anyone who visits here.
The 6.x.x is no longer in beta.
Simply update to the latest version. At the time of writing this answer the version id is 6.15.2. Updating to this will resolve the error.


text:
Fade effect analog RGB strip and NodeMCU
I have an analog or dumb RGB strip that I control with HTTP commands. I want to be able to make the strip fade between different colours when I call http://XX.X.X.XXX/fade. I want it to do this infinitely until another colour is set or it turns on or off. I have tried doing this with a while loop but I can no longer change the state of the light from fading. Does anyone know how to do this? I'll link my code below.
//NodeMCU RGB-Controller for Homebridge & HomeKit (Siri)

#include <ESP8266WiFi.h>

#include <DNSServer.h>
#include <ESP8266WebServer.h>

#define redPin 13 //D7 - Red channel
#define grnPin 12 //D6 - Green channel
#define bluPin 14 //D5 - Blue channel

#define max(a,b) ((a)>(b)?(a):(b))

WiFiServer server(80); //Set server port

String readString;           //String to hold incoming request
String hexString = "FFFFFF"; //Define inititial color here (hex value), 080100 would be a calm warmtone i.e.

int state;

bool fading;

int r;
int g;
int b;

float R;
float G;
float B;

int x;
int V;

///// WiFi SETTINGS - Replace with your values /////////////////
const char* ssid = "SSID";
const char* password = "PASSWORD";
IPAddress ip(XX,X,X,XXX);      // set a fixed IP for the NodeMCU
IPAddress gateway(XX.X.X.X);  // Your router IP
IPAddress subnet(XXX.XXX.XXX.X); // Subnet mask
////////////////////////////////////////////////////////////////////

void WiFiStart() {
  Serial.print("Connecting to ");
  Serial.println(ssid);
  WiFi.begin(ssid, password);
  WiFi.config(ip, gateway, subnet); //Set a fixed IP. You can comment this out and set it in your router instead.
  while (WiFi.status() != WL_CONNECTED) {
    delay(100);
    Serial.print("_");
  }
  Serial.println();
  Serial.println("Done");
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());
  Serial.println("");

  server.begin();
}

void allOff() {
  state = 0;
  for (float fade = 1.0; fade >= 0.0; fade -= 0.01) {
    analogWrite(redPin, map((r * fade), 0, 255, 0, 1023));
    analogWrite(grnPin, map((g * fade), 0, 255, 0, 1023));
    analogWrite(bluPin, map((b * fade), 0, 255, 0, 1023));
    delay(2);
  }
  // Set r/g/b to 0 so fade in is possible
  r = 0;
  b = 0;
  g = 0;
}

//Write requested hex-color to the pins
void setHex() {
  const float STEPS = 100; // Change number of steps while fading (lower is faster)
  // Save old values of r/g/b
  byte oldR = r;
  byte oldG = g;
  byte oldB = b;
  long number = (long) strtol( &hexString[0], NULL, 16);
  r = number >> 16;
  g = number >> 8 & 0xFF;
  b = number & 0xFF;
  float deltaR = (r - oldR) / STEPS;
  float deltaG = (g - oldG) / STEPS;
  float deltaB = (b - oldB) / STEPS;
  // Fade to new colour
  for (float f = 0; f < STEPS; f++) {
    analogWrite(redPin, map((oldR + (deltaR * f)), 0, 255, 0, 1023));
    analogWrite(grnPin, map((oldG + (deltaG * f)), 0, 255, 0, 1023));
    analogWrite(bluPin, map((oldB + (deltaB * f)), 0, 255, 0, 1023));
    delay(2);
  }
  state = 1;
}

//Compute current brightness value
void getV() {
  R = roundf(r/2.55);  //was (r/10.23);
  G = roundf(g/2.55);  //was (g/10.23);
  B = roundf(b/2.55);  //was (b/10.23);
  x = max(R,G);
  V = max(x, B);
}

//For serial debugging only
void showValues() {
  Serial.print("Status on/off: ");
  Serial.println(state);
  Serial.print("RGB color: ");
  Serial.print(r);
  Serial.print(".");
  Serial.print(g);
  Serial.print(".");
  Serial.println(b);
  Serial.print("Hex color: ");
  Serial.println(hexString);
  getV();
  Serial.print("Brightness: ");
  Serial.println(V);
  Serial.println("");
}

void setup() {
  Serial.begin(9600);
  delay(1);
  pinMode(redPin, OUTPUT);
  pinMode(grnPin, OUTPUT);
  pinMode(bluPin, OUTPUT);
  WiFi.mode(WIFI_STA);
  WiFiStart();
  setHex();
}

void loop() {
  WiFiClient client = server.available();

  if (!client) {
    return;
  }

  while(client.connected() && !client.available()) {
    delay(1);
  }

  //Respond on certain Homebridge HTTP requests
  if (client) {
    while (client.connected()) {
      if (client.available()) {
        char c = client.read();
        if (readString.length() < 100) {
          readString += c;
        }
        if (c == '\n') {
          Serial.print("Request: ");
          Serial.println(readString);

          //Send reponse
          client.println("HTTP/1.1 200 OK");
          client.println("Content-Type: text/html");
          client.println();

          //On
          if(readString.indexOf("on") >0) {
            setHex();
            showValues();
            fading = false;
          }

          //Off
          if(readString.indexOf("off") >0) {
            allOff();
            showValues();
            fading = false;
          }

          //Fade
          if(readString.indexOf("fade") >0) {
            fade();
            fading = true;
          }

          //Set color
          if(readString.indexOf("set") >0) {
            hexString = "";
            hexString = (readString.substring(9,15));
            setHex();
            showValues();
            fading = false;
          }

          //Status on/off
          if(readString.indexOf("status") >0) {
          client.println(state);
          }

          //Status color (hex)
          if(readString.indexOf("color") >0) {
          client.println(hexString);
          }

          //Status brightness (%)
          if(readString.indexOf("bright") >0) {
          getV();
          client.println(V);
          }

          delay(1);
          client.stop();
          readString="";
        }
      }
    }
  }
}

void fade() {
  while(fading == true){
    hexString = "000000";
    setHex();
    hexString = "FFFFFF";
    setHex();
    hexString = "FF0000";
    setHex();
    hexString = "008000";
    setHex();
    hexString = "0000FF";
    setHex();
    hexString = "FFFF00";
    setHex();
    hexString = "1E1E1E";
    setHex();
   }
 }

get rid of the client.read() malarky using server.on() to handle your API outside of loop(). 2. move your setHex code to loop, and make enough of the control variables globals so that it performs as expected. 3. have your API modify the control variables, like step increment (which can be zero to pause/halt), current colors, etc.

The variable fading cannot ever change, once you are in that while loop, since your code doesn't do it and you don't use interrupts either (And I don't know, if the library is supporting this). So the Arduino is stuck forever in this loop and will not respond to any interactions but resetting.
There are basically there are 2 different options for you (not counting the usage of a hypothetical interrupt capability of the Wifi library, as I don't know enough about the library):

Adding Wifi code to the while loop: You can just add code, that watches the Wifi interface into the while loop and set the fading variable correspondingly. This is the easiest to program option.
Rewrite your code (especially the fade() function) to be non-blocking, which means it will not block the execution of other code, but will only do something, when it is time to do so, and otherwise return from the function. You can achieve this by using the millis() function, which returns the milliseconds since the last startup/reset to use as a time source. Refer to the BlinkWithoutDelay example of the Arduino IDE. Also you can google for millis(); there are a ton of tutorials out there. When writing non-blocking code you might also want to implement a Finite State Machine (FSM). It's simpler as it sounds. You basically define a simple variable, which sets your current state (for example the states fading, off, specific_color, ...). In your loop() function you make a switch(state_variable){ case statement, where you insert code for every state in it's own case. Outside of the switch statement you can then check the Wifi interface and set the state variable correspondingly. If everything is written non-blocking it should work like a charm.

Thank you. It worked when I made a switch case in the loop then made a new function called handleWifi() to handle the wifi code.


text:
Setting pinMode(pin,input/output) as per user requirement
I am working on arduino IDE and esp8266 nodemcu.
As i am going through the IDE I saw that there is a structure of void loop() and void setup() and all examples in the internet included defining the pinModes within the void setup() block.
I want to make a program where through mqtt or http the user will give input as to what type of device he/she wants to attach to the esp8266, so based on that i will have to set, INPUT/OUTPUT state on the following pins.
Now my initial idea was :
void setup()
{
    connectwifi();
}

void loop()
{
   call_some_function();
}

where call_some_function() will recieve the requirements from user over http. For example he wants a light on pin3, so pinMode(pin3,OUTPUT);
now what I wanted is that,
call the method - call_some_function() whenever the user needs to add an extra device to it, which means initally when we wanted to add 4 lights to esp8266, we will write
pinMode(pin1,OUTPUT);
pinMode(pin2,OUTPUT);
pinMode(pin3,OUTPUT);
pinMode(pin4,OUTPUT);

But now when I have a user defined input, my code will become something like this,
call_some_function()
{
     pin=(user gave me the pin no);
     state=(based on the device the server will send the state i.e IN/OUT);
     pinMode(pin,state);
}

Now my question is , calling this function 4 times and writing pinMode() function 4 times will result in same thing or separate?
Also is this doable, like can i write like this?
I will be calling this function from void loop() instead if void setup(), since I continuously listen for user input,
Cause I cannot find any other way of making user specific input

you can call pinMode anytime

Can u make ur comment as "answer ur question", cuz if furthur discussion turns out to be an answer then i can mark it as an Answer.

Now my question is , calling this function 4 times and writing pinMode() function 4 times will result in same thing or separate? Also is this doable, like can i write like this?

you can call pinMode anytime
And to add something more to pinMode. It is not just some preparation of the pin. It changes things for the connected circuit. Setting to INPUT lets the attached circuit rule. If there is a pull-up circuit the state will be HIGH, if pull-down LOW. INPUT_PULLUP holds the state HIGH but lets the attached circuit to pull it down. pinMode OUTPUT sets the pin LOW.
In two cases for now I use setting a pin to OUTPUT only for the time I want to control the attached circuit and the I set it back to INPUT. In first case I reset an esp8266 with EN pin connected by setting the pin LOW, then I let the external pull-up hold the EN pin HIGH. Second case is amplifier module for the tone() function. I set the pin to INPUT after tone() otherwise it catches noise.

pinMode() is usually called from setup() because in most cases, the pin mode remains the same throughout the run. Sometimes there is a reason to change it during the run, such as in your example, and you can call pinMode() at whenever is the appropriate time to do that.

Ok, ty.. Juaraj gave the correct answer first so I will mark his answer.


text:
String input to character array
I am in between of project where i am getting string like "hello world" via Bluetooth to arduino I want to list this string into individual character so that I can call any of the character when required, this is not working i am getting only zeros in serial monitor
please suggest what i am doing wrong
char s;
int k[10];

void setup () {
  Serial.begin(9600);
}
void loop () {
  if (Serial.available() > 0) {
    s = Serial.read();
  }
  k[10] = s;
  for (int x = 0; x < 10; x++) {
    Serial.println(k[x]);
    delay(200);
  }
}

There are a few problems with your code sample:

You check for Serial.available()>0, but then assume/grab only one character:
if (Serial.available() > 0) {
  s = Serial.read();
}

It is possible that the serial receive buffer has more than one byte waiting, but you only capture one.

k[10] = s;

You assign the captured character to the last element of the byte array, regardless of all else. This presents two main problems

A C-style string must be terminated with a null character ('\0'), and you have immediately put real data in the position that should contain the terminating byte.
There is no possible way that bytes 0-9 can ever have any data written to them by this code.

Your code assumes that the entire string exists in k[] every time through loop(). Instead, you should assume that it might take hundreds or thousands of times through loop() just to finish receiving your string. The input string should have some kind of end-of-string marker like a newline ('\n') or carriage-return ('\r') (or both) so that your program can look for that and know when the input is fully received.
Below is a simple program that receives a string. Note that it has a portion labeled for when to process the recieved data. That block of code is only entered once a newline and/or carriage return are received.
#DEFINE MAX_INPUT 90

char inputBuffer[MAX_INPUT+1]; // Handles up to 90 bytes in a c-style string, with a null character termination.

void setup()
{
  Serial.begin(115200); // initialization
  inputBuffer[0] = '\0'; //Initialize string to emtpy.
  Serial.println("Begin:");
}

void loop() {

  if (Serial.available()>0)
  {
    char input = Serial.read();
    static int s_len; // static variables default to 0
    if (s_len>=MAX_INPUT) {
      // Have received already the maximum number of characters
      // Ignore all new input until line termination occurs
    } else if (input != '\n' && input != '\r') {
      inputBuffer[s_len++] = input;
    } else {
      // Have received a LF or CR character

      // INSERT YOUR CODE HERE TO PROCESS THE RECEIVED DATA //
      // YOU COULD COPY TO A NEW VARIABLE WITH strncpy() OR //
      // SET A FLAG TO SAY TO START SOME OTHER TASK         //
      Serial.print("RECEIVED MSG: ");
      Serial.println(inputBuffer);

      memset(inputBuffer, 0, sizeof(inputBuffer));
      s_len = 0;             // Reset input buffer here if you
                             // have already copied the data.
                             // If you don't reset here, then
                             // you can't start receiving more
                             // serial port data. This is your
                             // 'software' serial buffer, contrast
                             // with the hardware serial buffer.
    }
  }
}


text:
State machine waiting for input state isn't getting input states for unknown reason
I have a state machine program used to monitor sensors and activate relays that has been used and adapted on multiple machines and it typically performs exactly as needed. I am attempting to adapt the program to include an additional relay and two sensors and I can't figure out why the program won't update the states for two of the sensors added. All other sensors update and the program runs as intended until the program enters the state to check that the sensors have been interrupted. The final machine will use photo interrupters but I have bread boarded the circuit with both the sensors as well as using switches to attempt to debug the system.
Everything else works flawlessly on the breadboard and the program runs great save for the part where the program is waiting for the state of the sensors to read "BOTH_RSENSORS_LOW" on line 304 of the program. I have the serial monitor running to check the status of "RsensorState" that is updated every time line 302 runs. Within the main loop, "RsensorState" should be getting updated on line 174 which is supposed to be updated on line 437 where it should be returning the state based on the sensor inputs. The serial monitor shows no change to the state while changing the input on the pins attached to it. I have tested other pins as well in case they are shorted somehow to HIGH. I have the exact same sensors working fine to return the state of sensors 1 and 2. I have gone over the code and don't know what is missing. Every other block works great and as wanted. Perhaps I have a small syntax error that I am simply not seeing. I have attempted to lay out the program in as easy a format as I can and build the steps of the logic in blocks that are easy for me to navigate.
Board: Arduino DUE
Software: Arduino IDE 1.8.5
Includes the libraries Bounce2.h and LiquidCrystal.h
The device is designed to use a system of two buttons that need to be pressed within a specified time of each other. If at any point they are released they should turn off the relays and wait til both of them are released completely before being able to proceed again. The program is set up in 10 states to perform the functions of the machine.
CLEAR_SENSORS Turns off relay2 attached to a physical stop designed to align the part so the finished part can be slid through the machine and then checks to see if sensors 1 and 2 are not blocked meaning the part has been removed so the stop can then be be put back in place. Sensors 1 and two are on either side of the stop so that the stop will not be activated and hit the part as it is getting pushed through.
CHECK_SENSORS Turns back on relays and waits until a part is put back in and the first sensor can see that a part is in place. When it sees a part it moves to the next state.
WAIT_FOR_BOTH_LOW Checks the two safety buttons to be sure they are both released and the operator has not tried to short one out or has stuck something in the switch to hold it on. This is returned to any time the switches fail the timeout parameters.
WAIT_FOR_BUTTON Waits for a button to be pressed and goes into the next step.
ONE_PUSHED_WAIT_FOR_OTHER_BUTTON looks for the other button to be pressed within the specified time frame. If it is not then the program goes back to waiting for both to be released.
FINAL_CHECK checks to make sure the part has not been removed. If it has it goes back to waiting for the part to be put back in place and for all buttons to be released.
LOWER_RAILS checks to make sure the buttons are still being held and if so lowers an aligning and holding railing attached to Relay3
CHECK_RAIL_SENSORS checks 2 sensors to be sure they are both blocked and the railing is fully down. They are to act as limit sensors. This is the step the program gets stuck on.
SAFETY_WINDOW is a small time frame the machine waits until it turns on the relays and then after that time frame turns on relay1
RELAY_ON turns off the main relay1 and the holding relay3 if the buttons are released and turns them off after the time frame for the relays to run has expired. It then goes to the beginning where it waits for the part to be removed.
When I bypass the CHECK_RAIL_SENSORS step the whole things works flawlessly. I am stumped why that particular part isn't working. From what I can tell it has to do with the RsensorState not getting updated as expected like the other sensors are. sensorState updates and functions exactly as expected so I am not sure why RsensorState does not. Am I making a syntax error I am not aware of? I have gone through it a hundred times and maybe I am just not seeing it. All the components have been tested and function as expected. Here is the code:
// This sketch reads inputs from two buttons and a sensor to turns on 2 relays
// RelayPin2 is engaged until the end of the first relay's cycle
// It requires that both buttons be pressed within a certain time of each other and held
// A relay pin is then turned on for a specified period of time
// RelayPin3 turns on and is verified by Sensors 3 and 4
// RelayPin2 is turned off after the first relay pin has completed it's cycle
// When the sensor is clear, RelayPin2 is turned on again
// Both buttons must then be released again for another cycle to begin
// A state machine is used, only to make it more clear what is going on.
// Used with an Arduino DUE on Arduino 1.8.5 IDE
// Original sketch found on https://arduino.stackexchange.com/questions/45584/state-machine-logic-problem-with-added-states-monitoring-safety-switches/
// Uses the Bounce2 library: https://github.com/thomasfredericks/Bounce2
//
// When a button is pressed, the input turns HIGH.
//
// Normally only one 'enum' is used for the state, that controls the code.
// This sketch has also a 'enum' for the buttons, which is called the input state.
// define the different states for this sketch.
// An 'enum' is like a number of #define with increasing numbers.

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

// initialize the library with the numbers of the interface pins
LiquidCrystal lcd(7, 8, 9, 10, 11, 12);

// Logical states of the main state machine
enum
{
  CLEAR_SENSORS,
  CHECK_SENSORS,
  WAIT_FOR_BOTH_LOW,
  WAIT_FOR_BUTTON,
  ONE_PUSHED_WAIT_FOR_OTHER_BUTTON,
  FINAL_CHECK,
  LOWER_RAILS,
  CHECK_RAIL_SENSORS,
  SAFETY_WINDOW,
  RELAY_ON,
} state;       // an 'enum' is its own type.

// define the different input states.
enum
{
  BOTH_BUTTONS_LOW,      // no buttons are pressed.
  BOTH_BUTTONS_HIGH,     // both buttons are pressed.
  ONE_BUTTON_HIGH,       // probably one of the buttons is pressed.
};

// Define the different sensor states

enum
{
  BOTH_SENSORS_HIGH, // Both Sensors are not blocked
  BOTH_SENSORS_LOW, // Both Sensors are blocked
  SENSOR1_HIGH_SENSOR2_LOW,  // Sensor 1 is not blocked but Sensor 2 is
  SENSOR2_HIGH_SENSOR1_LOW,   // Sensor 2 is not blocked but Sensor 1 is
};

// Define the different rail sensor states

enum
{
  BOTH_RSENSORS_HIGH, // Both sensors are not blocked
  BOTH_RSENSORS_LOW,  // Both rail sensors are blocked
  SENSOR3_HIGH_SENSOR4_LOW,  // Sensor 3 is not blocked Sensor 4 is
  SENSOR4_HIGH_SENSOR3_LOW,  // Sensor 4 is not blocked Sensor 3 is
};

const int ButtonPin1 = 2;
const int ButtonPin2 = 3;
const int Sensor1Pin = 6;
const int Sensor2Pin = 24;
const int Sensor3Pin = 30;
const int Sensor4Pin = 31;
const int RelayPin = 5;
const int RelayPin2 = 13;
const int RelayPin3 = 34;
const int IndicatorPin = 4;
const int IndicatorPin2 = 25;
const int IndicatorPin3 = 26;
const int IndicatorPin4 = 27;
const int IndicatorPin5 = 35;

// The 'previousMillis' is exclusively for the state machine portion only.
// It is used for different software timers in different states.
// That is okay, because within the state machine the states are seperated from each other.
// Funtions outside the state machine would require a separate timer.
unsigned long previousMillis;

const unsigned long RelayOnTime = 1750;    // Length of time for relay
const unsigned long TimeFrameForSecondButton = 300; // Length of time to allow two pushes
const unsigned long PushSafetyWindow = 300; // Safety Delay after push to be sure part is in place

// Counters for the number of failed relay triggers and successful cycles.
// They can probably be normal integers as well.
unsigned long failed = 0;
unsigned long success = 0;

// Instantiate Bounce objects
Bounce debouncer1 = Bounce();
Bounce debouncer2 = Bounce();
Bounce debouncer3 = Bounce();
Bounce debouncer4 = Bounce();
Bounce debouncer5 = Bounce();
Bounce debouncer6 = Bounce();

void setup()
{
  lcd.begin(16, 2);
  lcd.print("On");
  Serial.begin(9600);
  Serial.println("Unit Online");

// Set up first button
  pinMode(ButtonPin1, INPUT);
  debouncer1.attach(ButtonPin1);
  debouncer1.interval(15); //Debounce time

// Set up second button
  pinMode(ButtonPin2, INPUT);
  debouncer2.attach(ButtonPin2);
  debouncer2.interval(15); //Debounce time

// Set up Sensor1
  pinMode (Sensor1Pin, INPUT);
  debouncer3.attach(Sensor1Pin);
  debouncer3.interval(5); //Debounce time

// Set up Sensor2
  pinMode (Sensor2Pin, INPUT);
  debouncer4.attach(Sensor2Pin);
  debouncer4.interval(5); //Debounce time

  // Set up Sensor3
  pinMode (Sensor3Pin, INPUT);
  debouncer5.attach(Sensor3Pin);
  debouncer5.interval(5); //Debounce time

// Set up Sensor4
  pinMode (Sensor4Pin, INPUT);
  debouncer6.attach(Sensor4Pin);
  debouncer6.interval(5); //Debounce time

  pinMode(RelayPin, OUTPUT);      // OUTPUT to Relay
  pinMode(RelayPin2, OUTPUT);     // OUTPUT to Second Relay
  pinMode(RelayPin3, OUTPUT);     // OUTPUT to Third Relay
  pinMode(IndicatorPin, OUTPUT);  // OUTPUT to Indicator LED
  pinMode(IndicatorPin2, OUTPUT); // OUTPUT to Second Indicator LED
  pinMode(IndicatorPin3, OUTPUT); // OUTPUT to Third Indicator LED
  pinMode(IndicatorPin4, OUTPUT); // OUTPUT to Fourth Indicator LED
  pinMode(IndicatorPin5, OUTPUT); // OUTPUT to Fifth Indicator LED

  Serial.println("Going to CLEAR_SENSORS state");

// Set initial state of the machine
  state = CLEAR_SENSORS;
}

void loop()
{

  unsigned long currentMillis = millis();

// Update the Bounce instances
  debouncer1.update();
  debouncer2.update();
  debouncer3.update();
  debouncer4.update();

  int inputState = getInputState();
  int sensorState = getSensorState();
  int RsensorState = getRSensorState();

// Process the data in a state machine.
// The output part is also in the state machine.
  switch(state)
  {
    case CLEAR_SENSORS:
       // Turn off relay2 and wait til everything is clear
        lcd.setCursor(0,0);
        lcd.print("Clear Machine");
        digitalWrite(RelayPin2, LOW);     // Turn OFF Relay 2
        digitalWrite(IndicatorPin2, LOW); // Turn OFF IndicatorPin 2
        digitalWrite(IndicatorPin4, HIGH); // Turn ON IndicatorPin 4
      if(sensorState == BOTH_SENSORS_HIGH)
      {
        // Prepare to go to the next state
        Serial.println("Machine Clear Going to CHECK_SENSORS state");
        state = CHECK_SENSORS;
      }
      break;
    case CHECK_SENSORS:
      // Turn on Relay 2 and then verify the sensor is engaged before proceeding
        lcd.setCursor(0,0);
        lcd.print("Load Barricade");
        digitalWrite(RelayPin2, HIGH);  // Turn on Relay 2
        digitalWrite(IndicatorPin2, HIGH); // Turn ON IndicatorPin 2
        digitalWrite(IndicatorPin3, HIGH); // Turn ON IndicatorPin 3
        digitalWrite(IndicatorPin4, LOW); // Turn OFF IndicatorPin 4
      if(sensorState == SENSOR2_HIGH_SENSOR1_LOW)
      {
        // Prepare to go to the next state
        Serial.println("Machine Clear Going to WAIT_FOR_BOTH_LOW state");
        state = WAIT_FOR_BOTH_LOW;
      }
      break;
    case WAIT_FOR_BOTH_LOW:
      // Both buttons must be released to be able to continue.
        lcd.setCursor(0,0);
        lcd.print("Wait For Release");
        digitalWrite(IndicatorPin3, LOW); // Turn OFF IndicatorPin 3
      if(inputState == BOTH_BUTTONS_LOW)
      {
        // Prepare to go to the next state.
        Serial.println("Going to WAIT_FOR_BUTTON state");
        state = WAIT_FOR_BUTTON;
      }
      break;
    case WAIT_FOR_BUTTON:
// This is the state when everything is idle and no buttons are pressed.
// Normally both buttons are released.
// Waiting for the first button to be pressed.
// Both buttons could be pressed at the same time !
        lcd.setCursor(0,0);
        lcd.print("Engage Buttons   ");
      if(inputState == ONE_BUTTON_HIGH || inputState == BOTH_BUTTONS_HIGH)
      {
// At least one button is pressed.
// Prepare to go to the next state.
// Start a timer, because there is a timeout.
        Serial.println("Going to ONE_PUSHED_WAIT_FOR_OTHER_BUTTON state");
        previousMillis = currentMillis;
        state = ONE_PUSHED_WAIT_FOR_OTHER_BUTTON;
       }
      break;
    case ONE_PUSHED_WAIT_FOR_OTHER_BUTTON:
        lcd.setCursor(0,0);
        lcd.print("Wait for Other");
      if(inputState == BOTH_BUTTONS_LOW)
      {
// The button was released. That's not what we want.
// Return to the state to wait for both off.
        Serial.println("Going to WAIT_FOR_BOTH_LOW state");
        state = WAIT_FOR_BOTH_LOW;
      }
      else if(currentMillis - previousMillis >= TimeFrameForSecondButton)
      {
// The timeout has ended.
// The second button was not pushed after the first button
// within the timeout. That's too bad.
        Serial.println("Too Long Going to WAIT_FOR_BOTH_LOW state");
        state = WAIT_FOR_BOTH_LOW;
      }
      else if(inputState == BOTH_BUTTONS_HIGH)
      {
// The timeout has not ended and is still running.
// And now both buttons are pressed.
// We can continue.
// Start the timer for the SAFETY_WINDOW state.
        Serial.println("Going to FINAL_CHECK state");
        previousMillis = currentMillis;
        state = FINAL_CHECK;
      }
      break;
    case FINAL_CHECK:
      if(sensorState != SENSOR2_HIGH_SENSOR1_LOW)
      // Check to make sure the barricade hasn't been removed
      {
        // Prepare to go to the next state
        Serial.println("Machine Clear Going to CHECK_SENSORS state");
        state = CHECK_SENSORS;
      }
      else if(sensorState == SENSOR2_HIGH_SENSOR1_LOW)
      {
        Serial.println("Going to LOWER_RAILS state");
        state = LOWER_RAILS;
      }
      break;
    case LOWER_RAILS:
        lcd.setCursor(0,0);
        lcd.print("Lowering Rails  ");
      if(inputState != BOTH_BUTTONS_HIGH)
      // Check to be sure safety buttons are held and if not wait for another try
      {
        Serial.println("Going to WAIT_FOR_BOTH_LOW state from LOWER_RAILS");
        state = WAIT_FOR_BOTH_LOW;
      }
      else
      // If buttons 1 and 2 are still held proceed to turn on Relay 3 and onto the sensor check
      {
        digitalWrite(RelayPin3, HIGH);  // Turn ON RelayPin3
        digitalWrite(IndicatorPin5, HIGH); // Turn ON IndicatorPin5
        Serial.println("Going to CHECK_RAIL_SENSORS state");
        state = CHECK_RAIL_SENSORS;
      }
      break;
    case CHECK_RAIL_SENSORS:
       lcd.setCursor(0,0);
       lcd.print("Checking Rails  ");
       Serial.println(RsensorState);
       // Wait until the sensors are blocked to move into the next state
      if(RsensorState == BOTH_RSENSORS_LOW)
      {
        Serial.println("Going to SAFETY_WINDOW state");
        state = SAFETY_WINDOW;
      }
      break;
    case SAFETY_WINDOW:
        lcd.setCursor(0,0);
        lcd.print("Wait a second");
      if(inputState != BOTH_BUTTONS_HIGH)
      {
// During the safety time window, a button was released.
// Return to idle.
        Serial.println("Going to WAIT_FOR_BOTH_LOW state");
        digitalWrite(RelayPin, LOW);  // Turn OFF RelayPin
        digitalWrite(IndicatorPin, LOW); // Turn OFF IndicatorPin
        digitalWrite(RelayPin3, LOW);  // Turn OFF RelayPin3
        digitalWrite(IndicatorPin5, LOW); // Turn OFF IndicatorPin5
        state = WAIT_FOR_BOTH_LOW;
      }
      else if(currentMillis - previousMillis >= PushSafetyWindow)
      {
// The buttons are still pressed.
// The time window has reached the end.
// Prepare to go to the next state.
        Serial.println("Going to RELAY_ON state");
        previousMillis = currentMillis;
        digitalWrite(RelayPin, HIGH);  // Turn ON RelayPin
        digitalWrite(IndicatorPin, HIGH); // Turn ON IndicatorPin
        state = RELAY_ON;
      }
      break;
    case RELAY_ON:
        lcd.setCursor(0,0);
        lcd.print("Relay Engaged   ");
      if(inputState != BOTH_BUTTONS_HIGH)
      {
// One of the buttons was released.
// Stop the relay and return to idle.
// Although the relay was triggered, it was not succesful.
        failed++;
        Serial.print("Failed=");
        Serial.println(failed);
        Serial.println("Going to WAIT_FOR_BOTH_LOW state");
        digitalWrite( RelayPin, LOW);  // Turn Off RelayPin
        digitalWrite(IndicatorPin, LOW); // Turn Off IndicatorPin
        digitalWrite(RelayPin3, LOW);  // Turn OFF RelayPin3
        digitalWrite(IndicatorPin5, LOW); // Turn OFF IndicatorPin5
        state = WAIT_FOR_BOTH_LOW;
      }
      else if(currentMillis - previousMillis >= RelayOnTime)
      {
        // Everyting was okay.
        // The buttons are still pressed.
        // It was complete and succesful.
        // It is time to turn off the relay and return to idle.
        success++;
        Serial.print("Success=");
        Serial.println(success);
        Serial.println("Going to CLEAR_SENSORS state");
        lcd.setCursor(0,1);
        lcd.print("Cycles ");
        lcd.print(success);
        digitalWrite(RelayPin, LOW);  // Turn Off RelayPin
        digitalWrite(IndicatorPin, LOW); // Turn Off IndicatorPin
        digitalWrite(RelayPin3, LOW);  // Turn OFF RelayPin3
        digitalWrite(IndicatorPin5, LOW); // Turn OFF IndicatorPin5
        state = CLEAR_SENSORS;
      }
      break;
    default:
        Serial.println("Error, unknown state");
      break;
    }
}

// This function returns the input state.
// There is no StateChangeDetection, because a state machine is used.
  int getInputState()
{
  int returnInputState;

// Read the debounce state and create an input state according to the 'enum' values.
  int value1 = debouncer1.read();
  int value2 = debouncer2.read();

    if(value1 == LOW && value2 == LOW)
    {
      returnInputState = BOTH_BUTTONS_LOW;
    }
    else if(value1 == HIGH && value2 == HIGH)
    {
      returnInputState = BOTH_BUTTONS_HIGH;
    }
    else
    {
    // Not both on, not both off, so it must be something else.
    returnInputState = ONE_BUTTON_HIGH;
    }

  return(returnInputState);
}

 // This function is to return the state of sensors 1 and 2
  int getSensorState()
{
  int returnSensorState;

// Read the sensor states and create an input state
  int value3 = debouncer3.read();
  int value4 = debouncer4.read();

    if(value3 == HIGH && value4 == HIGH)
    {
      returnSensorState = BOTH_SENSORS_HIGH;
    }
    else if(value3 == HIGH && value4 == LOW)
    {
      returnSensorState = SENSOR1_HIGH_SENSOR2_LOW;
    }
    else if(value4 == HIGH && value3 == LOW)
    {
      returnSensorState = SENSOR2_HIGH_SENSOR1_LOW;
    }
    else
    {
      returnSensorState = BOTH_SENSORS_LOW;
    }
  return(returnSensorState);
}

 // This function is to return the state of Sensors 3 and 4
  int getRSensorState()
{
  int returnRSensorState;

// Read the sensor states and create an input state
  int value5 = debouncer5.read();
  int value6 = debouncer6.read();

  if(value5 == LOW && value6 == LOW)
    {
      returnRSensorState = BOTH_RSENSORS_LOW;
    }
    else if(value5 == HIGH && value6 == LOW)
    {
      returnRSensorState = SENSOR3_HIGH_SENSOR4_LOW;
    }
    else if(value6 == HIGH && value5 == LOW)
    {
      returnRSensorState = SENSOR4_HIGH_SENSOR3_LOW;
    }
    else
    {
      returnRSensorState = BOTH_RSENSORS_HIGH;
    }
  return(returnRSensorState);
}

The part giving me trouble is this state:
case CHECK_RAIL_SENSORS:
   lcd.setCursor(0,0);
   lcd.print("Checking Rails  ");
   Serial.println(RsensorState);
   // Wait until the sensors are blocked to move into the next state
  if(RsensorState == BOTH_RSENSORS_LOW)
  {
    Serial.println("Going to SAFETY_WINDOW state");
    state = SAFETY_WINDOW;
  }
  break;

It may be something to do with how the sensor state is acquired. I am using Bounce2 to debounce the inputs.
 // This function is to return the state of Sensors 3 and 4
  int getRSensorState()
{

  int returnRSensorState;

// Read the sensor states and create an input state
  int value5 = debouncer5.read();
  int value6 = debouncer6.read();

  if(value5 == LOW && value6 == LOW)
    {
      returnRSensorState = BOTH_RSENSORS_LOW;
    }
    else if(value5 == HIGH && value6 == LOW)
    {
      returnRSensorState = SENSOR3_HIGH_SENSOR4_LOW;
    }
    else if(value6 == HIGH && value5 == LOW)
    {
      returnRSensorState = SENSOR4_HIGH_SENSOR3_LOW;
    }
    else
    {
      returnRSensorState = BOTH_RSENSORS_HIGH;
    }
  return(returnRSensorState);
}

Any input is greatly appreciated! Please let me know if more clarification is necessary.
Edit 07/12/18
IF you use this code don't forget to update this section for it to work! The complete, corrected code is too large to post:
// Update the Bounce instances
  debouncer1.update();
  debouncer2.update();
  debouncer3.update();
  debouncer4.update();
  debouncer5.update();
  debouncer6.update();

Your debouncer update section:
// Update the Bounce instances
  debouncer1.update();
  debouncer2.update();
  debouncer3.update();
  debouncer4.update();

is missing debouncer5.update(); and debouncer6.update();. It is required to call update() once per loop() to ensure the object is up to date.

Oh man I can't believe I missed that! Thank you I was going cross eyed trying to figure out what I missed! It works great now!


text:
How to filter or eliminate earths magnetic field readings around 3D Magnetic sensor?
Im using the SparkFun MAG3110 3D sensor:
https://www.sparkfun.com/products/12670
My application is essentially to make a contactless "magnetic joystick" using a local magnet for accurate and constant 3D position sensing in x, y, x planes of a local magnet, exactly like in this video (skip to 1:06):
https://www.youtube.com/watch?v=CO6y6bjFfmY
The magnet I'm using is constant, so i'm trying to figure out a way to remove the earths magnetic field noise around the sensor so it cannot interfere with the sensors readings as if the earths magnetic field was virtually not present.
I've already written code that takes about 50 samples in each plane (x,y,z) and takes the average of each of the planes and outputs those readings minus the average offset values (Ex: Serial.print(x-xavg), Serial.print(y-yavg), Serial.print(z-zavg)). I did this to basically "zero out" the earths magnetic field, like zeroing a weight scale.
That wasn't really effective and results were not anywhere near constant after introducing and removing the local magnet, over and over again.
I've considered:

a low pass filter
sensor fusion using my gyroscope/accelerometer module
(I know that sensor fusion is usually used to calibrate the Magnometer to be a more accurate compass, but is there anyway to use this technique to  eliminate the earths magnetic field?)
using data from http://www.magnetic-declination.com/ to tie into my calculations to offset the readings
Using an electromagnet module to output the earths magnetic field inverted continuously in an attempt to cancel out the earths magnetic field
trying to find a whole new sensor completely that does not have a low enough sensitivity to even detect earths magnetic field

So my questions are:

Is there any way to do this?
Are any of my considerations practical or possible?
Are there even any 3d magnetic sensors on the market that do NOT pick up the earths magnetic field? - I've contacted SparkFun, Arrow, ST, and other companies about this exact question and never really get a sure answer on this question specifically?
if not, how was this man in the video able to reduce noise around his sensor? - He shows visually that his sensor is starting to filter out noise, saying that he's using an "adaptive averages" algorithm and links to some code, but I was unable to see/find that and don't understand how he is doing that?

One option is a magnetic gradiometer.  This consists of two magnetometers, which are placed at different distances from the local magnet (one close, one far).  You subtract the readings to eliminate dependence on the earth's magnetic field, on the (fairly good) assumption that the earth's field does not change over the distance between the sensors.

Earth magnetic field is pretty constant. In your measurements it will show up as an offset that you could subtract, but of course it will change if the sensor rotates.
Whatever measurement noise you see certainly doesnt' come from Earth. Either your setup is close to a local source of magnetic radiation (inductors, wires with high alternating current), or your sensor picks up noise from its power supply. Put your sensor away from high currents, power it with batteries and see how much noise you'll get in that case.

This can also be used for calculations if you wanted to be precise as much as possible. Magnetic Field Calculator

If you're already subtracting the mean of several samples of the ambient field, what's left should be noise, and much lower than your signal (the field due to your handheld magnet).
If you're trying to get a level of precision at the same order of magnitude as the noise, you'll need a larger 'N' (sample size), perhaps of both the ambient and of the desired signal, or apply even more stringent statistical techniques.
But I doubt that's what the experimenter in the video was doing. It's more likely he was close enough the sensor and with a strong enough magnet, that the noise was insignificant by comparison. He was using a rare-earth magnet - are you? Those typically have a stronger field that a more common ceramic or steel one. If not, you may need to use yours at a smaller distance from the sensor to get a similar signal to noise ratio.


text:
hx711 and load cell read out 0 for calibration
I'm using this tutorial from Sparkfun
https://learn.sparkfun.com/tutorials/load-cell-amplifier-hx711-breakout-hookup-guide
And using THEIR code. The only difference is I added a delay so it wouldn't write a reading 10x a second.
QUESTION:
How do I get nonzeros?
#include "HX711.h"
#define DOUT  3
#define CLK  2
HX711 scale(DOUT, CLK);
float calibration_factor = -7050; //-7050 worked for my 440lb max scale setup
void setup() {
  Serial.begin(9600);
  Serial.println("HX711 calibration sketch");
  Serial.println("Remove all weight from scale");
  Serial.println("After readings begin, place known weight on scale");
  Serial.println("Press + or a to increase calibration factor");
  Serial.println("Press - or z to decrease calibration factor");
  scale.set_scale();
  scale.tare(); //Reset the scale to 0
  long zero_factor = scale.read_average(); //Get a baseline reading
  Serial.print("Zero factor: "); //This can be used to remove the need to tare the scale. Useful in permanent scale projects.
  Serial.println(zero_factor);
}
void loop() {
  scale.set_scale(calibration_factor); //Adjust to this calibration factor
  Serial.print("Reading: ");
  Serial.print(scale.get_units(), 20);
  Serial.print(" lbs"); //Change this to kg and re-adjust the calibration factor if you follow SI units like a sane person
  Serial.print(" calibration_factor: ");
  Serial.print(calibration_factor);
  Serial.println();
  if(Serial.available())
  {
    char temp = Serial.read();
    if(temp == '+' || temp == 'a')
      calibration_factor += 10;
    else if(temp == '-' || temp == 'z')
      calibration_factor -= 10;
  }
  delay(2000);
}

NOTE: I did not yet solder anything because I don't want to mess up the soldering and have to buy new cells and wait a week for shipping. So I placed pinheads in the amplifier and connected with m/f jumpers, and used alligator clips to connect to the loose wires.

what does this mean? ... How do I get nonzeros?

picture #1 shows the type of loadcell .... why did you include the other two pictures? ... they show nothing useful

@jsotola thank you so much for your insight, but just because YOU don't know something, it's not nice to say my images are useless. What they show is that I did not have the VDD connected to 5v, and that was actually the problem. And a "nonzero" is something other than 0.

they show is that I did not have the VDD connected to 5v ... actually, they do not show that .... the pictures are not a clear view of the wire routing

i thought about your comment .... it's not nice to say my images are useless  and but just because YOU don't know something  .... you are correct, i have no idea how everything is connected ... you are the only one that knows how it is connected .... your pictures do not show the connections in a clear way, therefore they are useless .... it has nothing to do with being nice or not nice, but it has to do with the quality of the information that you presented

@jsotola, well the SparkFun folks were able to tell from the exact same pictures, so clearly you are not qualified to make such an assessment.

Only VCC was connected to 5v. Had to add a breadboard to connect VDD as well.
(The kind folks at Sparkfun were able to help me out)


text:
Button Switch arduino
I'm trying to use my button as a switch (the led goes on after I push the button and the led goes off when I push the button again). I know I have the right circuit, because I also used a code from the internet, which looks really like mine. But my code doesn't work. The led doesn't go on. Does anyone know what is wrong with my code?
I have found the mistake now. The last 2 lines of the code were in the if statement block. But why doesn't it work then?
Here is the code i have written:
int ledPin = 8;
int buttonPin = 4;

int ledState = HIGH;      // the current state of the LED
int previousState = LOW;  // the previous state of the button
int readingState ;        // the current state of the button

void setup() {
   // put your setup code here, to run once:
pinMode(ledPin, OUTPUT);
pinMode(buttonPin, INPUT);
}

void loop() {
  // put your main code here, to run repeatedly:
readingState = digitalRead(buttonPin);

if(readingState == HIGH && previousState == LOW){
  if (ledState == HIGH){
    ledState = LOW;
  }

  else{
    ledState = HIGH;
    }

digitalWrite(ledPin, ledState);
previousState = readingState;

}
}

and doing blink (using a time based trigger) works?

Yes I can get the LED blinking

Why don't you use the internal pull-up resistor? Did you use one externally? If not, your input is floating and the state is undefined.

I did use a pull up resistor

If you don't update previousState on each iteration, your outermost if statement cannot be true if previousState is high, if that's your question.

I have found the mistake now. The last 2 lines of the code were in the if statement block. But why doesn't it work then?

previousState is set to high, and is never set again, so your if statement will never execute again because previousState is always set to high.
Moving the last line out of the if block sets previousState at every loop, and can then have a value other than HIGH, and then your if condition can be satisfied.
The penultimate line could stay in the if, or be lifted out, logically it shouldn't matter.


text:
Which platform is better to debug Arduino memory problems? Linux or Windows?
I am developing a product. I developed every module in the firmware individually. Now I am integrating them but getting memory issues. I am not able to see how the memory is allocated inside the MCU during the runtime.
Can Linux help me debug issues better, using its command than Windows platform?
Thanks in advance.

As I remember the Arduino IDE is the same at Linux or Windows. Doesn't the IDE show you, how much memory is used, at compile time? Or are you using dynamic allocation? (You should ditch those anyway if possible, due to heap fragmentation)

Ide is showing me 54% dynamic allocation leaving 46% for stack I have no track for the stack that where it collapses. I ditched calloc, malloc because of fragmentation in heap. My programme runs nice for some loops but after some time it stucks. I want to track every byte of memory in every function & pin point where memory is getting leaked & program gets stucked.

#include <MemoryFree.h> Serial.println(freeMemory());

Why do you think that you have memory issues? It could be a number of things. The most likely problem is writing beyond a buffer on the stack or a function that returns a pointer to a buffer that was declared in that function on the stack.

46% of RAM for the stack is plenty, unless you are doing recursion or loads of stack allocation.

@jot for some loops My device works fine when I see it in the Serial Monitor but
when I make it a standalone device it stops pinging or device hangs after some time.  what may be the other causes of getting program stucked other than memory issue..? one you told that writing beyond a buffer but I checked I have not any issue like this in the code but please tell other causes of programme crash.

@EdgarBonet I am actually doing a lot of stack allocation in my final firmware structure. Actually its irreplaceable :(  .

@juraj thanks for your kind reply. I tried MemoryFree.h but the problem is this library is a little buggy for ex. while(1){Char c=0;Serial.println(freeMemory());} declares variable c again & again into a function which should decrease stack memory present but it shows the same value.

Your “proof” that MemoryFree is bugged is flawed. Declaring a variable again and again does not increase memory usage: the compiler is not as dumb as you seem to believe.

@bandejiya, by the language definition the variable exists until end of the block. so at } it is removed from stack. in reality the compiler optimizes it and puts it on the stack of the parent block

@Juraj: The compiler doesn't put it anywhere: as it is an unused variable, it gets optimized away.

@EdgarBonet, true. what I wrote would be true if it was used :-)

Hmm..! point noted, Thank you all so much..! :)

I simply burned the code written below but it is showing me free memory as 2267 bytes please somebody clarify that how in a Atmega328pu can have 2267 bytes free with overall capacity of 2048 bytes, The code is :----#include <MemoryFree.h>
void setup()
{Serial.begin(9600); Serial.println(freeMemory(), DEC);}
void loop()
{}

The operating system is irrelevant. If you want to debug the target you need a debugger and a debugging environment. That means a proper hardware debugger interface, not an Arduino's USB serial port, and a proper IDE like Atmel Studio not the Arduino IDE.  All are available for both Linux and Windows.

I have developed firmware on arduino IDE..! will'nt  it will take a lot more efforts to change the IDE..? please suggest any other way if possible to achieve MVP.

The Arduino IDE is very easy to program in but almost impossible to debug in. The best you can do is use Serial.print to display information. You cannot do real debugging in the Arduino environment. It's not a professional tool.


text:
Variable that holds the users input doesn't empty itself, so the program only works once
This code seems to function, but only works once before I need to press the reset button. Otherwise, it repeats the same error message. It might have something to do with emptying the String variable.
// A program that will allow a user to turn ON one of several LED's
// using if...else statements.

String pinAsk="Please select which pin you would like to supply power to:";

// A different coloured LED will be attached to each pin number.
int Red=14; // This one would be the A0 Header on the Arduino
int Yellow=15; // A1
int Green=16; // A2
int Blue=17; // A3
int Purple=18; // A4
int Violet=19; // A5

int invalidColorRed;
int invalidColorYellow;
int invalidColorGreen;
int invalidColorBlue;
int invalidColorPurple;
int invalidColorViolet;
// If the user didn't select any of these colours, then all these variables will
// be given a 1. This triggers an if...else condition that prints out a message,
// to say that they didn't enter a valid input.

String inputColor;
 // The String variable can store integers as well as other characters

String activePin1="The ";
// The users input is printed out between these.
String activePin2=" LED is now active";

int Volts=102; // The 102 tells the Arduino to output 2+ (Two volts)

void setup() {
 Serial.begin(9600);
 Serial.println("Colour Selection");
 Serial.println("");

 pinMode(Red,OUTPUT);
 pinMode(Yellow,OUTPUT);
 pinMode(Green,OUTPUT);
 pinMode(Blue,OUTPUT);
 pinMode(Purple,OUTPUT);
 pinMode(Violet,OUTPUT);
}

void loop() {
 Serial.println(pinAsk);
 Serial.println("Red = A0 (14)");
// These describe the available pins and their colors.
 Serial.println("Yellow = A1 (15)");
 Serial.println("Green = A2 (16)");
 Serial.println("Blue = A3 (17)");
 Serial.println("Purple = A4 (18)");
 Serial.println("Violet = A5 (19)");

  while (Serial.available()==0) { } // Wait for user to respond

 inputColor=Serial.readString(); // Store their input into an empty variable

// The following segment checks whether the user has selected to turn ON
// the Red LED.

 if (inputColor=="14") analogWrite(Red,Volts);
 // The String variable can also store integers as well as other characters
 else if (inputColor=="A0") { analogWrite(Red,Volts); }
 else if (inputColor=="Red") { analogWrite(Red,Volts); }
 else if (inputColor=="red") { analogWrite(Red,Volts); }
// User may only use lower-case letters.
  // The "equal equal" sign == doesn't assign a new value.
  // It will test whether a number or string is the same
// as described at the end of the equal's sign.

 else { analogWrite(Red,LOW); }
// If the users input, stored within inputColor, isn’t "14", "A0", "Red",
// or "red" then this Red LED will be turned off.

 if (inputColor!="14" && inputColor!="A0" && inputColor!="Red" && inputColor!="red") { invalidColorRed=1; }

// The exclamation mark or bang ! is a NOT operator.
// A "bang equal" sign != is placed after a variable, such as inputPin!=
// to say that the value must NOT be equal to "14". If the expression is true
// (The condition is fulfilled), then a 1 is given to invalidColorRed.

// The AND operator, shown as a double ampersand && combines
// all the conditions into the same expression. By putting this operator `
// between them, it tells the Arduino that all the variables must NOT be
// any of the values described.

// Each colour has its own invalidColor variable.
// If the user does not enter any of the valid inputs
// (Which means the LED is off), a 1 will be assigned to this colors
// invalidColor variable.

// If all these invalidColor variables have a value of 1, it means all
// the LED’s are off. This can be made into another condition that causes
// the Arduino to read an expression that tells the user that they haven’t
// entered a proper input and to try again.

// Checking to see if the user has opted to turn on the Yellow LED.
 if (inputColor=="15") analogWrite(Yellow,Volts);
 else if (inputColor=="A1" || "Yellow" || "yellow") { analogWrite(Yellow,Volts); }
// The OR || operator combines the Lower-case and Upper-case letters in
// the same expression. A space between the operator and variables is not
// necessary, but improves readability. Also, a single pair of quotation
// marks "" can encase the conditions if || is being used.
 else { analogWrite(Yellow,LOW); }

 if (inputColor!="15" && inputColor!="A1" && inputColor!="Yellow" && inputColor!="yellow") { invalidColorYellow=1; }

// Checking to see if the user has opted to turn on the Green LED.
 if (inputColor=="16") analogWrite(Green,Volts);
 else if (inputColor=="A2") { analogWrite(Green,Volts); }
 else if (inputColor=="Green") { analogWrite(Green,Volts); }
 else if (inputColor=="green") { analogWrite(Green,Volts); }
 else { analogWrite(Green,LOW); }

 if (inputColor!="16" && inputColor!="A2" && inputColor!="Green" && inputColor!="green") { invalidColorGreen=1; }

// Checking to see if the user has opted to turn on the Blue LED.
 if (inputColor=="17") analogWrite(Blue,Volts);
 else if (inputColor=="A3") { analogWrite(Blue,Volts); }
 else if (inputColor=="Blue") { analogWrite(Blue,Volts); }
 else if (inputColor=="blue") { analogWrite(Blue,Volts); }
 else { analogWrite(Blue,LOW); }

 if (inputColor!="17" && inputColor!="A2" && inputColor!="Blue" && inputColor!="blue") { invalidColorBlue=1; }

// Checking to see if the user has opted to turn on the Purple LED.
 if (inputColor=="18") analogWrite(Purple,Volts);
 else if (inputColor=="A4") { analogWrite(Purple,Volts); }
 else if (inputColor=="Purple") { analogWrite(Purple,Volts); }
 else if (inputColor=="purple") { analogWrite(Purple,Volts); }
 else { analogWrite(Purple,LOW); }

 if (inputColor!="18" && inputColor!="A4" && inputColor!="Purple" && inputColor!="purple") { invalidColorPurple=1; }

// Checking to see if the user has opted to turn on the Violet LED.
 if (inputColor=="19") analogWrite(Violet,Volts);
 else if (inputColor=="A5") { analogWrite(Violet,Volts); }
 else if (inputColor=="Violet") { analogWrite(Violet,Volts); }
 else if (inputColor=="violet") { analogWrite(Violet,Volts); }
 else { analogWrite(Violet,LOW); }

 if (inputColor!="19" && inputColor!="A5" && inputColor!="Violet" && inputColor!="violet") { invalidColorViolet=1; }

 if (invalidColorRed==1 && invalidColorYellow==1 && invalidColorGreen==1 && invalidColorBlue==1 && invalidColorViolet==1)
 {
  // This if statement is asking "Are all invalidPin variables equal to 1?"
  // In other words, "Are all the LED's off?"
  Serial.println("");
  Serial.println("That is not a valid option, please try again");
  Serial.println(""); }
  else if (invalidColorRed==0 || invalidColorYellow==0 || invalidColorGreen==0 || invalidColorBlue==0 || invalidColorViolet==0)
  {
  // If the user entered a valid input for at least one LED,
  // this message will play instead.
  Serial.println("");
  Serial.print(activePin1);
  Serial.print(inputColor); // The users input is printed out here.
  Serial.println(activePin2);
  Serial.println(""); }

  inputColor=""; // Shouldn't this empty the variable?
}

Can someone tell me whats wrong?

Could you post the output you get from the console?

If a valid answer is entered, such as blue, it will print out 'The blue LED is is now active'. After that, it will repeat the first message, asking the user to select a color from the list presented. Even if the user gives an acceptable answer, it will read out the error message 'That is not a valid option, please try again'. The reset button needs to be pressed before the user can enter another color.

You set the invalidColor___ to 1, but you never reset it. So if you set the blue color, all variables invalidColor___ except for invalidColorBlue are set to 1. Then if in the next loop you set the red color, invalidColorBlueis also set to1, and now all invalidColor___s are set to 1and you get the error message. You need to set them back to0` at the beginning of the loop.

Without looking deeply into your code, this is wrong:
if (inputColor=="A1" || "Yellow" || "yellow")

You need to repeat what you are testing against, ie.
if (inputColor=="A1" || inputColor=="Yellow" || inputColor=="yellow")

You might want to use the auto-format tool (Ctrl+T). Putting a lot of stuff in one line is just confusing.


text:
Arduino based IR remote control - Transmission issue
I created a circuit of a 25 key IR remote controller for my RuneAudio device. The device is a standalone ATmega328P-PU running at 3V (2 AAA batteries) with 8 MHz internal clock. The circuit has 5 rows and 5 columns and uses Arduino keypad library. The code is mostly a copy of Nick Gammon's code (http://www.gammon.com.au/forum/?id=11497&reply=4#reply4), with slight modification for my purpose.
Following is the circuit (R1=1K, R2=10K, R3=62 Ohm):

Following is the code I am using:
#include <Keypad.h>
#include <avr/sleep.h>
#include <avr/power.h>
#include <IRremote.h>

const byte ROWS = 5;
const byte COLS = 5;
byte keynum;

char keys[ROWS][COLS] =
{
  {'E', 'D', 'C', 'B', 'A'},
  {'J', 'I', 'H', 'G', 'F'},
  {'O', 'N', 'M', 'L', 'K'},
  {'T', 'S', 'R', 'Q', 'P'},
  {'Y', 'X', 'W', 'V', 'U'}
};

byte rowPins[ROWS] = {9, 10, 11, 12, 13}; // Keypad row pins
byte colPins[COLS] = {4, 5, 6, 7, 8};     // Keypad column pins

unsigned long IRCode[25] =  {0xB54A38C7, 0xB54A30CF, 0xB54AE191, 0xB54ADCDD, 0xB54AD6C3, 0xB54AE5ED, 0xB54A50AF, 0xB54A9867, 0xB54AB04F, 0xB54A48B7, 0xB54AD02F, 0xB54AFCF7, 0xB54AF56C, 0xB54AEFEE, 0xB54AEAA0, 0xB54A02FD, 0xB54B176F, 0xB54B100D, 0xB54B08F6, 0xB54B031D, 0xB54A42BD, 0xB54AC23D, 0xB54A1AE5, 0xB54A7887, 0xB54A827D};

// Number of items in an array
#define NUMITEMS(arg) ((unsigned int) (sizeof (arg) / sizeof (arg [0])))

// IR setup (NEC remote)
const byte IRledPin = 3;
const int NumBits = 32;

// Define
Keypad kpd = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );
IRsend irsend;

// turn off interrupts until we are ready
ISR (PCINT0_vect)
  {
  PCICR = 0;  // cancel pin change interrupts
  } // end of ISR (PCINT0_vect)

ISR (PCINT1_vect)
  {
  PCICR = 0;  // cancel pin change interrupts
  } // end of ISR (PCINT1_vect)

ISR (PCINT2_vect)
  {
  PCICR = 0;  // cancel pin change interrupts
  } // end of ISR (PCINT2_vect)

void setup ()
{
  pinMode (IRledPin, OUTPUT);

  // Pin change interrupt masks (See list on Nick Gammons original code)
  PCMSK0 |= bit (PCINT1);   // Pin 9
  PCMSK0 |= bit (PCINT2);   // Pin 10
  PCMSK0 |= bit (PCINT3);   // Pin 11
  PCMSK0 |= bit (PCINT4);   // Pin 12
  PCMSK0 |= bit (PCINT5);   // Pin 13
  Serial.begin(9600);
}

void reconfigurePins ()
{
Serial.print("1 Reconfig pins");
Serial.println("");
  byte i;
  for (i = 0; i < NUMITEMS (colPins); i++)
  {
    pinMode (colPins [i], OUTPUT);
    digitalWrite (colPins [i], HIGH);
  }

  for (i = 0; i < NUMITEMS (rowPins); i++)
    {
    pinMode (rowPins [i], INPUT_PULLUP);
    }   // end of for each row
Serial.print("2 DONE Reconfig pins");
Serial.println("");
  }  // end of reconfigurePins

void goToSleep ()
{
Serial.print("3 inside SLEEP");
Serial.println("");

  // Set up keypress detection
  byte i;
  for (i = 0; i < NUMITEMS (colPins); i++)
  {
    pinMode (colPins [i], OUTPUT);
    digitalWrite (colPins [i], LOW);
  }

  for (i = 0; i < NUMITEMS (rowPins); i++)
  {
    pinMode (rowPins [i], INPUT_PULLUP);
  }  // end of for each row

  // Check no pins pressed (otherwise wake on a key release)
  for (i = 0; i < NUMITEMS (rowPins); i++)
  {
    if (digitalRead (rowPins [i]) == LOW)
    {
  Serial.print("ROW LOW: ");
  Serial.print(rowPins [i]);
Serial.println("");
      reconfigurePins ();
      return;
    }
  }

  // Overcome any debounce delays built into the keypad library
  delay (10);

  // At this point, pressing a key should connect the high in the row to the
  // to the low in the column and trigger a pin change
Serial.print("4 Going to SLEEP");
Serial.println("");

  set_sleep_mode (SLEEP_MODE_PWR_DOWN);
  sleep_enable();

Serial.print("5 AWAKE");
Serial.println("");

  byte old_ADCSRA = ADCSRA;
  // Disable ADC to save power
  ADCSRA = 0;

  power_all_disable ();  // turn off various modules

  PCIFR  |= bit (PCIF0) | bit (PCIF1) | bit (PCIF2);   // clear any outstanding interrupts
  PCICR  |= bit (PCIE0) | bit (PCIE1) | bit (PCIE2);   // enable pin change interrupts

  // Turn off brown-out enable in software
  MCUCR = bit (BODS) | bit (BODSE);
  MCUCR = bit (BODS);
  sleep_cpu ();

  // Cancel sleep as a precaution
  sleep_disable();
  power_all_enable ();   // enable modules again
  ADCSRA = old_ADCSRA;   // re-enable ADC conversion

  // Put keypad pins back how they are expected to be
  reconfigurePins ();
Serial.print("6 Leaving SLEEP");
Serial.println("");

}

void loop ()
{

  byte key =  kpd.getKey();
  if (!key)
  {
Serial.print("CALLING SLEEP");
Serial.println("");

    // Sleep if no key is pressed
    goToSleep ();
    return;
 Serial.print("After RETURN");
Serial.println("");

  }

  // Subtract ASCII value of first key value to obtain HEX array argument
  keynum = key - 'A';
Serial.print("SENDING IR.....................................................................................");
Serial.println("");

  // sendNEC(unsigned long data, int nbits);
  irsend.sendNEC(IRCode[keynum], NumBits);
Serial.print(IRCode[keynum]);
Serial.println("");

}

The sketch compiles and uploads just fine. It detects key presses and sends out IR signals. But it misses around half of the key presses. I am testing on a breadboard using a single key - R1C5 (S5 in the schematic).
I must admit that despite spending a lot of time on ATmega328 datasheet and Nick's blogs on power saving, I am not able to fully understand the power saving features due to my not-so-mature skills and the complexity of overall project (Raspberry Pi based rune audio + TDA7439 based tone controller + ATmega based power switch for Pi + 2channel Audio amplifier + this IR remote).
I added a few serial prints to check what is happening. The serial outs seem to be out of sync and last message before sleep is "CALLING SLEEP" whereas I expected it to be "4 Going to SLEEP". And adding serial print mysteriously reduces the number of misses.
Following is the serial output, just after power on and a single key press:
EP
3 inside SLEEP
4 Going to SLEEP
5 AWAKE
1 Reconfig pins
2 DONE Reconfig pins
6 Leaving SLEEP
SENDING IR.....................................................................................
3041540295
CALLING SLEEP
3 inside SLEEP
ROW LOW: 9
1 Reconfig pins
2 DONE Reconfig

The following happens after multiple key presses:
CALLING SLEEP
3 inside SLEEP
ROW LOW: 9
1 Reconfig pins
2 DONE Reconfig pins
SENDING IR.....................................................................................
3041540295
CALLING SLEEP
3 inside SLEEP
ROW LOW: 9
1 Reconfig pins
2 DONE Reconfig pins
CALLING SLEEP
3 inside SLEEP
ROW LOW: 9
1 Reconfig pins
2 DONE Reconfig
CALLING SLEEP
3 inside SLEEP
4 Going to SLEEP
5 AWAKE
1 Reconfig pins
2 DONE Reconfig pins
6 Leaving SLEEP
CALLING SLEEP
3 inside SLEEP
ROW LOW: 9
1 Reconfig pins
2 DONE Reconfig
CALLING SLEEP
3 inside SLEEP
4 Going to SLEEP
5 AWAKE
1 Reconfig pins
2 DONE Reconfig pins
6 Leaving
CALLING SLEEP
3 inside SLEEP
4 Going to SLEEP
5 AWAKE
1 Reconfig pins
2 DONE Reconfig pins
6 Leaving
CALLING SLEEP
3 inside SLEEP
4 Going to SLEEP
5 AWAKE
1 Reconfig pins
2 DONE Reconfig pins
6 Leaving
CALLING SLEEP
3 inside SLEEP
4 Going to SLEEP
5 AWAKE
1 Reconfig pins
2 DONE Reconfig pins
6 Leaving
CALLING SLEEP
3 inside SLEEP
4 Going to SLEEP
5 AWAKE
1 Reconfig pins
2 DONE Reconfig pins
6 Leaving SLEEP
CALLING SLEEP
3 inside SLEEP
ROW LOW: 9
1 Reconfig pins
2 DONE Reconfig pins
SENDING IR.....................................................................................
3041540295
CALLING SLEEP
3 inside SLEEP
ROW LOW: 9
1 Reconfig pins
2 DONE Reconfig

It would be of great help if someone could show me the light here.

Ok. Replaced long serial print strings with single digits where these stand for:
1= 1 Reconfig pins
2= 2 DONE Reconfig pins
3= 3 inside SLEEP
4= ROW LOW=
5= 4 Going to SLEEP
6= 5 AWAKE
7= 6 Leaving SLEEP
8= CALLING SLEEP
.....= SENDING IR
I see where it is failing.  Now getting the following serial out:
6
1
2
7
8
3
49
1
2
8
3
49
1
2
8
3
49
1
2
8
3
49

So the program wakes on keypress (6), then reconfigures the pins (1,2), leaves the sleep function (7) enaters the main (8). Here byte key =  kpd.getKey() DOES NOT detect a keypress and calls sleep again (3). Sleep DOES detect a low row 9 (4-9).
After this it gets stuck in a loop of main and sleep functions till key press is over. For now the problem seems to be with kpd.getKey().

I added a few serial prints to check what is happening. The serial outs seem to be out of sync and last message before sleep is "CALLING SLEEP" whereas I expected it to be "4 Going to SLEEP".

Printing to Serial doesn't send data to your computer. It just adds that data to a TX buffer, and then an interrupt sends each character one byte at a time.
Your prints are happening, but aren't being sent from the queue before the MCU goes to sleep.
You should add
Serial.flush();

before actually going to sleep to ensure that all data from the TX buffer has been sent. That way your messages will actually be meaningful.
Also if you send more than 64 bytes of data through Serial in a short space of time it will block and wait for some data to be sent out of the TX buffer. The buffer is only 64 bytes in size, so if there is no room left it has to wait for the interrupt.  That waiting slows your entire sketch down and can affect the way the sketch operates.  A bit like quantum physics - the act of observing the operation of the sketch changes the operation of the sketch.


text:
How to connect both MicroSD module and MPU9235 power in an arduino
I'm really new at electronics and wiring, so please be kind. Coding is my stuff, but I'm trying to learn something here.
I'm working with a project to store the movements of a skateboard through a MPU 9235 and the idea is to save the output of the sensor to a MicroSD.
I have both components and acquired a LiPO 3.7v 400mAh to take everything off the protoboard and attach at the bottom of the skateboard.
The code is working, everything code wise is working ok, but I'm strugging to understand how to power both MicroSD module and MPU9235, since both have the VCC pin (VDD in some versions).
The current connections are replicated in Fritzing. Only replacing Arduino Uno for an Arduino Nano, and the MPU 6050 from the picture for a MPU9235.

My first thought was to connect the LiPo battery into VIN and GND pins of Nano. From there I believe that I can wire up the 3V3 output directly to VCC from MPU9235.
But what about the MicroSD module?
How would I power its VCC pin since I have no 3V3 pin left? I read that it's not right to use a digital pin as power output.
How can I connect two components that needs power from external source?

VIN takes 6-12v and it sends it through the on board regulator - so that is the best way to power the nano.
If you take a wire from the 3v3 pin and split it (solder two wires to one) then you will have two 3v3 feeds to wire to your two devices.  This will be the same as you have to do for the Gnd connections, back to the Nano.
Does that make sense? (if not I'll try and draw you something).

Yes it does. It didn't make sense before because I did think that splitting a wire would provide half of 3.3v. Thing is, the board will always try to provide 3.3v for the output wire and if I ended up having too many devices connected to it, to this 3.3v output wire, the battery life will be low. Is that correct?

"The wire" will supply 3.3v to all devices connected, but the board will have to 'split' the maximum current that it can supply between the devices.  Each device will get UP TO the maximum mA it requires, but that may not be enough for it to functions.  I THINK you battery will drain faster, the more devices you have but you can get 10AH+ lipo batteries that aren't much bigger than a AA battery.